File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.216: download - view: text, annotated - select for diffs
Sun May 24 13:08:18 2009 UTC (14 years, 11 months ago) by www
Branches: MAIN
CVS tags: version_2_9_X, version_2_9_99_0, version_2_9_1, version_2_9_0, version_2_8_99_1, version_2_8_99_0, bz6209-base, bz6209, bz5969, bz2851, HEAD, GCI_3, GCI_2, BZ5971-printing-apage
Bug #2802: partial credit multiple answers

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

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