Annotation of loncom/homework/response.pm, revision 1.213

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

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