File:  [LON-CAPA] / loncom / homework / response.pm
Revision 1.238: download - view: text, annotated - select for diffs
Tue Dec 30 20:03:10 2014 UTC (9 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Changes in args passed to &edit_mathresponse_button() to support use of
  id attributes by LON-CAPA Math editor.
- DragMath implementation now also uses id attributes.
- Support math editor in formularesponse and mathresponse items in
  composite pages (.page).

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

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