File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.223: download - view: text, annotated - select for diffs
Mon Jun 6 17:17:38 2011 UTC (12 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #6476: reversing lonnet.pm 1.1109 to 1.1108
Needed to catch post-processing of random seed.

    1: # The LearningOnline Network with CAPA
    2: # various response type definitons response definition
    3: #
    4: # $Id: response.pm,v 1.223 2011/06/06 17:17:38 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::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::lonmaxima();
   57: use Apache::lonr();
   58: 
   59: BEGIN {
   60:     &Apache::lonxml::register('Apache::response',('responseparam','parameter','dataresponse','customresponse','mathresponse'));
   61: }
   62: 
   63: sub start_response {
   64:     my ($parstack,$safeeval)=@_;
   65:     my $id = &Apache::lonxml::get_id($parstack,$safeeval);
   66:     if ($#Apache::inputtags::import > -1) {
   67: 	&Apache::lonxml::debug("Turning :$id: into");
   68: 	$id = join('_',@Apache::inputtags::import).'_'.$id;
   69: 	&Apache::lonxml::debug("New  :$id:");
   70:     }
   71:     push (@Apache::inputtags::response,$id);
   72:     push (@Apache::inputtags::responselist,$id);
   73:     @Apache::inputtags::inputlist=();
   74:     if ($Apache::inputtags::part eq '' && 
   75: 	!$Apache::lonhomework::ignore_response_errors) {
   76: 	&Apache::lonxml::error(&HTML::Entities::encode(&mt("Found a <*response> outside of a <part> in a <part>ed problem"),'<>&"'));
   77:     }
   78:     if ($Apache::inputtags::response_with_no_part &&
   79: 	$Apache::inputtags::part ne '0') {
   80: 	&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 />');
   81:     }
   82:     if ($Apache::inputtags::part eq '0') {
   83: 	$Apache::inputtags::response_with_no_part=1;
   84:     }
   85:     return $id;
   86: }
   87: 
   88: sub end_response {
   89:     #pop @Apache::inputtags::response;
   90:     @Apache::inputtags::inputlist=();
   91:     return '';
   92: }
   93: 
   94: sub start_hintresponse {
   95:     my ($parstack,$safeeval)=@_;
   96:     my $id = &Apache::lonxml::get_id($parstack,$safeeval);
   97:     push (@Apache::inputtags::hint,$id);
   98:     push (@Apache::inputtags::hintlist,$id);
   99:     push (@Apache::inputtags::paramstack,[%Apache::inputtags::params]);
  100:     return $id;
  101: }
  102: 
  103: sub end_hintresponse {
  104:     pop @Apache::inputtags::hint;
  105:     if (defined($Apache::inputtags::paramstack[-1])) {
  106: 	%Apache::inputtags::params=
  107: 	    @{ pop(@Apache::inputtags::paramstack) };
  108:     }
  109:     return '';
  110: }
  111: 
  112: my @randomseeds;
  113: sub pushrandomnumber {
  114:     my $rand_alg=&Apache::lonnet::get_rand_alg();
  115:     if (!$rand_alg || $rand_alg eq '32bit' || $rand_alg eq '64bit' ||
  116: 	$rand_alg eq '64bit2') {
  117: 	# do nothing
  118:     } else {
  119: 	my @seed=&Math::Random::random_get_seed();
  120: 	push(@randomseeds,\@seed);
  121:     }
  122:     &Apache::response::setrandomnumber(@_);
  123: }
  124: sub poprandomnumber {
  125:     my $rand_alg=&Apache::lonnet::get_rand_alg();
  126:     if (!$rand_alg || $rand_alg eq '32bit' || $rand_alg eq '64bit' ||
  127: 	$rand_alg eq '64bit2') {
  128: 	return;
  129:     }
  130:     my $seed=pop(@randomseeds);
  131:     if ($seed) {
  132: 	&Math::Random::random_set_seed(@$seed);
  133:     } else {
  134: 	&Apache::lonxml::error("Unable to restore random algorithm.");
  135:     }
  136: }
  137: 
  138: sub setrandomnumber {
  139:     my ($ignore_id2,$target,$rndseed) = @_;
  140:     if (!defined($rndseed)) {
  141:         $rndseed=&Apache::structuretags::setup_rndseed(undef,$target);
  142:     } 
  143:     if (!defined($rndseed)) { $rndseed=&Apache::lonnet::rndseed(); }
  144:     &Apache::lonxml::debug("randseed $rndseed");
  145:     #  $rndseed=unpack("%32i",$rndseed);
  146:     my $rand_alg=&Apache::lonnet::get_rand_alg();
  147:     my ($rndmod,$rndmod2);
  148: 
  149:     my ($id1,$id2,$shift_amt);
  150:     if ($Apache::lonhomework::parsing_a_problem) {
  151: 	$id1=$Apache::inputtags::part;
  152: 	if (defined($Apache::inputtags::response[-1])) {
  153: 	    $id2=$Apache::inputtags::response[-1];
  154: 	}
  155: 	$shift_amt=scalar(@Apache::inputtags::responselist);
  156:     } elsif ($Apache::lonhomework::parsing_a_task) {
  157: 	$id1=&Apache::bridgetask::get_dim_id();
  158: 	if (!$ignore_id2 && ref($Apache::bridgetask::instance{$id1})) {
  159: 	    $id2=$Apache::bridgetask::instance{$id1}[-1];
  160: 	    $shift_amt=scalar(@{$Apache::bridgetask::instance{$id1}});
  161: 	} else {
  162: 	    $shift_amt=0;
  163: 	}
  164:     } 
  165:     &Apache::lonxml::debug("id1: $id1, id2: $id2, shift_amt: $shift_amt");
  166:     if (!$rand_alg || $rand_alg eq '32bit' || $rand_alg eq '64bit' ||
  167: 	$rand_alg eq '64bit2') {
  168: 	$rndmod=(&Apache::lonnet::numval($id1) << 10);
  169: 	if (defined($id2)) { $rndmod+=&Apache::lonnet::numval($id2); }
  170:     } elsif ($rand_alg eq '64bit3') {
  171: 	$rndmod=(&Apache::lonnet::numval2($id1) << 10);
  172: 	if (defined($id2)) { $rndmod+=&Apache::lonnet::numval2($id2); }
  173:     } elsif ($rand_alg eq '64bit4') {
  174: 	my $shift=(4*$shift_amt)%30;
  175: 	$rndmod=(&Apache::lonnet::numval3($id1) << (($shift+15)%30));
  176: 	if (defined($id2)) {
  177: 	    $rndmod+=(&Apache::lonnet::numval3($id2) << $shift );
  178: 	}
  179:     } else {
  180: 	($rndmod,$rndmod2)=&Apache::lonnet::digest("$id1,$id2");
  181:     }
  182: 
  183:     if ($rndseed =~/([,:])/) {
  184: 	my $char=$1;
  185: 	use integer;
  186: 	my ($num1,$num2)=split(/\Q$char\E/,$rndseed);
  187: 	$num1+=$rndmod;
  188: 	$num2+= ((defined($rndmod2)) ? $rndmod2 : $rndmod);
  189: 	if($Apache::lonnet::_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
  190: 	$rndseed=$num1.$char.$num2;
  191:     } else {
  192: 	$rndseed+=$rndmod;
  193: 	if($Apache::lonnet::_64bit) {
  194: 	    use integer;
  195: 	    $rndseed=(($rndseed<<32)>>32);
  196: 	}
  197:     }
  198:     &Apache::lonxml::debug("randseed $rndmod $rndseed");
  199:     $Apache::lonhomework::results{'resource.'.$id1.'.rndseed'}=$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{"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='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: 	    &Apache::response::handle_previous(\%previous,$award);
  472: 	    $Apache::lonhomework::results{"resource.$part.$id.awarddetail"}=
  473: 		$award;
  474:             if ($award eq 'ASSIGNED_SCORE') {
  475:                 $Apache::lonhomework::results{"resource.$part.$id.awarded"}=1.0*$score;
  476:             }
  477: 	    if ($error) {
  478: 		$Apache::lonhomework::results{"resource.$part.$id.awardmsg"}=
  479: 		    $error;
  480: 	    }
  481: 	}
  482:     } elsif ( $target eq 'answer') {
  483: 	$result  = &Apache::response::answer_header('customresponse');
  484: 	my $answer = &Apache::lonxml::get_param('answerdisplay',$parstack,
  485: 						$safeeval);
  486: 	if ($env{'form.answer_output_mode'} ne 'tex') {
  487: 	    $answer = '<b>'.$answer.'</b>';
  488: 	}
  489: 	$result .= &Apache::response::answer_part('customresponse',$answer);
  490: 	$result .= &Apache::response::answer_footer('customresponse');
  491:     }
  492:     if ($target eq 'web') {
  493: 	&setup_prior_tries_hash(\&format_prior_response_math);
  494:     }
  495:     if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' || 
  496: 	$target eq 'tex' || $target eq 'analyze') {
  497: 	&Apache::lonxml::increment_counter(&Apache::response::repetition(),
  498: 					   "$part.$id");
  499: 	if ($target eq 'analyze') {
  500:             $Apache::lonhomework::analyze{"$part.$id.type"} = 'customresponse';
  501: 	    &Apache::lonhomework::set_bubble_lines();
  502: 	}
  503:     }
  504:     pop(@Apache::lonxml::namespace);
  505:     pop(@Apache::response::custom_answer);
  506:     pop(@Apache::response::custom_answer_type);
  507:     &Apache::lonxml::deregister('Apache::response',('answer'));
  508:     &Apache::response::end_response();
  509:     return $result;
  510: }
  511: 
  512: sub format_prior_response_custom {
  513:     my ($mode,$answer) =@_;
  514:     return '<span class="LC_prior_custom">'.
  515: 	    &HTML::Entities::encode($answer,'"<>&').'</span>';
  516: }
  517: 
  518: sub start_mathresponse {
  519:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  520:     my $id = &Apache::response::start_response($parstack,$safeeval);
  521:     push(@Apache::lonxml::namespace,'mathresponse');
  522:     my $result;
  523:     @Apache::response::custom_answer=();
  524:     @Apache::response::custom_answer_type=();
  525:     &Apache::lonxml::register('Apache::response',('answer'));
  526:     if ($target eq 'web') {
  527:   	if (  &Apache::response::show_answer() ) {
  528: 	    my $answer = &Apache::lonxml::get_param('answerdisplay',$parstack,
  529: 						   $safeeval);
  530: 	    $Apache::inputtags::answertxt{$id}=[$answer];
  531: 	}
  532: 
  533:     } elsif ($target eq 'edit') {
  534: 	$result.=&Apache::edit::tag_start($target,$token);
  535: 	$result.=&Apache::edit::text_arg('String to display for answer:',
  536: 					 'answerdisplay',$token,'50');
  537: 	$result.=&Apache::edit::select_arg('Algebra System:',
  538: 					   'cas',
  539: 					   ['maxima','R'],
  540: 					   $token);
  541: 	$result.=&Apache::edit::text_arg('Argument Array:',
  542: 					 'args',$token).
  543:                  &Apache::loncommon::help_open_topic('Maxima_Argument_Array');
  544:         $result.=&Apache::edit::text_arg('Libraries:',
  545:                                          'libraries',$token).
  546:                  &Apache::loncommon::help_open_topic('Maxima_Libraries');
  547: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
  548:     } elsif ($target eq 'modified') {
  549: 	my $constructtag;
  550: 	$constructtag=&Apache::edit::get_new_args($token,$parstack,
  551: 						  $safeeval,'answerdisplay','cas','args','libraries');
  552: 	if ($constructtag) {
  553: 	    $result = &Apache::edit::rebuild_tag($token);
  554: 	}
  555:     } elsif ($target eq 'answer' || $target eq 'grade') {
  556: 	&Apache::response::reset_params();
  557:     } elsif ($target eq 'meta') {
  558: 	$result .= &Apache::response::meta_package_write('mathresponse');
  559:     }
  560:     return $result;
  561: }
  562: 
  563: sub edit_mathresponse_button {
  564:     my ($id,$field)=@_;
  565:     my $button=&mt('Edit Answer');
  566: #    my $helplink=&Apache::loncommon::help_open_topic('Formula_Editor');
  567:     my $iconpath=$Apache::lonnet::perlvar{'lonIconsURL'};
  568:     return(<<ENDFORMULABUTTON);
  569: <script type="text/javascript" language="JavaScript">
  570: function edit_${id}_${field} (textarea) {
  571:     thenumber = textarea;
  572:     thedata = document.forms['lonhomework'].elements[textarea].value;
  573:     newwin = window.open("/adm/dragmath/applet/MaximaPopup.html","","width=565,height=400,resizable");
  574: }
  575: </script>
  576: <a href="javascript:edit_${id}_${field}('${field}');void(0);"><img class="stift" src="$iconpath/stift.gif" alt="$button" title="$button" /></a>
  577: ENDFORMULABUTTON
  578: }
  579: 
  580: sub end_mathresponse {
  581:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  582:     my $result;
  583:     my $part=$Apache::inputtags::part;
  584:     my $id=$Apache::inputtags::response[-1];
  585:     if ( $target eq 'grade' && &Apache::response::submitted() ) {
  586: 	my $response = &Apache::response::getresponse();
  587: 	if ( $response =~ /[^\s]/ ) {
  588: 	    if (!$Apache::lonxml::default_homework_loaded) {
  589: 		&Apache::lonxml::default_homework_load($safeeval);
  590: 	    }
  591: 	    my %previous = &Apache::response::check_for_previous($response,
  592: 								 $part,$id);
  593: 	    $Apache::lonhomework::results{"resource.$part.$id.submission"}=
  594: 		$response;
  595: 	    my $error;
  596: 	    my $award;
  597: 	    my $cas = &Apache::lonxml::get_param('cas',$parstack,$safeeval);
  598:             if ($cas eq 'maxima') {
  599:                 my $args = [&Apache::lonxml::get_param_var('args',$parstack,$safeeval)];
  600:                 $award=&Apache::lonmaxima::maxima_run($Apache::response::custom_answer[-1],$response,$args,
  601:                                                       &Apache::lonxml::get_param('libraries',$parstack,$safeeval));
  602:             }
  603:             if ($cas eq 'R') {
  604:                 my $args = [&Apache::lonxml::get_param_var('args',$parstack,$safeeval)];
  605:                 $award=&Apache::lonr::r_run($Apache::response::custom_answer[-1],$response,$args,
  606:                                             &Apache::lonxml::get_param('libraries',$parstack,$safeeval));
  607:             }
  608: 
  609: 	    if (!&Apache::inputtags::valid_award($award)) {
  610: 		$error = $award;
  611: 		$award = 'ERROR';
  612: 	    }
  613: 	    &Apache::response::handle_previous(\%previous,$award);
  614: 	    $Apache::lonhomework::results{"resource.$part.$id.awarddetail"}=
  615: 		$award;
  616: 	    if ($error) {
  617: 		$Apache::lonhomework::results{"resource.$part.$id.awardmsg"}=
  618: 		    $error;
  619: 	    }
  620: 	}
  621:     }
  622:     if ($target eq 'web') {
  623: 	&setup_prior_tries_hash(\&format_prior_response_math);
  624:         my $partid = $Apache::inputtags::part;
  625:         my $id = $Apache::inputtags::response[-1];
  626:         if (($Apache::inputtags::status['-1'] eq 'CAN_ANSWER')
  627:            && (&Apache::lonnet::EXT('resource.'.$partid.'_'.$id.'.turnoffeditor') ne 'yes')) {
  628:             $result.=&edit_mathresponse_button($id,"HWVAL_$id");
  629:         }
  630:     }
  631: 
  632:     pop(@Apache::lonxml::namespace);
  633:     pop(@Apache::response::custom_answer);
  634:     pop(@Apache::response::custom_answer_type);
  635:     &Apache::lonxml::deregister('Apache::response',('answer'));
  636:     &Apache::response::end_response();
  637:     return $result;
  638: }
  639: 
  640: sub format_prior_response_math {
  641:     my ($mode,$answer) =@_;
  642:     return '<span class="LC_prior_math">'.
  643: 	    &HTML::Entities::encode($answer,'"<>&').'</span>';
  644: }
  645: 
  646: sub implicit_multiplication {
  647:     my ($expression)=@_;
  648: # Escape scientific notation, so 3e8 does not become 3*e*8
  649: # 3e8 -> 3&8; 3e-8 -> 3&-8; 3E+8 -> e&+8
  650:     $expression=~s/(\d+)e([\+\-]*\d+)/$1\&\($2\)/gsi;
  651: # 3x10^8 -> 3&8; 3*10^-8 -> 3&-8
  652:     $expression=~s/(\d+)(?:x|\*)10(?:\^|\*\*)([\+\-]*\d+)/$1\&\($2\)/gsi;
  653: # Fill in multiplication signs
  654: # a b -> a*b;3 b -> 3*b;3 4 -> 3*4
  655:     $expression=~s/([A-Za-z0-9])\s+(?=[A-Za-z0-9])/$1\*/gs;
  656: # )( -> )*(; ) ( -> )*(
  657:     $expression=~s/\)\s*\(/\)\*\(/gs;
  658: # 3a -> 3*a; 3( -> 3*(; 3 ( -> 3*(; 3A -> 3*A
  659:     $expression=~s/(\d)\s*([a-zA-Z\(])/$1\*$2/gs;
  660: # a ( -> a*(
  661:     $expression=~s/([A-Za-z0-9])\s+\(/$1\*\(/gs;
  662: # )a -> )*a; )3 -> )*3; ) 3 -> )*3
  663:     $expression=~s/\)\s*([A-Za-z0-9])/\)\*$1/gs;
  664: # 3&8 -> 3e8; 3&-4 -> 3e-4
  665:     $expression=~s/(\d+)\&\(([\+\-]*\d+)\)/$1e$2/gs;
  666:     return $expression;
  667: }
  668: 
  669: sub start_answer {
  670:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  671:     my $result;
  672:     push(@Apache::response::custom_answer,
  673: 	&Apache::lonxml::get_all_text_unbalanced("/answer",$parser));
  674:     push(@Apache::response::custom_answer_type,
  675: 	lc(&Apache::lonxml::get_param('type',$parstack,$safeeval)));
  676:     $Apache::response::custom_answer_type[-1] =~ s/\s+//g;
  677:     if ($target eq "edit" ) {
  678: 	$result=&Apache::edit::tag_start($target,$token,'Answer algorithm');
  679: 	$result.=&Apache::edit::editfield($token->[1],
  680: 					  $Apache::response::custom_answer[-1],
  681: 					  '',80,4);
  682:     } elsif ( $target eq "modified" ) {
  683: 	$result=$token->[4].&Apache::edit::modifiedfield('/answer',$parser);
  684:     }
  685:     return $result;
  686: }
  687: 
  688: sub end_answer {
  689:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  690:     if ($target eq 'edit' ) {
  691: 	return &Apache::edit::end_table();
  692:     }
  693: }
  694: 
  695: sub decide_package {
  696:     my ($tagstack)=@_;
  697:     my $package;
  698:     if ($$tagstack[-1] eq 'parameter') {
  699: 	$package='part';
  700:     } else {
  701: 	my $i=-1;
  702: 	while (defined($$tagstack[$i])) {
  703: 	    if ($$tagstack[$i] =~ /(response|hint)$/) {
  704: 		$package=$$tagstack[$i];
  705: 		last;
  706: 	    }
  707: 	    $i--;
  708: 	}
  709:     }
  710:     return $package;
  711: }
  712: 
  713: sub start_responseparam {
  714:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  715:     my $result='';
  716:     if ($target eq 'meta') {
  717: 	$result = &meta_parameter_write($token->[2]->{'name'},
  718: 					$token->[2]->{'type'},
  719: 					$token->[2]->{'default'},
  720: 					$token->[2]->{'description'});
  721:     } elsif ($target eq 'edit') {
  722: 	$result.=&Apache::edit::tag_start($target,$token);
  723: 	my $optionlist;
  724: 	my $package=&decide_package($tagstack);
  725: 	foreach my $key (sort(keys(%Apache::lonnet::packagetab))) {
  726: 	    if ($key =~ /^\Q$package\E&(.*)&display$/) {
  727: 		$optionlist.='<option value="'.$1.'">'.
  728: 		    $Apache::lonnet::packagetab{$key}.'</option>';
  729: 	    }
  730: 	}
  731: 	if (defined($optionlist)) {
  732: 	    $result.=&mt('Use template:').' <select name="'.
  733: 		&Apache::edit::html_element_name('parameter_package').'">'.
  734: 		    '<option value=""></option>'.$optionlist.'</select><br />';
  735: 	}
  736: 	$result.=&Apache::edit::text_arg('Name:','name',$token).
  737: 	    &Apache::edit::text_arg('Type:','type',$token).
  738: 		&Apache::edit::text_arg('Description:','description',$token).
  739: 		    &Apache::edit::text_arg('Default:','default',$token).
  740: 			"</td></tr>";
  741: 	$result.=&Apache::edit::end_table;
  742:     } elsif ($target eq 'modified') {
  743: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  744: 						     $safeeval,'name','type',
  745: 						     'description','default');
  746: 	my $element=&Apache::edit::html_element_name('parameter_package');
  747: 	if (defined($env{"form.$element"}) && $env{"form.$element"} ne '') {
  748: 	    my $name=$env{"form.$element"};
  749: 	    my $tag=&decide_package($tagstack);
  750: 	    $token->[2]->{'name'}=$name;
  751: 	    $token->[2]->{'type'}=
  752: 		$Apache::lonnet::packagetab{"$tag&$name&type"};
  753: 	    $token->[2]->{'description'}=
  754: 		$Apache::lonnet::packagetab{"$tag&$name&display"};
  755: 	    $token->[2]->{'default'}=
  756: 		$Apache::lonnet::packagetab{"$tag&$name&default"};
  757:             $token->[3] = ['name','type','description','default'];
  758: 	    $constructtag=1;
  759: 	}
  760: 	if ($constructtag) {
  761: 	    $result = &Apache::edit::rebuild_tag($token);
  762: 	}
  763:     } elsif ($target eq 'grade' || $target eq 'answer' || $target eq 'web' ||
  764: 	     $target eq 'tex' || $target eq 'analyze' ) {
  765: 	if ($env{'request.state'} eq 'construct') {
  766: 	    my $name   =&Apache::lonxml::get_param('name',$parstack,$safeeval);
  767: 	    my $default=&Apache::lonxml::get_param('default',$parstack,
  768: 						     $safeeval);
  769: 	    if ($name) {$Apache::inputtags::params{$name}=$default;}
  770: 	}
  771:     }
  772:     return $result;
  773: }
  774: 
  775: sub end_responseparam {
  776:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  777:     if ($target eq 'edit') { return ('','no'); }
  778:     return '';
  779: }
  780: 
  781: sub start_parameter {
  782:     return &start_responseparam(@_);
  783: }
  784: 
  785: sub end_parameter {
  786:     return &end_responseparam(@_);
  787: }
  788: 
  789: sub reset_params {
  790:     %Apache::inputtags::params=();
  791: }
  792: 
  793: sub setup_params {
  794:     my ($tag,$safeeval) = @_;
  795: 
  796:     if ($env{'request.state'} eq 'construct') { return; }
  797:     my %paramlist=();
  798:     foreach my $key (keys(%Apache::lonnet::packagetab)) {
  799: 	if ($key =~ /^\Q$tag\E/) {
  800: 	    my ($package,$name) = split(/&/,$key);
  801: 	    $paramlist{$name}=1;
  802: 	}
  803:     }
  804:     foreach my $key (keys(%paramlist)) {
  805: 	my $entry= 'resource.'.$Apache::inputtags::part;
  806: 	if (defined($Apache::inputtags::response[-1])) {
  807: 	    $entry.='_'.$Apache::inputtags::response[-1];
  808: 	}
  809: 	$entry.='.'.$key;
  810: 	&Apache::lonxml::debug("looking for $entry");
  811: 	my $value = &Apache::lonnet::EXT("$entry");
  812: 	&Apache::lonxml::debug("$key has value :$value:");
  813: 	if ($value eq 'con_lost' || $value =~ /^error:/) {
  814: 	    &Apache::lonxml::debug("using nothing");
  815: 	    $Apache::inputtags::params{$key}='';
  816: 	} else {
  817: 	    my $string="{return qq\0".$value."\0}";
  818: 	    my $newvalue=&Apache::run::run($string,$safeeval,1);
  819: 	    if (defined($newvalue)) { $value=$newvalue; }
  820: 	    $Apache::inputtags::params{$key}=$value;
  821: 	}
  822:     }
  823: }
  824: 
  825: {
  826:     my @answer_bits;
  827:     my $need_row_start;
  828: 
  829: sub answer_header {
  830:     my ($type,$increment,$rows) = @_;
  831:     my $result;
  832:     if ($env{'form.answer_output_mode'} eq 'tex') {
  833: 	undef(@answer_bits);
  834: 	my $bit;
  835: 	if ($Apache::lonhomework::type eq 'exam') {
  836: 	    $bit = ($Apache::lonxml::counter+$increment).') ';
  837: 	} else {
  838: 	    $bit .= ' Answer for Part: \verb|'.
  839: 		$Apache::inputtags::part.'| ';
  840: 	}
  841: 	push(@answer_bits,$bit);
  842:     } else {
  843: 	my $td = '<td '.(defined($rows)?'rowspan="'.$rows.'"':'').'>';
  844: 	$result  = '<table border="1"><tr>';
  845: 	if ($Apache::lonhomework::type eq 'exam') {
  846: 	    $result .= $td.($Apache::lonxml::counter+$increment). ')</td>';
  847: 	} else {
  848: 	    $result .= $td.&mt('Answer for Part: [_1]',
  849: 			       $Apache::inputtags::part).'</td>';
  850: 	}
  851: 	$result .= "\n";
  852: 	$need_row_start = 0;
  853:     }
  854:     return $result;
  855: }
  856: 
  857: sub next_answer {
  858:     my ($type) = @_;
  859:     my $result;
  860:     if ($env{'form.answer_output_mode'} eq 'tex') {
  861: 	# FIXME ... need to do something with tex mode
  862:     } else {
  863: 	$result .= "</tr>";
  864: 	$need_row_start = 1;
  865:     }
  866:     return $result;
  867: }
  868: 
  869: sub answer_part {
  870:     my ($type,$answer,$args) = @_;
  871:     my $result;
  872:     if ($env{'form.answer_output_mode'} eq 'tex') {
  873: 	if (!$args->{'no_verbatim'}) {
  874: 	    my $to_use='|';
  875: 	    foreach my $value (32..126) {
  876: 		my $char=pack('c',$value);
  877: 		if ($answer !~ /\Q$char\E/) {
  878: 		    $to_use=$char;
  879: 		    last;
  880: 		}
  881: 	    }
  882:             my $fullanswer=$answer;
  883:             $answer='';
  884:             foreach my $element (split(/[\;]/,$fullanswer)) {
  885: 	       if ($element ne '') {
  886: 	 	  $answer.= '\verb'.$to_use.$element.$to_use.' \newline';
  887: 	       }
  888:             }
  889: 	}
  890: 	if ($answer ne '') {
  891: 	    push(@answer_bits,$answer);
  892: 	}
  893:     } else {
  894: 	if ($need_row_start) {
  895: 	    $result .= '<tr>';
  896: 	    $need_row_start = 0;
  897: 	}
  898: 	$result .= '<td>'.$answer.'</td>';
  899:     }
  900:     return $result;
  901: }
  902: 
  903: sub answer_footer {
  904:     my ($type) = @_;
  905:     my $result;
  906:     if ($env{'form.answer_output_mode'} eq 'tex') {
  907: 	$result  = ' \vskip 0 mm \noindent \begin{tabular}{|p{1.5cm}|p{6.8cm}|}\hline ';
  908: 	$result .= $answer_bits[0].'&\vspace*{-4mm}\begin{itemize}';
  909:         for (my $i=1;$i<=$#answer_bits;$i++) {
  910:             $result.='\item '.$answer_bits[$i].'\vspace*{-7mm}';
  911:         }
  912: 	$result .= ' \end{itemize} \\\\ \hline \end{tabular} \vskip 0 mm ';
  913:     } else {
  914: 	if (!$need_row_start) {
  915: 	    $result .= '</tr>';
  916: 	}
  917: 	$result .= '</table>';
  918:     }
  919:     return $result;
  920: }
  921: 
  922: }
  923: 
  924: sub showallfoils {
  925:     if (defined($env{'form.showallfoils'})) {
  926: 	my ($symb)=&Apache::lonnet::whichuser();
  927: 	if (($env{'request.state'} eq 'construct') || 
  928: 	    ($env{'user.adv'} && $symb eq '')      ||
  929:             ($Apache::lonhomework::viewgrades) ) {
  930: 	    return 1;
  931: 	}
  932:     }
  933:     if ($Apache::lonhomework::type eq 'survey') { return 1; }
  934:     if ($Apache::lonhomework::type eq 'surveycred') { return 1; }
  935:     if ($Apache::lonhomework::type eq 'anonsurvey') { return 1; }
  936:     if ($Apache::lonhomework::type eq 'anonsurveycred') { return 1; }
  937: 
  938:     return 0;
  939: }
  940: 
  941: =pod
  942: 
  943: =item &getresponse();
  944: 
  945: Retreives the current submitted response, helps out in the case of
  946: scantron mode.
  947: 
  948: Returns either the exact text of the submission, or a bubbled response
  949: converted to something usable.
  950: 
  951: Optional Arguments:
  952:   $offset - (defaults to 1) if a problem has more than one bubble
  953:             response, pass in the number of the bubble wanted, (the
  954:             first bubble associated with a problem has an offset of 1,
  955:             the second bubble is 2
  956: 
  957:   $resulttype - undef    -> a number between 0 and 25
  958:                 'A is 1' -> a number between 1 and 26
  959:                 'letter' -> a letter between 'A' and 'Z'
  960:   $lines  - undef problem only needs a single line of bubbles.
  961:             nonzero  Problem wants the first nonempty response in 
  962:                       $lines lines of bubbles.
  963:   $bubbles_per_line - Must be provided if lines is defined.. number of
  964:                       bubbles on a line.
  965: 
  966: =cut
  967: 
  968: sub getresponse {
  969:     my ($offset,$resulttype, $lines, $bubbles_per_line)=@_;
  970:     my $formparm='form.HWVAL_'.$Apache::inputtags::response['-1'];
  971:     my $response;
  972:     if (!defined($offset)) {
  973: 	$offset=1;
  974:     } else {
  975: 	$formparm.=":$offset";
  976:     }
  977:     if (!defined($lines)) {
  978: 	$lines = 1;
  979:     }
  980:     my %let_to_num=('A'=>0,'B'=>1,'C'=>2,'D'=>3,'E'=>4,'F'=>5,'G'=>6,'H'=>7,
  981: 		    'I'=>8,'J'=>9,'K'=>10,'L'=>11,'M'=>12,'N'=>13,'O'=>14,
  982: 		    'P'=>15,'Q'=>16,'R'=>17,'S'=>18,'T'=>19,'U'=>20,'V'=>21,
  983: 		    'W'=>22,'X'=>23,'Y'=>24,'Z'=>25);
  984:     if ($env{'form.submitted'} eq 'scantron') {
  985: 	my $part  = $Apache::inputtags::part;
  986: 	my $id    = $Apache::inputtags::response[-1];
  987: 	
  988: 	my $line;
  989: 	my $startline = $env{'form.scantron_questnum_start.'.$part.'.'.$id};
  990:         if (!$startline) {
  991:             $startline = $Apache::lonxml::counter;
  992:         }
  993: 	for ($line = 0; $line < $lines; $line++) {
  994:             my $theline = $startline+$offset-1+$line;
  995: 	    $response = $env{"scantron.$theline.answer"};
  996: 	    if ((defined($response)) && ($response ne "") && ($response ne " ")) {
  997: 		last;
  998: 	    }
  999:  
 1000: 	}
 1001: 
 1002: 	# save bubbled letter for later
 1003: 	$Apache::lonhomework::results{"resource.$part.$id.scantron"}.=
 1004: 	    $response;
 1005: 	if ($resulttype ne 'letter') {
 1006: 	    if ($resulttype eq 'A is 1') {
 1007: 		$response = $let_to_num{$response}+1;
 1008: 	    } else {
 1009: 		$response = $let_to_num{$response};
 1010: 	    }
 1011: 	    if ($response ne "") {
 1012: 		$response += $line * $bubbles_per_line;
 1013: 	    }
 1014: 	} else {
 1015: 	    if ($response ne "") {
 1016: 		$response = chr(ord($response) + $line * $bubbles_per_line);
 1017: 	    }
 1018: 	}
 1019: 
 1020:     } else {
 1021: 	$response = $env{$formparm};
 1022:     }
 1023:     # 
 1024:     #  If we have a nonempty answer, correct the numeric value
 1025:     #  of the answer for the line on which it was found.
 1026:     #
 1027: 
 1028:     return $response;
 1029: }
 1030: 
 1031: =pod
 1032: 
 1033: =item &repetition();
 1034: 
 1035: Returns the number of lines that are required to encode the weight.
 1036: (Currently expects that there are 10 bubbles per line)
 1037: 
 1038: =cut
 1039: 
 1040: sub repetition {
 1041:     my $id = $Apache::inputtags::part;
 1042:     my $weight = &Apache::lonnet::EXT("resource.$id.weight");
 1043:     if (!defined($weight) || ($weight eq '')) { $weight=1; }
 1044:     my $repetition = int($weight/10);
 1045:     if ($weight % 10 != 0) { $repetition++; } 
 1046:     return $repetition;
 1047: }
 1048: 
 1049: =pod
 1050: 
 1051: =item &scored_response();
 1052: 
 1053: Sets the results hash elements
 1054: 
 1055:    resource.$part_id.$response_id.awarded - to the floating point
 1056:      number between 0 and 1 that was awarded on the bubbled input
 1057: 
 1058:    resource.$part_id.$response_id.awarddetail - to 'ASSIGNED_SCORE'
 1059: 
 1060: Returns
 1061: 
 1062:    the number of bubble sheet lines that were used (and likely need to
 1063:      be passed to &Apache::lonxml::increment_counter()
 1064: 
 1065: Arguments
 1066: 
 1067:    $part_id - id of the part to grade
 1068:    $response_id - id of the response to grade
 1069:   
 1070: 
 1071: =cut
 1072: 
 1073: sub scored_response {
 1074:     my ($part,$id)=@_;
 1075:     my $repetition=&repetition();
 1076:     my $score=0;
 1077:     for (my $i=0;$i<$repetition;$i++) {
 1078: 	# A is 1, B is 2, etc. (get response return 0-9 and then we add 1)
 1079: 	my $increase=&Apache::response::getresponse($i+1);
 1080: 	if ($increase ne '') { $score+=$increase+1; }
 1081:     }
 1082:     my $weight = &Apache::lonnet::EXT("resource.$part.weight");
 1083:     if (!defined($weight) || $weight eq '' || $weight eq 0) { $weight = 1; }
 1084:     my $pcr=$score/$weight;
 1085:     $Apache::lonhomework::results{"resource.$part.$id.awarded"}=$pcr;
 1086:     $Apache::lonhomework::results{"resource.$part.$id.awarddetail"}=
 1087: 	'ASSIGNED_SCORE';
 1088:     return $repetition;
 1089: }
 1090: 
 1091: sub whichorder {
 1092:     my ($max,$randomize,$showall,$hash,$rndseed)=@_;
 1093:     #&Apache::lonxml::debug("man $max randomize $randomize");
 1094:     if (!defined(@{ $$hash{'names'} })) { return; }
 1095:     my @names = @{ $$hash{'names'} };
 1096:     my @whichopt =();
 1097:     my (%top,@toplist,%bottom,@bottomlist);
 1098:     if (!($showall || ($randomize eq 'no'))) {
 1099: 	my $current=0;
 1100: 	foreach my $name (@names) {
 1101: 	    $current++;
 1102: 	    if ($$hash{"$name.location"} eq 'top') {
 1103: 		$top{$name}=$current;
 1104: 	    } elsif ($$hash{"$name.location"} eq 'bottom') {
 1105: 		$bottom{$name}=$current;
 1106: 	    }
 1107: 	}
 1108:     }
 1109:     my $topcount=0;
 1110:     my $bottomcount=0;
 1111:     while (((scalar(@whichopt)+$topcount+$bottomcount) < $max || $showall)
 1112: 	   && ($#names > -1)) {
 1113: 	#&Apache::lonxml::debug("Have $#whichopt max is $max");
 1114: 	my $aopt;
 1115: 	if ($showall || ($randomize eq 'no')) {
 1116: 	    $aopt=0;
 1117: 	} else {
 1118: 	    $aopt=int(&Math::Random::random_uniform() * ($#names+1));
 1119: 	}
 1120: 	#&Apache::lonxml::debug("From $#whichopt $max $#names elms, picking $aopt");
 1121: 	$aopt=splice(@names,$aopt,1);
 1122: 	#&Apache::lonxml::debug("Picked $aopt");
 1123: 	if ($top{$aopt}) {
 1124: 	    $toplist[$top{$aopt}]=$aopt;
 1125: 	    $topcount++;
 1126: 	} elsif ($bottom{$aopt}) {
 1127: 	    $bottomlist[$bottom{$aopt}]=$aopt;
 1128: 	    $bottomcount++;
 1129: 	} else {
 1130: 	    push (@whichopt,$aopt);
 1131: 	}
 1132:     }
 1133:     for (my $i=0;$i<=$#toplist;$i++) {
 1134: 	if ($toplist[$i]) { unshift(@whichopt,$toplist[$i]) }
 1135:     }
 1136:     for (my $i=0;$i<=$#bottomlist;$i++) {
 1137: 	if ($bottomlist[$i]) { push(@whichopt,$bottomlist[$i]) }
 1138:     }
 1139:     return @whichopt;
 1140: }
 1141: 
 1142: sub show_answer {
 1143:     my $part   = $Apache::inputtags::part;
 1144:     my $award  = $Apache::lonhomework::history{"resource.$part.awarded"};
 1145:     my $status = $Apache::inputtags::status[-1];
 1146:     return  ( ($award ==1
 1147: 	       && &Apache::lonhomework::show_problem_status())
 1148: 	      || $status eq "SHOW_ANSWER");
 1149: }
 1150: 
 1151: sub analyze_store_foilgroup {
 1152:     my ($shown,$attrs)=@_;
 1153:     my $part_id="$Apache::inputtags::part.$Apache::inputtags::response[-1]";
 1154:     foreach my $name (@{ $Apache::response::foilgroup{'names'} }) {
 1155: 	if (defined($Apache::lonhomework::analyze{"$part_id.foil.value.$name"})) { next; }
 1156: 	push (@{ $Apache::lonhomework::analyze{"$part_id.foils"} },$name);
 1157: 	foreach my $attr (@$attrs) {
 1158: 	    $Apache::lonhomework::analyze{"$part_id.foil.".$attr.".$name"} =
 1159: 		$Apache::response::foilgroup{"$name.".$attr};
 1160: 	}
 1161:     }
 1162:     push (@{ $Apache::lonhomework::analyze{"$part_id.shown"} }, @{ $shown });
 1163: }
 1164: 
 1165: sub check_if_computed {
 1166:     my ($token,$parstack,$safeeval,$name)=@_;
 1167:     my $value = &Apache::lonxml::get_param($name,$parstack,$safeeval);
 1168:     if (ref($token->[2]) eq 'HASH' && $value ne $token->[2]{$name}) {
 1169: 	my $part_id="$Apache::inputtags::part.$Apache::inputtags::response[-1]";
 1170: 	$Apache::lonhomework::analyze{"$part_id.answercomputed"} = 1;
 1171:     }
 1172: }
 1173: 
 1174: sub pick_foil_for_concept {
 1175:     my ($target,$attrs,$hinthash,$parstack,$safeeval)=@_;
 1176:     if (not defined(@{ $Apache::response::conceptgroup{'names'} })) { return; }
 1177:     my @names = @{ $Apache::response::conceptgroup{'names'} };
 1178:     my $pick=int(&Math::Random::random_uniform() * ($#names+1));
 1179:     my $name=$names[$pick];
 1180:     push @{ $Apache::response::foilgroup{'names'} }, $name;
 1181:     foreach my $attr (@$attrs) {
 1182: 	$Apache::response::foilgroup{"$name.".$attr} =
 1183: 	    $Apache::response::conceptgroup{"$name.".$attr};
 1184:     }
 1185:     my $concept = &Apache::lonxml::get_param('concept',$parstack,$safeeval);
 1186:     $Apache::response::foilgroup{"$name.concept"} = $concept;
 1187:     &Apache::lonxml::debug("Selecting $name in $concept");
 1188:     my $part_id="$Apache::inputtags::part.$Apache::inputtags::response[-1]";
 1189:     if ($target eq 'analyze') {
 1190: 	push (@{ $Apache::lonhomework::analyze{"$part_id.concepts"} },
 1191: 	      $concept);
 1192: 	$Apache::lonhomework::analyze{"$part_id.concept.$concept"}=
 1193: 	    $Apache::response::conceptgroup{'names'};
 1194: 	foreach my $name (@{ $Apache::response::conceptgroup{'names'} }) {
 1195: 	    push (@{ $Apache::lonhomework::analyze{"$part_id.foils"} },
 1196: 		  $name);
 1197: 	    foreach my $attr (@$attrs) {
 1198: 		$Apache::lonhomework::analyze{"$part_id.foil.$attr.$name"}=
 1199: 		    $Apache::response::conceptgroup{"$name.$attr"};
 1200: 	    }
 1201: 	}
 1202:     }
 1203:     push(@{ $hinthash->{"$part_id.concepts"} },$concept);
 1204:     $hinthash->{"$part_id.concept.$concept"}=
 1205: 	$Apache::response::conceptgroup{'names'};
 1206: 
 1207: }
 1208: 
 1209: =pod
 1210: 
 1211: =item get_response_param()
 1212: 
 1213: Get a parameter associated with a problem.
 1214: Parameters:
 1215: 	$id        - the id of the paramater, either a part id, 
 1216:               or a partid and responspe id joined by _
 1217: 	$name      - Name of the parameter to fetch
 1218: 	$default   - Default value for the paramter.
 1219: 
 1220: =cut
 1221: 
 1222: sub get_response_param {
 1223:     my ($id,$name,$default)=@_;
 1224:     my $parameter;
 1225:     if ($env{'request.state'} eq 'construct' &&
 1226: 	defined($Apache::inputtags::params{$name})) {
 1227: 	$parameter=$Apache::inputtags::params{$name};
 1228:     } else {
 1229: 	$parameter=&Apache::lonnet::EXT("resource.$id.$name");
 1230:     }
 1231:     if (!defined($parameter) ||	$parameter eq '') {
 1232: 	$parameter = $default;
 1233:     }
 1234:     return $parameter;
 1235: }
 1236: 
 1237: sub submitted {
 1238:     my ($who)=@_;
 1239:     
 1240:     # when scatron grading any submission is a submission
 1241:     if ($env{'form.submitted'} eq 'scantron') { return 1; }
 1242:     # if the caller only cared if this was a scantron submission
 1243:     if ($who eq 'scantron') { return 0; }
 1244:     # if the Submit Answer button for this particular part was pressed
 1245:     my $partid=$Apache::inputtags::part;
 1246:     if ($env{'form.submitted'} eq "part_$partid") {
 1247: 	return 1;
 1248:     }
 1249:     if ($env{'form.submitted'} eq "yes"
 1250: 	&& defined($env{'form.submit_'.$partid})) {
 1251: 	return 1;
 1252:     }
 1253:     # Submit All button on a .page was pressed
 1254:     if (defined($env{'form.all_submit'})) { return 1; }
 1255:     # otherwise no submission occurred
 1256:     return 0;
 1257: }
 1258: 
 1259: sub add_to_gradingqueue {
 1260:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
 1261:     if (   $courseid eq ''
 1262: 	|| $symb eq ''
 1263: 	|| $env{'request.state'} eq 'construct'
 1264: 	|| $Apache::lonhomework::type ne 'problem') {
 1265: 	return;
 1266:     }
 1267: 
 1268:     my %queue_info = ( 'type' => 'problem',
 1269: 		       'time' => time);
 1270: 
 1271:     if (exists($Apache::lonhomework::history{"resource.0.checkedin.slot"})) {
 1272: 	$queue_info{'slot'}=
 1273: 	     $Apache::lonhomework::history{"resource.0.checkedin.slot"};
 1274:     }
 1275: 
 1276:     my $result=&Apache::bridgetask::add_to_queue('gradingqueue',\%queue_info);
 1277:     if ($result ne 'ok') {
 1278: 	&Apache::lonxml::error("add_to_queue said $result");
 1279:     }
 1280: }
 1281: 
 1282: =pod 
 1283: 
 1284: =item check_status()
 1285: 
 1286: basically undef and 0 (both false) mean that they still have work to do
 1287: and all true values mean that they can't do any more work
 1288: 
 1289: 	a return of undef means it is unattempted
 1290: 	a return of 0 means it is attmpted and wrong but still has tries
 1291: 	a return of 1 means it is marked correct
 1292: 	a return of 2 means they have exceed maximum number of tries
 1293: 	a return of 3 means it after the answer date
 1294: 
 1295: =cut
 1296: 
 1297: sub check_status {
 1298:     my ($id)=@_;
 1299:     if (!defined($id)) { $id=$Apache::inputtags::part; }
 1300:     my $curtime=&Apache::lonnet::EXT('system.time');
 1301:     my $opendate=&Apache::lonnet::EXT("resource.$id.opendate");
 1302:     my $duedate=&Apache::lonnet::EXT("resource.$id.duedate");
 1303:     my $answerdate=&Apache::lonnet::EXT("resource.$id.answerdate");
 1304:     if ( $opendate && $curtime > $opendate &&
 1305:          $duedate && $curtime > $duedate &&
 1306:          $answerdate && $curtime > $answerdate) {
 1307:         return 3;
 1308:     }
 1309:     my $status=&Apache::lonnet::EXT("user.resource.resource.$id.solved");
 1310:     if ($status =~ /^correct/) { return 1; }
 1311:     if (!$status) { return undef; }
 1312:     my $maxtries=&Apache::lonnet::EXT("resource.$id.maxtries");
 1313:     if ($maxtries eq '') { $maxtries=2; }
 1314:     my $curtries=&Apache::lonnet::EXT("user.resource.resource.$id.tries");
 1315:     if ($curtries < $maxtries) { return 0; }
 1316:     return 2;
 1317: }
 1318: 
 1319: =pod
 1320: 
 1321: =item setup_prior_tries_hash()
 1322: 
 1323:   Foreach each past .submission $func is called with 3 arguments
 1324:      - the mode to set things up for (currently always 'grade')
 1325:      - the stored .submission string
 1326:      - The expansion of $data
 1327: 
 1328:   $data is an array ref containing elements that are either
 1329:     - scalars that are other elements of the history hash to pass to $func
 1330:     - ref to data to be passed untouched to $func
 1331: 
 1332:   $questiontype is the questiontype (currently only passed in if
 1333:       randomizebytry.
 1334: 
 1335: =cut
 1336: 
 1337: sub setup_prior_tries_hash {
 1338:     my ($func,$data,$questiontype) = @_;
 1339:     my $part = $Apache::inputtags::part;
 1340:     my $id   = $Apache::inputtags::response[-1];
 1341:     foreach my $i (1..$Apache::lonhomework::history{'version'}) {
 1342:         my $partprefix = "$i:resource.$part";
 1343: 	my $sub_key   = "$partprefix.$id.submission";
 1344: 	next if (!exists($Apache::lonhomework::history{$sub_key}));
 1345:         my $type_key = "$partprefix.type";
 1346:         my $type = $Apache::lonhomework::history{$type_key};
 1347: 	my @other_data;
 1348:         if (ref($data) eq 'ARRAY') {
 1349: 	    foreach my $datum (@{ $data }) {
 1350: 	        if (ref($datum)) {
 1351: 		    push(@other_data,$datum);
 1352: 	        } else {
 1353: 		    my $info_key = "$i:resource.$part.$id.$datum";
 1354: 		    push(@other_data,$Apache::lonhomework::history{$info_key});
 1355: 	        }
 1356: 	    }
 1357:         }
 1358:         if ($questiontype eq 'randomizetry') { 
 1359:             my $order_key = "$partprefix.$id.foilorder";
 1360:             my @whichopts = &Apache::lonnet::str2array($Apache::lonhomework::history{$order_key});
 1361:             if (@whichopts > 0) {
 1362:                 shift(@other_data);
 1363:                 unshift(@other_data,\@whichopts);
 1364:             }
 1365:         }
 1366: 	my $output =
 1367: 	    &$func('grade',
 1368: 		   $Apache::lonhomework::history{$sub_key},
 1369: 		   \@other_data);
 1370: 	if (defined($output)) {
 1371: 	    $Apache::inputtags::submission_display{$sub_key} = $output;
 1372: 	}
 1373:     }
 1374: }
 1375: 
 1376: 1;
 1377: __END__
 1378:  
 1379: =pod
 1380: 
 1381: =cut

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