File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.220: download - view: text, annotated - select for diffs
Wed Nov 24 00:10:06 2010 UTC (13 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Need more room for good answers

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

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