File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.209: download - view: text, annotated - select for diffs
Sun Dec 7 23:40:57 2008 UTC (15 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Detect if there were timeouts or other internal errors during grading.

Do not charge a try, allow student to enter same answer again.

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

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