File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.221.2.1: download - view: text, annotated - select for diffs
Sat Oct 8 20:51:30 2011 UTC (12 years, 6 months ago) by raeburn
Branches: version_2_10_X
Diff to branchpoint 1.221: preferred, unified
- Backport 1.225.

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

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