File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.207: download - view: text, annotated - select for diffs
Mon Nov 24 16:53:26 2008 UTC (15 years, 5 months ago) by jms
Branches: MAIN
CVS tags: HEAD
POD changes

    1: # The LearningOnline Network with CAPA
    2: # various response type definitons response definition
    3: #
    4: # $Id: response.pm,v 1.207 2008/11/24 16:53:26 jms Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::response;
   30: use strict;
   31: use Apache::lonlocal;
   32: use Apache::lonnet;
   33: use Apache::lonmaxima();
   34: 
   35: BEGIN {
   36:     &Apache::lonxml::register('Apache::response',('responseparam','parameter','dataresponse','customresponse','mathresponse'));
   37: }
   38: 
   39: sub start_response {
   40:     my ($parstack,$safeeval)=@_;
   41:     my $id = &Apache::lonxml::get_id($parstack,$safeeval);
   42:     if ($#Apache::inputtags::import > -1) {
   43: 	&Apache::lonxml::debug("Turning :$id: into");
   44: 	$id = join('_',@Apache::inputtags::import).'_'.$id;
   45: 	&Apache::lonxml::debug("New  :$id:");
   46:     }
   47:     push (@Apache::inputtags::response,$id);
   48:     push (@Apache::inputtags::responselist,$id);
   49:     @Apache::inputtags::inputlist=();
   50:     if ($Apache::inputtags::part eq '' && 
   51: 	!$Apache::lonhomework::ignore_response_errors) {
   52: 	&Apache::lonxml::error(&HTML::Entities::encode(&mt("Found a <*response> outside of a <part> in a <part>ed problem"),'<>&"'));
   53:     }
   54:     if ($Apache::inputtags::response_with_no_part &&
   55: 	$Apache::inputtags::part ne '0') {
   56: 	&Apache::lonxml::error(&HTML::Entities::encode(&mt("<*response>s are both inside of <part> and outside of <part>, this is not a valid problem, errors in grading may occur."),'<>&"').'<br />');
   57:     }
   58:     if ($Apache::inputtags::part eq '0') {
   59: 	$Apache::inputtags::response_with_no_part=1;
   60:     }
   61:     return $id;
   62: }
   63: 
   64: sub end_response {
   65:     #pop @Apache::inputtags::response;
   66:     @Apache::inputtags::inputlist=();
   67:     return '';
   68: }
   69: 
   70: sub start_hintresponse {
   71:     my ($parstack,$safeeval)=@_;
   72:     my $id = &Apache::lonxml::get_id($parstack,$safeeval);
   73:     push (@Apache::inputtags::hint,$id);
   74:     push (@Apache::inputtags::hintlist,$id);
   75:     push (@Apache::inputtags::paramstack,[%Apache::inputtags::params]);
   76:     return $id;
   77: }
   78: 
   79: sub end_hintresponse {
   80:     pop @Apache::inputtags::hint;
   81:     if (defined($Apache::inputtags::paramstack[-1])) {
   82: 	%Apache::inputtags::params=
   83: 	    @{ pop(@Apache::inputtags::paramstack) };
   84:     }
   85:     return '';
   86: }
   87: 
   88: my @randomseeds;
   89: sub pushrandomnumber {
   90:     my $rand_alg=&Apache::lonnet::get_rand_alg();
   91:     if (!$rand_alg || $rand_alg eq '32bit' || $rand_alg eq '64bit' ||
   92: 	$rand_alg eq '64bit2') {
   93: 	# do nothing
   94:     } else {
   95: 	my @seed=&Math::Random::random_get_seed();
   96: 	push(@randomseeds,\@seed);
   97:     }
   98:     &Apache::response::setrandomnumber(@_);
   99: }
  100: sub poprandomnumber {
  101:     my $rand_alg=&Apache::lonnet::get_rand_alg();
  102:     if (!$rand_alg || $rand_alg eq '32bit' || $rand_alg eq '64bit' ||
  103: 	$rand_alg eq '64bit2') {
  104: 	return;
  105:     }
  106:     my $seed=pop(@randomseeds);
  107:     if ($seed) {
  108: 	&Math::Random::random_set_seed(@$seed);
  109:     } else {
  110: 	&Apache::lonxml::error("Unable to restore random algorithm.");
  111:     }
  112: }
  113: 
  114: sub setrandomnumber {
  115:     my ($ignore_id2) = @_;
  116:     my $rndseed;
  117:     $rndseed=&Apache::structuretags::setup_rndseed();
  118:     if (!defined($rndseed)) { $rndseed=&Apache::lonnet::rndseed(); }
  119:     &Apache::lonxml::debug("randseed $rndseed");
  120:     #  $rndseed=unpack("%32i",$rndseed);
  121:     my $rand_alg=&Apache::lonnet::get_rand_alg();
  122:     my ($rndmod,$rndmod2);
  123: 
  124:     my ($id1,$id2,$shift_amt);
  125:     if ($Apache::lonhomework::parsing_a_problem) {
  126: 	$id1=$Apache::inputtags::part;
  127: 	if (defined($Apache::inputtags::response[-1])) {
  128: 	    $id2=$Apache::inputtags::response[-1];
  129: 	}
  130: 	$shift_amt=scalar(@Apache::inputtags::responselist);
  131:     } elsif ($Apache::lonhomework::parsing_a_task) {
  132: 	$id1=&Apache::bridgetask::get_dim_id();
  133: 	if (!$ignore_id2 && ref($Apache::bridgetask::instance{$id1})) {
  134: 	    $id2=$Apache::bridgetask::instance{$id1}[-1];
  135: 	    $shift_amt=scalar(@{$Apache::bridgetask::instance{$id1}});
  136: 	} else {
  137: 	    $shift_amt=0;
  138: 	}
  139:     } 
  140:     &Apache::lonxml::debug("id1: $id1, id2: $id2, shift_amt: $shift_amt");
  141:     if (!$rand_alg || $rand_alg eq '32bit' || $rand_alg eq '64bit' ||
  142: 	$rand_alg eq '64bit2') {
  143: 	$rndmod=(&Apache::lonnet::numval($id1) << 10);
  144: 	if (defined($id2)) { $rndmod+=&Apache::lonnet::numval($id2); }
  145:     } elsif ($rand_alg eq '64bit3') {
  146: 	$rndmod=(&Apache::lonnet::numval2($id1) << 10);
  147: 	if (defined($id2)) { $rndmod+=&Apache::lonnet::numval2($id2); }
  148:     } elsif ($rand_alg eq '64bit4') {
  149: 	my $shift=(4*$shift_amt)%30;
  150: 	$rndmod=(&Apache::lonnet::numval3($id1) << (($shift+15)%30));
  151: 	if (defined($id2)) {
  152: 	    $rndmod+=(&Apache::lonnet::numval3($id2) << $shift );
  153: 	}
  154:     } else {
  155: 	($rndmod,$rndmod2)=&Apache::lonnet::digest("$id1,$id2");
  156:     }
  157: 
  158:     if ($rndseed =~/([,:])/) {
  159: 	my $char=$1;
  160: 	use integer;
  161: 	my ($num1,$num2)=split(/\Q$char\E/,$rndseed);
  162: 	$num1+=$rndmod;
  163: 	$num2+= ((defined($rndmod2)) ? $rndmod2 : $rndmod);
  164: 	if($Apache::lonnet::_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
  165: 	$rndseed=$num1.$char.$num2;
  166:     } else {
  167: 	$rndseed+=$rndmod;
  168: 	if($Apache::lonnet::_64bit) {
  169: 	    use integer;
  170: 	    $rndseed=(($rndseed<<32)>>32);
  171: 	}
  172:     }
  173:     &Apache::lonxml::debug("randseed $rndmod $rndseed");
  174:     &Apache::lonnet::setup_random_from_rndseed($rndseed);
  175:     return '';
  176: }
  177: 
  178: sub meta_parameter_write {
  179:     my ($name,$type,$default,$display)=@_;
  180:     my $partref=$Apache::inputtags::part;
  181:     my $result='<parameter part="'.$Apache::inputtags::part.'"';
  182:     if (defined($Apache::inputtags::response[-1])) {
  183: 	$result.=            ' id="'.$Apache::inputtags::response[-1].'"';
  184: 	$partref.='_'.$Apache::inputtags::response[-1];
  185:     }
  186:     $result.=            ' name="'.$name.'"'.
  187:                          ' type="'.$type.'"'.
  188: (defined($default)?' default="'.$default.'"':'').
  189: (defined($display)?' display="'.$display.' [Part: '.$partref.']"':'')
  190:              .'></parameter>'
  191:              ."\n";
  192:     return $result;
  193: }
  194: 
  195: sub meta_package_write {
  196:     my $name=shift;
  197:     my $result = '<parameter part="'.$Apache::inputtags::part.'"';
  198:     if(defined($Apache::inputtags::response[-1])) {
  199: 	$result.= ' id="'.$Apache::inputtags::response[-1].'"';
  200:     }
  201:     $result.=' package="'.$name.'"></parameter>'."\n";
  202:     return $result;
  203: }
  204: 
  205: sub meta_stores_write {
  206:     my ($name,$type,$display)=@_;
  207:     my $partref=$Apache::inputtags::part;
  208:     my $result = '<stores part="'.$Apache::inputtags::part.'"';
  209:     if (defined($Apache::inputtags::response[-1])) {
  210: 	$result.=           ' id="'.$Apache::inputtags::response[-1].'"';
  211: 	$partref.='_'.$Apache::inputtags::response[-1];
  212:     }	
  213:     $result.=          ' name="'.$name.'"'.
  214:                        ' type="'.$type.'"'.
  215: 	            ' display="'.$display.' [Part: '.$partref.']"'.
  216: 		      "></stores>\n";
  217: }
  218: 
  219: sub mandatory_part_meta {
  220: =pod
  221: 
  222: =item meta_part_order
  223: 
  224: Autogenerate metadata for mandatory
  225: input (from RAT or lonparmset) and 
  226: output (to lonspreadsheet)
  227: of each part
  228: #
  229:     return
  230:    &meta_parameter_write('opendate','date_start','',
  231:                          'Opening Date').
  232:    &meta_parameter_write('duedate','date_end','',
  233:                          'Due Date').
  234:    &meta_parameter_write('answerdate','date_start','',
  235:                          'Show Answer Date').
  236:    &meta_parameter_write('weight','int_zeropos','',
  237:                          'Available Points').
  238:    &meta_parameter_write('maxtries','int_pos','',
  239:                          'Maximum Number of Tries').
  240: 	&meta_package_write('part').
  241:         &meta_stores_write('solved','string',
  242: 			   'Problem Status').
  243:         &meta_stores_write('tries','int_zeropos',
  244: 			   'Number of Attempts').
  245:         &meta_stores_write('awarded','float',
  246: 			   'Partial Credit Factor');
  247: 
  248: Note: responseid-specific data 'submission' and 'awarddetail'
  249: not available to spreadsheet -> skip here
  250: 
  251: =cut
  252: 
  253: }
  254: 
  255: sub meta_part_order {
  256:     if (@Apache::inputtags::partlist) {
  257: 	my @parts=@Apache::inputtags::partlist;
  258: 	shift(@parts);
  259: 	return '<partorder>'.join(',',@parts).'</partorder>'."\n";
  260:     } else {
  261: 	return '<partorder>0</partorder>'."\n";
  262:     }
  263: }
  264: 
  265: sub meta_response_order {
  266:     if (@Apache::inputtags::responselist) {
  267: 	return '<responseorder>'.join(',',@Apache::inputtags::responselist).
  268: 	    '</responseorder>'."\n";
  269:     }
  270: }
  271: 
  272: sub check_for_previous {
  273:     my ($curresponse,$partid,$id,$last) = @_;
  274:     my %previous;
  275:     $previous{'used'} = 0;
  276:     foreach my $key (sort(keys(%Apache::lonhomework::history))) {
  277: 	if ($key =~ /resource\.$partid\.$id\.submission$/) {
  278: 	    if ( $last && $key =~ /^(\d+):/ ) {
  279: 		next if ($1 >= $last);
  280: 	    }
  281: 	    &Apache::lonxml::debug("Trying $key");
  282: 	    my $pastresponse=$Apache::lonhomework::history{$key};
  283: 	    if ($pastresponse eq $curresponse) {
  284: 		$previous{'used'} = 1;
  285: 		my $history;
  286: 		if ( $key =~ /^(\d+):/ ) {
  287: 		    $history=$1;
  288: 		    $previous{'award'} = $Apache::lonhomework::history{"$history:resource.$partid.$id.awarddetail"};
  289: 		    $previous{'last'}='0';
  290: 		    push(@{ $previous{'version'} },$history);
  291: 		} else {
  292: 		    $previous{'award'} = $Apache::lonhomework::history{"resource.$partid.$id.awarddetail"};
  293: 		    $previous{'last'}='1';
  294: 		}
  295: 		if (! $previous{'award'} ) { $previous{'award'} = 'UNKNOWN';	}
  296: 		&Apache::lonxml::debug("got a match :$previous{'award'}:$previous{'used'}:");
  297: 	    }
  298: 	}
  299:     }
  300:     &Apache::lonhomework::showhash(%previous);
  301:     return %previous;
  302: }
  303: 
  304: sub handle_previous {
  305:     my ($previous,$ad)=@_;
  306:     if ($$previous{'used'} && ($$previous{'award'} eq $ad) ) {
  307: 	if ($$previous{'last'}) {
  308: 	    push(@Apache::inputtags::previous,'PREVIOUSLY_LAST');
  309: 	    push(@Apache::inputtags::previous_version,$$previous{'version'});
  310: 	} elsif ($Apache::lonhomework::type ne 'survey') {
  311: 	    push(@Apache::inputtags::previous,'PREVIOUSLY_USED');
  312: 	    push(@Apache::inputtags::previous_version,$$previous{'version'});
  313: 	}
  314:     }
  315: }
  316: 
  317: sub view_or_modify {
  318:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
  319:     my $myself=0;
  320:     if ( ($name eq $env{'user.name'}) && ($domain eq $env{'user.domain'}) ) {
  321: 	$myself=1;
  322:     }
  323:     my $vgr=&Apache::lonnet::allowed('vgr',$courseid);
  324:     my $mgr=&Apache::lonnet::allowed('vgr',$courseid);
  325:     if ($mgr) { return "M"; }
  326:     if ($vgr) { return "V"; }
  327:     if ($myself) { return "V"; }
  328:     return '';
  329: }
  330: 
  331: sub start_dataresponse {
  332:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  333:     my $id = &Apache::response::start_response($parstack,$safeeval);
  334:     my $result;
  335:     if ($target eq 'web') {
  336: 	$result = $token->[2]->{'display'}.':';
  337:     } elsif ($target eq 'meta') {
  338: 	$result = &Apache::response::meta_stores_write($token->[2]->{'name'},
  339: 						       $token->[2]->{'type'},
  340: 						       $token->[2]->{'display'});
  341: 	$result .= &Apache::response::meta_package_write('dataresponse');
  342:     }
  343:     return $result;
  344: }
  345: 
  346: sub end_dataresponse {
  347:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  348:     my $result;
  349:     if ( $target eq 'web' ) {
  350:     } elsif ($target eq 'grade' ) {
  351: 	if ( defined $env{'form.submitted'}) {
  352: 	    my ($symb,$courseid,$domain,$name)=&Apache::lonnet::whichuser();
  353: 	    my $allowed=&Apache::lonnet::allowed('mgr',$courseid);
  354: 	    if ($allowed) {
  355: 		&Apache::response::setup_params('dataresponse',$safeeval);
  356: 		my $partid = $Apache::inputtags::part;
  357: 		my $id = $Apache::inputtags::response['-1'];
  358: 		my $response = $env{'form.HWVAL_'.$id};
  359: 		my $name = &Apache::lonxml::get_param('name',$parstack,$safeeval);
  360: 		if ( $response =~ /[^\s]/) {
  361: 		    $Apache::lonhomework::results{"resource.$partid.$id.$name"}=$response;
  362: 		    $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
  363: 		    $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}='SUBMITTED';
  364: 		}
  365: 	    } else {
  366: 		$result='Not Permitted to change values.'
  367: 	    }
  368: 	}
  369:     }
  370:     &Apache::response::end_response;
  371:     return $result;
  372: }
  373: 
  374: sub start_customresponse {
  375:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  376:     my $id = &Apache::response::start_response($parstack,$safeeval);
  377:     push(@Apache::lonxml::namespace,'customresponse');
  378:     my $result;
  379:     @Apache::response::custom_answer=();
  380:     @Apache::response::custom_answer_type=();
  381:     &Apache::lonxml::register('Apache::response',('answer'));
  382:     if ($target eq 'web') {
  383:   	if (  &Apache::response::show_answer() ) {
  384: 	    my $answer = &Apache::lonxml::get_param('answerdisplay',$parstack,
  385: 						   $safeeval);
  386: 	    $Apache::inputtags::answertxt{$id}=[$answer];
  387: 	}
  388:     } elsif ($target eq 'edit') {
  389: 	$result.=&Apache::edit::tag_start($target,$token);
  390: 	$result.=&Apache::edit::text_arg('String to display for answer:',
  391: 					 'answerdisplay',$token);
  392: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
  393:     } elsif ($target eq 'modified') {
  394: 	my $constructtag;
  395: 	$constructtag=&Apache::edit::get_new_args($token,$parstack,
  396: 						  $safeeval,'answerdisplay');
  397: 	if ($constructtag) {
  398: 	    $result = &Apache::edit::rebuild_tag($token);
  399: 	}
  400:     } elsif ($target eq 'answer' || $target eq 'grade') {
  401: 	&Apache::response::reset_params();
  402:     } elsif ($target eq 'meta') {
  403: 	$result .= &Apache::response::meta_package_write('customresponse');
  404:     }
  405:     return $result;
  406: }
  407: 
  408: sub end_customresponse {
  409:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  410:     my $result;
  411:     my $part=$Apache::inputtags::part;
  412:     my $id=$Apache::inputtags::response[-1];
  413:     if ( $target eq 'grade' && &Apache::response::submitted() ) {
  414: 	my $response = &Apache::response::getresponse();
  415: 	if ($Apache::lonhomework::type eq 'exam' ||
  416: 	    &Apache::response::submitted('scantron')) {
  417: 	    &Apache::response::scored_response($part,$id);
  418: 	} elsif ( $response =~ /[^\s]/ && 
  419: 		  $Apache::response::custom_answer_type[-1] eq 'loncapa/perl') {
  420: 	    if (!$Apache::lonxml::default_homework_loaded) {
  421: 		&Apache::lonxml::default_homework_load($safeeval);
  422: 	    }
  423: 	    my %previous = &Apache::response::check_for_previous($response,
  424: 								 $part,$id);
  425: 	    $Apache::lonhomework::results{"resource.$part.$id.submission"}=
  426: 		$response;
  427: 	    my $error;
  428: 	    ${$safeeval->varglob('LONCAPA::customresponse_submission')}=
  429: 		$response;
  430: 	    
  431: 	    my $award = &Apache::run::run('{ my $submission=$LONCAPA::customresponse_submission;'.$Apache::response::custom_answer[-1].'}',$safeeval);
  432: 	    if (!&Apache::inputtags::valid_award($award)) {
  433: 		$error = $award;
  434: 		$award = 'ERROR';
  435: 	    }
  436: 	    &Apache::response::handle_previous(\%previous,$award);
  437: 	    $Apache::lonhomework::results{"resource.$part.$id.awarddetail"}=
  438: 		$award;
  439: 	    if ($error) {
  440: 		$Apache::lonhomework::results{"resource.$part.$id.awardmsg"}=
  441: 		    $error;
  442: 	    }
  443: 	}
  444:     } elsif ( $target eq 'answer') {
  445: 	$result  = &Apache::response::answer_header('customresponse');
  446: 	my $answer = &Apache::lonxml::get_param('answerdisplay',$parstack,
  447: 						$safeeval);
  448: 	if ($env{'form.answer_output_mode'} ne 'tex') {
  449: 	    $answer = '<b>'.$answer.'</b>';
  450: 	}
  451: 	$result .= &Apache::response::answer_part('customresponse',$answer);
  452: 	$result .= &Apache::response::answer_footer('customresponse');
  453:     }
  454:     if ($target eq 'web') {
  455: 	&setup_prior_tries_hash(\&format_prior_response_math);
  456:     }
  457:     if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' || 
  458: 	$target eq 'tex' || $target eq 'analyze') {
  459: 	&Apache::lonxml::increment_counter(&Apache::response::repetition(),
  460: 					   "$part.$id");
  461: 	if ($target eq 'analyze') {
  462:             $Apache::lonhomework::analyze{"$part.$id.type"} = 'customresponse';
  463: 	    &Apache::lonhomework::set_bubble_lines();
  464: 	}
  465:     }
  466:     pop(@Apache::lonxml::namespace);
  467:     pop(@Apache::response::custom_answer);
  468:     pop(@Apache::response::custom_answer_type);
  469:     &Apache::lonxml::deregister('Apache::response',('answer'));
  470:     &Apache::response::end_response();
  471:     return $result;
  472: }
  473: 
  474: sub format_prior_response_custom {
  475:     my ($mode,$answer) =@_;
  476:     return '<span class="LC_prior_custom">'.
  477: 	    &HTML::Entities::encode($answer,'"<>&').'</span>';
  478: }
  479: 
  480: sub start_mathresponse {
  481:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  482:     my $id = &Apache::response::start_response($parstack,$safeeval);
  483:     push(@Apache::lonxml::namespace,'mathresponse');
  484:     my $result;
  485:     @Apache::response::custom_answer=();
  486:     @Apache::response::custom_answer_type=();
  487:     &Apache::lonxml::register('Apache::response',('answer'));
  488:     if ($target eq 'web') {
  489:   	if (  &Apache::response::show_answer() ) {
  490: 	    my $answer = &Apache::lonxml::get_param('answerdisplay',$parstack,
  491: 						   $safeeval);
  492: 	    $Apache::inputtags::answertxt{$id}=[$answer];
  493: 	}
  494: 
  495:     } elsif ($target eq 'edit') {
  496: 	$result.=&Apache::edit::tag_start($target,$token);
  497: 	$result.=&Apache::edit::text_arg('String to display for answer:',
  498: 					 'answerdisplay',$token);
  499: 	$result.=&Apache::edit::select_arg('Algebra System:',
  500: 					   'cas',
  501: 					   ['maxima'],
  502: 					   $token);
  503: 	$result.=&Apache::edit::text_arg('Argument Array:',
  504: 					 'args',$token).
  505:                  &Apache::loncommon::help_open_topic('Maxima_Argument_Array');
  506:         $result.=&Apache::edit::text_arg('Libraries:',
  507:                                          'libraries',$token).
  508:                  &Apache::loncommon::help_open_topic('Maxima_Libraries');
  509: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
  510:     } elsif ($target eq 'modified') {
  511: 	my $constructtag;
  512: 	$constructtag=&Apache::edit::get_new_args($token,$parstack,
  513: 						  $safeeval,'answerdisplay','cas','args','libraries');
  514: 	if ($constructtag) {
  515: 	    $result = &Apache::edit::rebuild_tag($token);
  516: 	}
  517:     } elsif ($target eq 'answer' || $target eq 'grade') {
  518: 	&Apache::response::reset_params();
  519:     } elsif ($target eq 'meta') {
  520: 	$result .= &Apache::response::meta_package_write('mathresponse');
  521:     }
  522:     return $result;
  523: }
  524: 
  525: sub edit_mathresponse_button {
  526:     my ($id,$field)=@_;
  527:     my $button=&mt('Edit Answer');
  528: #    my $helplink=&Apache::loncommon::help_open_topic('Formula_Editor');
  529:     my $iconpath=$Apache::lonnet::perlvar{'lonIconsURL'};
  530:     return(<<ENDFORMULABUTTON);
  531: <script language="JavaScript">
  532: function edit_${id}_${field} (textarea) {
  533:     thenumber = textarea;
  534:     thedata = document.forms['lonhomework'].elements[textarea].value;
  535:     newwin = window.open("/adm/dragmath/applet/MaximaPopup.html","","width=565,height=400,resizable");
  536: }
  537: </script>
  538: <a href="javascript:edit_${id}_${field}('${field}');void(0);"><img class="stift" src='$iconpath/stift.gif' alt='$button' title='$button'/></a>
  539: ENDFORMULABUTTON
  540: }
  541: 
  542: sub end_mathresponse {
  543:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  544:     my $result;
  545:     my $part=$Apache::inputtags::part;
  546:     my $id=$Apache::inputtags::response[-1];
  547:     if ( $target eq 'grade' && &Apache::response::submitted() ) {
  548: 	my $response = &Apache::response::getresponse();
  549: 	if ( $response =~ /[^\s]/ ) {
  550: 	    if (!$Apache::lonxml::default_homework_loaded) {
  551: 		&Apache::lonxml::default_homework_load($safeeval);
  552: 	    }
  553: 	    my %previous = &Apache::response::check_for_previous($response,
  554: 								 $part,$id);
  555: 	    $Apache::lonhomework::results{"resource.$part.$id.submission"}=
  556: 		$response;
  557: 	    my $error;
  558: 	    my $award;
  559: 	    my $cas = &Apache::lonxml::get_param('cas',$parstack,$safeeval);
  560:             if ($cas eq 'maxima') {
  561:                 my $args = [&Apache::lonxml::get_param_var('args',$parstack,$safeeval)];
  562:                 $award=&Apache::lonmaxima::maxima_run($Apache::response::custom_answer[-1],$response,$args,
  563:                                                       &Apache::lonxml::get_param('libraries',$parstack,$safeeval));
  564:             }
  565: 	    if (!&Apache::inputtags::valid_award($award)) {
  566: 		$error = $award;
  567: 		$award = 'ERROR';
  568: 	    }
  569: 	    &Apache::response::handle_previous(\%previous,$award);
  570: 	    $Apache::lonhomework::results{"resource.$part.$id.awarddetail"}=
  571: 		$award;
  572: 	    if ($error) {
  573: 		$Apache::lonhomework::results{"resource.$part.$id.awardmsg"}=
  574: 		    $error;
  575: 	    }
  576: 	}
  577:     }
  578:     if ($target eq 'web') {
  579: 	&setup_prior_tries_hash(\&format_prior_response_math);
  580:         my $partid = $Apache::inputtags::part;
  581:         my $id = $Apache::inputtags::response[-1];
  582:         if (($Apache::inputtags::status['-1'] eq 'CAN_ANSWER')
  583:            && (&Apache::lonnet::EXT('resource.'.$partid.'_'.$id.'.turnoffeditor') ne 'yes')) {
  584:             $result.=&edit_mathresponse_button($id,"HWVAL_$id");
  585:         }
  586:     }
  587: 
  588:     pop(@Apache::lonxml::namespace);
  589:     pop(@Apache::response::custom_answer);
  590:     pop(@Apache::response::custom_answer_type);
  591:     &Apache::lonxml::deregister('Apache::response',('answer'));
  592:     &Apache::response::end_response();
  593:     return $result;
  594: }
  595: 
  596: sub format_prior_response_math {
  597:     my ($mode,$answer) =@_;
  598:     return '<span class="LC_prior_math">'.
  599: 	    &HTML::Entities::encode($answer,'"<>&').'</span>';
  600: }
  601: 
  602: sub implicit_multiplication {
  603:     my ($expression)=@_;
  604: # Escape scientific notation, so 3e8 does not become 3*e*8
  605: # 3e8 -> 3&8; 3e-8 -> 3&-8; 3E+8 -> e&+8
  606:     $expression=~s/(\d+)e([\+\-]*\d+)/$1\&\($2\)/gsi;
  607: # 3x10^8 -> 3&8; 3*10^-8 -> 3&-8
  608:     $expression=~s/(\d+)(?:x|\*)10(?:\^|\*\*)([\+\-]*\d+)/$1\&\($2\)/gsi;
  609: # Fill in multiplication signs
  610: # a b -> a*b;3 b -> 3*b;3 4 -> 3*4
  611:     $expression=~s/([A-Za-z0-9])\s+(?=[A-Za-z0-9])/$1\*/gs;
  612: # )( -> )*(; ) ( -> )*(
  613:     $expression=~s/\)\s*\(/\)\*\(/gs;
  614: # 3a -> 3*a; 3( -> 3*(; 3 ( -> 3*(; 3A -> 3*A
  615:     $expression=~s/(\d)\s*([a-zA-Z\(])/$1\*$2/gs;
  616: # a ( -> a*(
  617:     $expression=~s/([A-Za-z0-9])\s+\(/$1\*\(/gs;
  618: # )a -> )*a; )3 -> )*3; ) 3 -> )*3
  619:     $expression=~s/\)\s*([A-Za-z0-9])/\)\*$1/gs;
  620: # 3&8 -> 3e8; 3&-4 -> 3e-4
  621:     $expression=~s/(\d+)\&\(([\+\-]*\d+)\)/$1e$2/gs;
  622:     return $expression;
  623: }
  624: 
  625: sub start_answer {
  626:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  627:     my $result;
  628:     push(@Apache::response::custom_answer,
  629: 	&Apache::lonxml::get_all_text_unbalanced("/answer",$parser));
  630:     push(@Apache::response::custom_answer_type,
  631: 	lc(&Apache::lonxml::get_param('type',$parstack,$safeeval)));
  632:     $Apache::response::custom_answer_type[-1] =~ s/\s+//g;
  633:     if ($target eq "edit" ) {
  634: 	$result=&Apache::edit::tag_start($target,$token,'Answer algorithm');
  635: 	$result.=&Apache::edit::editfield($token->[1],
  636: 					  $Apache::response::custom_answer[-1],
  637: 					  '',80,4);
  638:     } elsif ( $target eq "modified" ) {
  639: 	$result=$token->[4].&Apache::edit::modifiedfield('/answer',$parser);
  640:     }
  641:     return $result;
  642: }
  643: 
  644: sub end_answer {
  645:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  646:     if ($target eq 'edit' ) {
  647: 	return &Apache::edit::end_table();
  648:     }
  649: }
  650: 
  651: sub decide_package {
  652:     my ($tagstack)=@_;
  653:     my $package;
  654:     if ($$tagstack[-1] eq 'parameter') {
  655: 	$package='part';
  656:     } else {
  657: 	my $i=-1;
  658: 	while (defined($$tagstack[$i])) {
  659: 	    if ($$tagstack[$i] =~ /(response|hint)$/) {
  660: 		$package=$$tagstack[$i];
  661: 		last;
  662: 	    }
  663: 	    $i--;
  664: 	}
  665:     }
  666:     return $package;
  667: }
  668: 
  669: sub start_responseparam {
  670:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  671:     my $result='';
  672:     if ($target eq 'meta') {
  673: 	$result = &meta_parameter_write($token->[2]->{'name'},
  674: 					$token->[2]->{'type'},
  675: 					$token->[2]->{'default'},
  676: 					$token->[2]->{'description'});
  677:     } elsif ($target eq 'edit') {
  678: 	$result.=&Apache::edit::tag_start($target,$token);
  679: 	my $optionlist;
  680: 	my $package=&decide_package($tagstack);
  681: 	foreach my $key (sort(keys(%Apache::lonnet::packagetab))) {
  682: 	    if ($key =~ /^\Q$package\E&(.*)&display$/) {
  683: 		$optionlist.='<option value="'.$1.'">'.
  684: 		    $Apache::lonnet::packagetab{$key}.'</option>';
  685: 	    }
  686: 	}
  687: 	if (defined($optionlist)) {
  688: 	    $result.=&mt('Use template:').' <select name="'.
  689: 		&Apache::edit::html_element_name('parameter_package').'">'.
  690: 		    '<option value=""></option>'.$optionlist.'</select><br />';
  691: 	}
  692: 	$result.=&Apache::edit::text_arg('Name:','name',$token).
  693: 	    &Apache::edit::text_arg('Type:','type',$token).
  694: 		&Apache::edit::text_arg('Description:','description',$token).
  695: 		    &Apache::edit::text_arg('Default:','default',$token).
  696: 			"</td></tr>";
  697: 	$result.=&Apache::edit::end_table;
  698:     } elsif ($target eq 'modified') {
  699: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  700: 						     $safeeval,'name','type',
  701: 						     'description','default');
  702: 	my $element=&Apache::edit::html_element_name('parameter_package');
  703: 	if (defined($env{"form.$element"}) && $env{"form.$element"} ne '') {
  704: 	    my $name=$env{"form.$element"};
  705: 	    my $tag=&decide_package($tagstack);
  706: 	    $token->[2]->{'name'}=$name;
  707: 	    $token->[2]->{'type'}=
  708: 		$Apache::lonnet::packagetab{"$tag&$name&type"};
  709: 	    $token->[2]->{'description'}=
  710: 		$Apache::lonnet::packagetab{"$tag&$name&display"};
  711: 	    $token->[2]->{'default'}=
  712: 		$Apache::lonnet::packagetab{"$tag&$name&default"};
  713:             $token->[3] = ['name','type','description','default'];
  714: 	    $constructtag=1;
  715: 	}
  716: 	if ($constructtag) {
  717: 	    $result = &Apache::edit::rebuild_tag($token);
  718: 	}
  719:     } elsif ($target eq 'grade' || $target eq 'answer' || $target eq 'web' ||
  720: 	     $target eq 'tex' || $target eq 'analyze' ) {
  721: 	if ($env{'request.state'} eq 'construct') {
  722: 	    my $name   =&Apache::lonxml::get_param('name',$parstack,$safeeval);
  723: 	    my $default=&Apache::lonxml::get_param('default',$parstack,
  724: 						     $safeeval);
  725: 	    if ($name) {$Apache::inputtags::params{$name}=$default;}
  726: 	}
  727:     }
  728:     return $result;
  729: }
  730: 
  731: sub end_responseparam {
  732:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  733:     if ($target eq 'edit') { return ('','no'); }
  734:     return '';
  735: }
  736: 
  737: sub start_parameter {
  738:     return &start_responseparam(@_);
  739: }
  740: 
  741: sub end_parameter {
  742:     return &end_responseparam(@_);
  743: }
  744: 
  745: sub reset_params {
  746:     %Apache::inputtags::params=();
  747: }
  748: 
  749: sub setup_params {
  750:     my ($tag,$safeeval) = @_;
  751: 
  752:     if ($env{'request.state'} eq 'construct') { return; }
  753:     my %paramlist=();
  754:     foreach my $key (keys(%Apache::lonnet::packagetab)) {
  755: 	if ($key =~ /^\Q$tag\E/) {
  756: 	    my ($package,$name) = split(/&/,$key);
  757: 	    $paramlist{$name}=1;
  758: 	}
  759:     }
  760:     foreach my $key (keys(%paramlist)) {
  761: 	my $entry= 'resource.'.$Apache::inputtags::part;
  762: 	if (defined($Apache::inputtags::response[-1])) {
  763: 	    $entry.='_'.$Apache::inputtags::response[-1];
  764: 	}
  765: 	$entry.='.'.$key;
  766: 	&Apache::lonxml::debug("looking for $entry");
  767: 	my $value = &Apache::lonnet::EXT("$entry");
  768: 	&Apache::lonxml::debug("$key has value :$value:");
  769: 	if ($value eq 'con_lost' || $value =~ /^error:/) {
  770: 	    &Apache::lonxml::debug("using nothing");
  771: 	    $Apache::inputtags::params{$key}='';
  772: 	} else {
  773: 	    my $string="{return qq\0".$value."\0}";
  774: 	    my $newvalue=&Apache::run::run($string,$safeeval,1);
  775: 	    if (defined($newvalue)) { $value=$newvalue; }
  776: 	    $Apache::inputtags::params{$key}=$value;
  777: 	}
  778:     }
  779: }
  780: 
  781: {
  782:     my @answer_bits;
  783:     my $need_row_start;
  784: 
  785: sub answer_header {
  786:     my ($type,$increment,$rows) = @_;
  787:     my $result;
  788:     if ($env{'form.answer_output_mode'} eq 'tex') {
  789: 	undef(@answer_bits);
  790: 	my $bit;
  791: 	if ($Apache::lonhomework::type eq 'exam') {
  792: 	    $bit = ($Apache::lonxml::counter+$increment).') ';
  793: 	} else {
  794: 	    $bit .= ' Answer for Part: \verb|'.
  795: 		$Apache::inputtags::part.'| ';
  796: 	}
  797: 	push(@answer_bits,$bit);
  798:     } else {
  799: 	my $td = '<td '.(defined($rows)?'rowspan="'.$rows.'"':'').'>';
  800: 	$result  = '<table border="1"><tr>';
  801: 	if ($Apache::lonhomework::type eq 'exam') {
  802: 	    $result .= $td.($Apache::lonxml::counter+$increment). ')</td>';
  803: 	} else {
  804: 	    $result .= $td.&mt('Answer for Part: [_1]',
  805: 			       $Apache::inputtags::part).'</td>';
  806: 	}
  807: 	$result .= "\n";
  808: 	$need_row_start = 0;
  809:     }
  810:     return $result;
  811: }
  812: 
  813: sub next_answer {
  814:     my ($type) = @_;
  815:     my $result;
  816:     if ($env{'form.answer_output_mode'} eq 'tex') {
  817: 	# FIXME ... need to do something with tex mode
  818:     } else {
  819: 	$result .= "</tr>";
  820: 	$need_row_start = 1;
  821:     }
  822:     return $result;
  823: }
  824: 
  825: sub answer_part {
  826:     my ($type,$answer,$args) = @_;
  827:     my $result;
  828:     if ($env{'form.answer_output_mode'} eq 'tex') {
  829: 	if (!$args->{'no_verbatim'}) {
  830: 	    my $to_use='|';
  831: 	    foreach my $value (32..126) {
  832: 		my $char=pack('c',$value);
  833: 		if ($answer !~ /\Q$char\E/) {
  834: 		    $to_use=$char;
  835: 		    last;
  836: 		}
  837: 	    }
  838:             my $fullanswer=$answer;
  839:             $answer='';
  840:             foreach my $element (split(/[\;]/,$fullanswer)) {
  841: 	       if ($element ne '') {
  842: 	 	  $answer.= '\verb'.$to_use.$element.$to_use.' \newline';
  843: 	       }
  844:             }
  845: 	}
  846: 	if ($answer ne '') {
  847: 	    push(@answer_bits,$answer);
  848: 	}
  849:     } else {
  850: 	if ($need_row_start) {
  851: 	    $result .= '<tr>';
  852: 	    $need_row_start = 0;
  853: 	}
  854: 	$result .= '<td>'.$answer.'</td>';
  855:     }
  856:     return $result;
  857: }
  858: 
  859: sub answer_footer {
  860:     my ($type) = @_;
  861:     my $result;
  862:     if ($env{'form.answer_output_mode'} eq 'tex') {
  863: 	$result  = ' \vskip 0 mm \noindent \begin{tabular}{|p{1.5cm}|p{6.8cm}|}\hline ';
  864: 	$result .= $answer_bits[0].'&\vspace*{-4mm}\begin{itemize}';
  865:         for (my $i=1;$i<=$#answer_bits;$i++) {
  866:             $result.='\item '.$answer_bits[$i].'\vspace*{-7mm}';
  867:         }
  868: 	$result .= ' \end{itemize} \\\\ \hline \end{tabular} \vskip 0 mm ';
  869:     } else {
  870: 	if (!$need_row_start) {
  871: 	    $result .= '</tr>';
  872: 	}
  873: 	$result .= '</table>';
  874:     }
  875:     return $result;
  876: }
  877: 
  878: }
  879: 
  880: sub showallfoils {
  881:     if (defined($env{'form.showallfoils'})) {
  882: 	my ($symb)=&Apache::lonnet::whichuser();
  883: 	if (($env{'request.state'} eq 'construct') || 
  884: 	    ($env{'user.adv'} && $symb eq '')      ||
  885:             ($Apache::lonhomework::viewgrades) ) {
  886: 	    return 1;
  887: 	}
  888:     }
  889:     if ($Apache::lonhomework::type eq 'survey') { return 1; }
  890:     return 0;
  891: }
  892: 
  893: =pod
  894: 
  895: =item &getresponse($offset,$resulttype);
  896: 
  897: Retreives the current submitted response, helps out in the case of
  898: scantron mode.
  899: 
  900: Returns either the exact text of the submission, or a bubbled response
  901: converted to something usable.
  902: 
  903: Optional Arguments:
  904:   $offset - (defaults to 1) if a problem has more than one bubble
  905:             response, pass in the number of the bubble wanted, (the
  906:             first bubble associated with a problem has an offset of 1,
  907:             the second bubble is 2
  908: 
  909:   $resulttype - undef    -> a number between 0 and 25
  910:                 'A is 1' -> a number between 1 and 26
  911:                 'letter' -> a letter between 'A' and 'Z'
  912:   $lines  - undef problem only needs a single line of bubbles.
  913:             nonzero  Problem wants the first nonempty response in 
  914:                       $lines lines of bubbles.
  915:   $bubbles_per_line - Must be provided if lines is defined.. number of
  916:                       bubbles on a line.
  917: 
  918: =cut
  919: 
  920: sub getresponse {
  921:     my ($offset,$resulttype, $lines, $bubbles_per_line)=@_;
  922:     my $formparm='form.HWVAL_'.$Apache::inputtags::response['-1'];
  923:     my $response;
  924:     if (!defined($offset)) {
  925: 	$offset=1;
  926:     } else {
  927: 	$formparm.=":$offset";
  928:     }
  929:     if (!defined($lines)) {
  930: 	$lines = 1;
  931:     }
  932:     my %let_to_num=('A'=>0,'B'=>1,'C'=>2,'D'=>3,'E'=>4,'F'=>5,'G'=>6,'H'=>7,
  933: 		    'I'=>8,'J'=>9,'K'=>10,'L'=>11,'M'=>12,'N'=>13,'O'=>14,
  934: 		    'P'=>15,'Q'=>16,'R'=>17,'S'=>18,'T'=>19,'U'=>20,'V'=>21,
  935: 		    'W'=>22,'X'=>23,'Y'=>24,'Z'=>25);
  936:     if ($env{'form.submitted'} eq 'scantron') {
  937: 	my $part  = $Apache::inputtags::part;
  938: 	my $id    = $Apache::inputtags::response[-1];
  939: 	
  940: 	my $line;
  941: 	for ($line = 0; $line < $lines; $line++) {
  942: 	    my $theline = $Apache::lonxml::counter+$offset-1+$line;
  943: 	    $response = $env{"scantron.$theline.answer"};
  944: 	    if ((defined($response)) && ($response ne "") && ($response ne " ")) {
  945: 		last;
  946: 	    }
  947: 	    
  948: 	}
  949: 
  950: 	# save bubbled letter for later
  951: 	$Apache::lonhomework::results{"resource.$part.$id.scantron"}.=
  952: 	    $response;
  953: 	if ($resulttype ne 'letter') {
  954: 	    if ($resulttype eq 'A is 1') {
  955: 		$response = $let_to_num{$response}+1;
  956: 	    } else {
  957: 		$response = $let_to_num{$response};
  958: 	    }
  959: 	    if ($response ne "") {
  960: 		$response += $line * $bubbles_per_line;
  961: 	    }
  962: 	} else {
  963: 	    if ($response ne "") {
  964: 		$response = chr(ord($response) + $line * $bubbles_per_line);
  965: 	    }
  966: 	}
  967: 
  968:     } else {
  969: 	$response = $env{$formparm};
  970:     }
  971:     # 
  972:     #  If we have a nonempty answer, correct the numeric value
  973:     #  of the answer for the line on which it was found.
  974:     #
  975: 
  976:     return $response;
  977: }
  978: 
  979: =pod
  980: 
  981: =item &repetition();
  982: 
  983: Returns the number of lines that are required to encode the weight.
  984: (Currently expects that there are 10 bubbles per line)
  985: 
  986: =cut
  987: 
  988: sub repetition {
  989:     my $id = $Apache::inputtags::part;
  990:     my $weight = &Apache::lonnet::EXT("resource.$id.weight");
  991:     if (!defined($weight) || ($weight eq '')) { $weight=1; }
  992:     my $repetition = int($weight/10);
  993:     if ($weight % 10 != 0) { $repetition++; } 
  994:     return $repetition;
  995: }
  996: 
  997: =pod
  998: 
  999: =item &scored_response($part_id,$response_id);
 1000: 
 1001: Sets the results hash elements
 1002: 
 1003:    resource.$part_id.$response_id.awarded - to the floating point
 1004:      number between 0 and 1 that was awarded on the bubbled input
 1005: 
 1006:    resource.$part_id.$response_id.awarddetail - to 'ASSIGNED_SCORE'
 1007: 
 1008: Returns
 1009: 
 1010:    the number of bubble sheet lines that were used (and likely need to
 1011:      be passed to &Apache::lonxml::increment_counter()
 1012: 
 1013: Arguments
 1014: 
 1015:    $part_id - id of the part to grade
 1016:    $response_id - id of the response to grade
 1017:   
 1018: 
 1019: =cut
 1020: 
 1021: sub scored_response {
 1022:     my ($part,$id)=@_;
 1023:     my $repetition=&repetition();
 1024:     my $score=0;
 1025:     for (my $i=0;$i<$repetition;$i++) {
 1026: 	# A is 1, B is 2, etc. (get response return 0-9 and then we add 1)
 1027: 	my $increase=&Apache::response::getresponse($i+1);
 1028: 	if ($increase ne '') { $score+=$increase+1; }
 1029:     }
 1030:     my $weight = &Apache::lonnet::EXT("resource.$part.weight");
 1031:     if (!defined($weight) || $weight eq '' || $weight eq 0) { $weight = 1; }
 1032:     my $pcr=$score/$weight;
 1033:     $Apache::lonhomework::results{"resource.$part.$id.awarded"}=$pcr;
 1034:     $Apache::lonhomework::results{"resource.$part.$id.awarddetail"}=
 1035: 	'ASSIGNED_SCORE';
 1036:     return $repetition;
 1037: }
 1038: 
 1039: sub whichorder {
 1040:     my ($max,$randomize,$showall,$hash)=@_;
 1041:     #&Apache::lonxml::debug("man $max randomize $randomize");
 1042:     if (!defined(@{ $$hash{'names'} })) { return; }
 1043:     my @names = @{ $$hash{'names'} };
 1044:     my @whichopt =();
 1045:     my (%top,@toplist,%bottom,@bottomlist);
 1046:     if (!($showall || ($randomize eq 'no'))) {
 1047: 	my $current=0;
 1048: 	foreach my $name (@names) {
 1049: 	    $current++;
 1050: 	    if ($$hash{"$name.location"} eq 'top') {
 1051: 		$top{$name}=$current;
 1052: 	    } elsif ($$hash{"$name.location"} eq 'bottom') {
 1053: 		$bottom{$name}=$current;
 1054: 	    }
 1055: 	}
 1056:     }
 1057:     my $topcount=0;
 1058:     my $bottomcount=0;
 1059:     while (((scalar(@whichopt)+$topcount+$bottomcount) < $max || $showall)
 1060: 	   && ($#names > -1)) {
 1061: 	#&Apache::lonxml::debug("Have $#whichopt max is $max");
 1062: 	my $aopt;
 1063: 	if ($showall || ($randomize eq 'no')) {
 1064: 	    $aopt=0;
 1065: 	} else {
 1066: 	    $aopt=int(&Math::Random::random_uniform() * ($#names+1));
 1067: 	}
 1068: 	#&Apache::lonxml::debug("From $#whichopt $max $#names elms, picking $aopt");
 1069: 	$aopt=splice(@names,$aopt,1);
 1070: 	#&Apache::lonxml::debug("Picked $aopt");
 1071: 	if ($top{$aopt}) {
 1072: 	    $toplist[$top{$aopt}]=$aopt;
 1073: 	    $topcount++;
 1074: 	} elsif ($bottom{$aopt}) {
 1075: 	    $bottomlist[$bottom{$aopt}]=$aopt;
 1076: 	    $bottomcount++;
 1077: 	} else {
 1078: 	    push (@whichopt,$aopt);
 1079: 	}
 1080:     }
 1081:     for (my $i=0;$i<=$#toplist;$i++) {
 1082: 	if ($toplist[$i]) { unshift(@whichopt,$toplist[$i]) }
 1083:     }
 1084:     for (my $i=0;$i<=$#bottomlist;$i++) {
 1085: 	if ($bottomlist[$i]) { push(@whichopt,$bottomlist[$i]) }
 1086:     }
 1087:     return @whichopt;
 1088: }
 1089: 
 1090: sub show_answer {
 1091:     my $part   = $Apache::inputtags::part;
 1092:     my $award  = $Apache::lonhomework::history{"resource.$part.solved"};
 1093:     my $status = $Apache::inputtags::status[-1];
 1094:     return  ( ($award =~ /^correct/
 1095: 	       && &Apache::lonhomework::show_problem_status())
 1096: 	      || $status eq "SHOW_ANSWER");
 1097: }
 1098: 
 1099: sub analyze_store_foilgroup {
 1100:     my ($shown,$attrs)=@_;
 1101:     my $part_id="$Apache::inputtags::part.$Apache::inputtags::response[-1]";
 1102:     foreach my $name (@{ $Apache::response::foilgroup{'names'} }) {
 1103: 	if (defined($Apache::lonhomework::analyze{"$part_id.foil.value.$name"})) { next; }
 1104: 	push (@{ $Apache::lonhomework::analyze{"$part_id.foils"} },$name);
 1105: 	foreach my $attr (@$attrs) {
 1106: 	    $Apache::lonhomework::analyze{"$part_id.foil.".$attr.".$name"} =
 1107: 		$Apache::response::foilgroup{"$name.".$attr};
 1108: 	}
 1109:     }
 1110:     push (@{ $Apache::lonhomework::analyze{"$part_id.shown"} }, @{ $shown });
 1111: }
 1112: 
 1113: sub check_if_computed {
 1114:     my ($token,$parstack,$safeeval,$name)=@_;
 1115:     my $value = &Apache::lonxml::get_param($name,$parstack,$safeeval);
 1116:     if (ref($token->[2]) eq 'HASH' && $value ne $token->[2]{$name}) {
 1117: 	my $part_id="$Apache::inputtags::part.$Apache::inputtags::response[-1]";
 1118: 	$Apache::lonhomework::analyze{"$part_id.answercomputed"} = 1;
 1119:     }
 1120: }
 1121: 
 1122: sub pick_foil_for_concept {
 1123:     my ($target,$attrs,$hinthash,$parstack,$safeeval)=@_;
 1124:     if (not defined(@{ $Apache::response::conceptgroup{'names'} })) { return; }
 1125:     my @names = @{ $Apache::response::conceptgroup{'names'} };
 1126:     my $pick=int(&Math::Random::random_uniform() * ($#names+1));
 1127:     my $name=$names[$pick];
 1128:     push @{ $Apache::response::foilgroup{'names'} }, $name;
 1129:     foreach my $attr (@$attrs) {
 1130: 	$Apache::response::foilgroup{"$name.".$attr} =
 1131: 	    $Apache::response::conceptgroup{"$name.".$attr};
 1132:     }
 1133:     my $concept = &Apache::lonxml::get_param('concept',$parstack,$safeeval);
 1134:     $Apache::response::foilgroup{"$name.concept"} = $concept;
 1135:     &Apache::lonxml::debug("Selecting $name in $concept");
 1136:     my $part_id="$Apache::inputtags::part.$Apache::inputtags::response[-1]";
 1137:     if ($target eq 'analyze') {
 1138: 	push (@{ $Apache::lonhomework::analyze{"$part_id.concepts"} },
 1139: 	      $concept);
 1140: 	$Apache::lonhomework::analyze{"$part_id.concept.$concept"}=
 1141: 	    $Apache::response::conceptgroup{'names'};
 1142: 	foreach my $name (@{ $Apache::response::conceptgroup{'names'} }) {
 1143: 	    push (@{ $Apache::lonhomework::analyze{"$part_id.foils"} },
 1144: 		  $name);
 1145: 	    foreach my $attr (@$attrs) {
 1146: 		$Apache::lonhomework::analyze{"$part_id.foil.$attr.$name"}=
 1147: 		    $Apache::response::conceptgroup{"$name.$attr"};
 1148: 	    }
 1149: 	}
 1150:     }
 1151:     push(@{ $hinthash->{"$part_id.concepts"} },$concept);
 1152:     $hinthash->{"$part_id.concept.$concept"}=
 1153: 	$Apache::response::conceptgroup{'names'};
 1154: 
 1155: }
 1156: #------------------------------------------------------------
 1157: #
 1158: #  Get a parameter associated with a problem.
 1159: # Parameters:
 1160: #  $id        - the id of the paramater, either a part id, 
 1161: #               or a partid and responspe id joined by _
 1162: #  $name      - Name of the parameter to fetch
 1163: #  $default   - Default value for the paramter.
 1164: #
 1165: #  
 1166: #
 1167: sub get_response_param {
 1168:     my ($id,$name,$default)=@_;
 1169:     my $parameter;
 1170:     if ($env{'request.state'} eq 'construct' &&
 1171: 	defined($Apache::inputtags::params{$name})) {
 1172: 	$parameter=$Apache::inputtags::params{$name};
 1173:     } else {
 1174: 	$parameter=&Apache::lonnet::EXT("resource.$id.$name");
 1175:     }
 1176:     if (!defined($parameter) ||	$parameter eq '') {
 1177: 	$parameter = $default;
 1178:     }
 1179:     return $parameter;
 1180: }
 1181: 
 1182: sub submitted {
 1183:     my ($who)=@_;
 1184:     
 1185:     # when scatron grading any submission is a submission
 1186:     if ($env{'form.submitted'} eq 'scantron') { return 1; }
 1187:     # if the caller only cared if this was a scantron submission
 1188:     if ($who eq 'scantron') { return 0; }
 1189:     # if the Submit Answer button for this particular part was pressed
 1190:     my $partid=$Apache::inputtags::part;
 1191:     if ($env{'form.submitted'} eq "part_$partid") {
 1192: 	return 1;
 1193:     }
 1194:     if ($env{'form.submitted'} eq "yes"
 1195: 	&& defined($env{'form.submit_'.$partid})) {
 1196: 	return 1;
 1197:     }
 1198:     # Submit All button on a .page was pressed
 1199:     if (defined($env{'form.all_submit'})) { return 1; }
 1200:     # otherwise no submission occurred
 1201:     return 0;
 1202: }
 1203: 
 1204: sub add_to_gradingqueue {
 1205:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
 1206:     if (   $courseid eq ''
 1207: 	|| $symb eq ''
 1208: 	|| $env{'request.state'} eq 'construct'
 1209: 	|| $Apache::lonhomework::type ne 'problem') {
 1210: 	return;
 1211:     }
 1212: 
 1213:     my %queue_info = ( 'type' => 'problem',
 1214: 		       'time' => time);
 1215: 
 1216:     if (exists($Apache::lonhomework::history{"resource.0.checkedin.slot"})) {
 1217: 	$queue_info{'slot'}=
 1218: 	     $Apache::lonhomework::history{"resource.0.checkedin.slot"};
 1219:     }
 1220: 
 1221:     my $result=&Apache::bridgetask::add_to_queue('gradingqueue',\%queue_info);
 1222:     if ($result ne 'ok') {
 1223: 	&Apache::lonxml::error("add_to_queue said $result");
 1224:     }
 1225: }
 1226: 
 1227: # basically undef and 0 (both false) mean that they still have work to do
 1228: # and all true values mean that they can't do any more work
 1229: #
 1230: # a return of undef means it is unattempted
 1231: # a return of 0 means it is attmpted and wrong but still has tries
 1232: # a return of 1 means it is marked correct
 1233: # a return of 2 means they have exceed maximum number of tries
 1234: # a return of 3 means it after the answer date
 1235: sub check_status {
 1236:     my ($id)=@_;
 1237:     if (!defined($id)) { $id=$Apache::inputtags::part; }
 1238:     my $curtime=&Apache::lonnet::EXT('system.time');
 1239:     my $opendate=&Apache::lonnet::EXT("resource.$id.opendate");
 1240:     my $duedate=&Apache::lonnet::EXT("resource.$id.duedate");
 1241:     my $answerdate=&Apache::lonnet::EXT("resource.$id.answerdate");
 1242:     if ( $opendate && $curtime > $opendate &&
 1243:          $duedate && $curtime > $duedate &&
 1244:          $answerdate && $curtime > $answerdate) {
 1245:         return 3;
 1246:     }
 1247:     my $status=&Apache::lonnet::EXT("user.resource.resource.$id.solved");
 1248:     if ($status =~ /^correct/) { return 1; }
 1249:     if (!$status) { return undef; }
 1250:     my $maxtries=&Apache::lonnet::EXT("resource.$id.maxtries");
 1251:     if ($maxtries eq '') { $maxtries=2; }
 1252:     my $curtries=&Apache::lonnet::EXT("user.resource.resource.$id.tries");
 1253:     if ($curtries < $maxtries) { return 0; }
 1254:     return 2;
 1255: }
 1256: 
 1257: =pod
 1258: 
 1259: =item setup_prior_tries_hash($func,$data)
 1260: 
 1261:   Foreach each past .submission $func is called with 3 arguments
 1262:      - the mode to set things up for (currently always 'grade')
 1263:      - the stored .submission string
 1264:      - The expansion of $data
 1265: 
 1266:   $data is an array ref containing elements that are either
 1267:     - scalars that are other elements of the history hash to pass to $func
 1268:     - ref to data to be passed untouched to $func
 1269: 
 1270: =cut
 1271: 
 1272: sub setup_prior_tries_hash {
 1273:     my ($func,$data) = @_;
 1274:     my $part = $Apache::inputtags::part;
 1275:     my $id   = $Apache::inputtags::response[-1];	
 1276:     foreach my $i (1..$Apache::lonhomework::history{'version'}) {
 1277: 	my $sub_key   = "$i:resource.$part.$id.submission";
 1278: 	next if (!exists($Apache::lonhomework::history{$sub_key}));
 1279: 	my @other_data;
 1280: 	foreach my $datum (@{ $data }) {
 1281: 	    if (ref($datum)) {
 1282: 		push(@other_data,$datum);
 1283: 	    } else {
 1284: 		my $info_key = "$i:resource.$part.$id.$datum";
 1285: 		push(@other_data,$Apache::lonhomework::history{$info_key});
 1286: 	    }
 1287: 	}
 1288: 
 1289: 	my $output =
 1290: 	    &$func('grade',
 1291: 		   $Apache::lonhomework::history{$sub_key},
 1292: 		   \@other_data);
 1293: 	if (defined($output)) {
 1294: 	    $Apache::inputtags::submission_display{$sub_key} = $output;
 1295: 	}
 1296:     }
 1297: }
 1298: 
 1299: 1;
 1300: __END__
 1301:  

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>