File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.203: download - view: text, annotated - select for diffs
Tue Sep 9 13:56:48 2008 UTC (15 years, 7 months ago) by riegler
Branches: MAIN
CVS tags: HEAD
Added ressource parameter to turn DragMath-Editor on/off.

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

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