File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.241: download - view: text, annotated - select for diffs
Mon Feb 23 19:46:19 2015 UTC (9 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Modify how information from user agent is used to determine whether pop-up
  dragmath applet (java) or inline math preview (javascript) should be
  offered. Work in progress.

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

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