File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.229: download - view: text, annotated - select for diffs
Tue Nov 29 17:43:30 2011 UTC (12 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
Displaying previous tries for customresponse.
  - Actually use &format_prior_response_custom().
  - Check if submission is an array (e.g., custompartial.problem template).

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

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