File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.246: download - view: text, annotated - select for diffs
Wed Jun 6 18:39:55 2018 UTC (5 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support retrypartial parameter in &check_status().

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

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