File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.210: download - view: text, annotated - select for diffs
Tue Dec 23 18:09:36 2008 UTC (15 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Restore pre-1.207 functionality to &mandatory_part_meta().
- Eliminate previously commented out code (commented out in rev 1.34 - 8/2001)     - moved to POD in 1.207.
- Eliminate unbalanced 'back' from POD.
- Remove args from subroutine titles in POD items so perldoc underlines them.
- Move POD for &mandatory_part_meta() so it precedes subroutine.

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

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