File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.244.2.1: download - view: text, annotated - select for diffs
Sun Sep 2 16:51:51 2018 UTC (5 years, 8 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.244: preferred, unified
- For 2.11
  Backport 1.246

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

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