File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.217: download - view: text, annotated - select for diffs
Sun Feb 28 23:44:36 2010 UTC (14 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: PRINT_INCOMPLETE_base, PRINT_INCOMPLETE, HEAD
- Bug 6119 Anonymous Surveys.
  - additional survey types: anonsurvey, anonsurvey_cred, survey_cred.

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

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