Annotation of loncom/homework/caparesponse/caparesponse.pm, revision 1.265

1.3       albertel    1: # The LearningOnline Network with CAPA
                      2: # caparesponse definition
1.47      albertel    3: #
1.265   ! raeburn     4: # $Id: caparesponse.pm,v 1.264 2024/09/29 01:58:43 raeburn Exp $
1.47      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.3       albertel   28: 
                     29: package Apache::caparesponse;
                     30: use strict;
1.4       albertel   31: use capa;
1.190     albertel   32: use Safe::Hole;
                     33: use Apache::lonmaxima();
1.129     www        34: use Apache::lonlocal;
1.166     albertel   35: use Apache::lonnet;
1.241     raeburn    36: use Apache::lonmsg();
1.202     www        37: use Apache::response();
1.194     albertel   38: use Storable qw(dclone);
1.251     foxr       39: use Apache::lonnet;
1.3       albertel   40: 
1.50      harris41   41: BEGIN {
1.194     albertel   42:     &Apache::lonxml::register('Apache::caparesponse',('numericalresponse','stringresponse','formularesponse'));
1.3       albertel   43: }
                     44: 
1.181     albertel   45: my %answer;
1.204     albertel   46: my @answers;
1.251     foxr       47: my @alphabet=('A'..'Z');
                     48: 
1.203     albertel   49: sub get_answer { return %answer; };
1.204     albertel   50: sub push_answer{ push(@answers,dclone(\%answer)); undef(%answer) }
                     51: sub pop_answer { %answer = %{pop(@answers)}; };
1.203     albertel   52: 
1.181     albertel   53: my $cur_name;
1.195     albertel   54: my $tag_internal_answer_name = 'INTERNAL';
                     55: 
1.181     albertel   56: sub start_answer {
                     57:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                     58:     my $result;
                     59:     $cur_name = &Apache::lonxml::get_param('name',$parstack,$safeeval);
                     60:     if ($cur_name =~ /^\s*$/) { $cur_name = $Apache::lonxml::curdepth; }
                     61:     my $type = &Apache::lonxml::get_param('type',$parstack,$safeeval);
                     62:     if (!defined($type) && $tagstack->[-2] eq 'answergroup') {
                     63: 	$type = &Apache::lonxml::get_param('type',$parstack,$safeeval,-2);
                     64:     }
                     65:     if (!defined($type)) { $type = 'ordered' };
                     66:     $answer{$cur_name}= { 'type' => $type,
                     67: 			  'answers' => [] };
1.208     albertel   68:     if ($target eq 'edit') {
                     69:   	$result.=&Apache::edit::tag_start($target,$token);
                     70: 	$result.=&Apache::edit::text_arg('Name:','name',$token);
                     71: 	$result.=&Apache::edit::select_arg('Type:','type',
                     72: 					   [['ordered',  'Ordered'  ],
                     73: 					    ['unordered','Unordered'],],
                     74: 					   $token);
                     75: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
                     76:     } elsif ($target eq 'modified') {
                     77: 	my $constructtag = &Apache::edit::get_new_args($token,$parstack,
                     78: 						       $safeeval,'name',
                     79: 						       'type');
                     80: 	if ($constructtag) {
                     81: 	    $result = &Apache::edit::rebuild_tag($token);
                     82: 	    $result.= &Apache::edit::handle_insert();
                     83: 	}
                     84:     }
1.181     albertel   85:     return $result;
                     86: }
                     87: 
                     88: sub end_answer {
                     89:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                     90:     my $result;
1.208     albertel   91:     if ($target eq 'edit') {
                     92: 	$result .= &Apache::edit::tag_end();
                     93:     }
                     94: 
1.181     albertel   95:     undef($cur_name);
                     96:     return $result;
                     97: }
                     98: 
1.208     albertel   99: sub insert_answer {
                    100:     return '
                    101:         <answer>
                    102:             <value></value>
                    103:         </answer>';
                    104: }
                    105: 
1.181     albertel  106: sub start_answergroup {
                    107:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                    108:     my $result;
1.208     albertel  109:     if ($target eq 'edit') {
                    110:   	$result.=&Apache::edit::tag_start($target,$token);
                    111: 	$result.=&Apache::edit::select_arg('Type:','type',
                    112: 					   [['ordered',  'Ordered'  ],
                    113: 					    ['unordered','Unordered'],],
                    114: 					   $token);
                    115: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
                    116:     } elsif ($target eq 'modified') {
                    117: 	my $constructtag = &Apache::edit::get_new_args($token,$parstack,
                    118: 						       $safeeval,'name',
                    119: 						       'type');
                    120: 	if ($constructtag) {
                    121: 	    $result = &Apache::edit::rebuild_tag($token);
                    122: 	    $result.= &Apache::edit::handle_insert();
                    123: 	}
                    124:     }
1.181     albertel  125:     return $result;
                    126: }
                    127: 
                    128: sub end_answergroup {
                    129:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                    130:     my $result;
1.194     albertel  131:     if ($target eq 'web') {
                    132:     	if (  &Apache::response::show_answer() ) {  
                    133: 	    my $partid = $Apache::inputtags::part;
                    134: 	    my $id = $Apache::inputtags::response[-1];
                    135: 	    &set_answertext($Apache::lonhomework::history{"resource.$partid.$id.answername"},
                    136: 			    $target,$token,$tagstack,$parstack,$parser,
                    137: 			    $safeeval,-2);
                    138: 	}
1.208     albertel  139:     } elsif ($target eq 'edit') {
                    140: 	$result .= &Apache::edit::tag_end();
1.194     albertel  141:     }
1.181     albertel  142:     return $result;
                    143: }
                    144: 
1.208     albertel  145: sub insert_answergroup {
                    146:     return '
                    147:     <answergroup>
                    148:         <answer>
                    149:             <value></value>
                    150:         </answer>
                    151:     </answergroup>';
                    152: }
                    153: 
1.181     albertel  154: sub start_value {
1.182     albertel  155:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.181     albertel  156:     my $result;
                    157:     if ( $target eq 'web' || $target eq 'tex' ||
                    158: 	 $target eq 'grade' || $target eq 'webgrade' ||
                    159: 	 $target eq 'answer' || $target eq 'analyze' ) {
1.182     albertel  160: 	my $bodytext = &Apache::lonxml::get_all_text("/value",$parser,$style);
1.181     albertel  161: 	$bodytext = &Apache::run::evaluate($bodytext,$safeeval,
                    162: 					   $$parstack[-1]);
1.195     albertel  163: 	
                    164: 	push(@{ $answer{$cur_name}{'answers'} },[$bodytext]);
                    165: 	
1.208     albertel  166:     } elsif ($target eq 'edit') {
                    167:   	$result.=&Apache::edit::tag_start($target,$token);
                    168: 	my $bodytext = &Apache::lonxml::get_all_text("/value",$parser,$style);
                    169: 	$result.=&Apache::edit::editline($token->[1],$bodytext,undef,40).
                    170: 	    &Apache::edit::end_row();
                    171:     } elsif ($target eq 'modified') {
                    172: 	$result=$token->[4].&Apache::edit::modifiedfield('/value',$parser);
1.181     albertel  173:     }
                    174:     return $result;
                    175: }
                    176: 
                    177: sub end_value {
                    178:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                    179:     my $result;
1.208     albertel  180:     if ($target eq 'edit') {
                    181: 	$result = &Apache::edit::end_table();
                    182:     }
1.181     albertel  183:     return $result;
                    184: }
                    185: 
1.208     albertel  186: sub insert_value {
                    187:     return '
                    188:             <value></value>';
                    189: }
                    190: 
1.195     albertel  191: sub start_vector {
                    192:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    193:     my $result;
                    194:     if ( $target eq 'web' || $target eq 'tex' ||
                    195: 	 $target eq 'grade' || $target eq 'webgrade' ||
                    196: 	 $target eq 'answer' || $target eq 'analyze' ) {
                    197: 	my $bodytext = &Apache::lonxml::get_all_text("/vector",$parser,$style);
                    198: 	my @values = &Apache::run::run($bodytext,$safeeval,$$parstack[-1]);
                    199: 	if (@values == 1) {
                    200: 	    @values = split(',',$values[0]);
                    201: 	}
                    202: 	push(@{ $answer{$cur_name}{'answers'} },\@values);
1.208     albertel  203:     } elsif ($target eq 'edit') {
                    204:   	$result.=&Apache::edit::tag_start($target,$token);
                    205: 	my $bodytext = &Apache::lonxml::get_all_text("/vector",$parser,$style);
                    206: 	$result.=&Apache::edit::editline($token->[1],$bodytext,undef,40).
                    207: 	    &Apache::edit::end_row();
                    208:     } elsif ($target eq 'modified') {
                    209: 	$result=$token->[4].&Apache::edit::modifiedfield('/vector',$parser);
1.195     albertel  210:     }
                    211:     return $result;
                    212: }
                    213: 
                    214: sub end_vector {
                    215:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                    216:     my $result;
1.208     albertel  217:     if ($target eq 'edit') {
                    218: 	$result = &Apache::edit::end_table();
                    219:     }
1.195     albertel  220:     return $result;
                    221: }
                    222: 
1.208     albertel  223: sub insert_vector {
                    224:     return '
                    225:             <value></value>';
                    226: }
                    227: 
1.181     albertel  228: sub start_array {
1.182     albertel  229:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.181     albertel  230:     my $result;
                    231:     if ( $target eq 'web' || $target eq 'tex' ||
                    232: 	 $target eq 'grade' || $target eq 'webgrade' ||
                    233: 	 $target eq 'answer' || $target eq 'analyze' ) {
1.182     albertel  234: 	my $bodytext = &Apache::lonxml::get_all_text("/array",$parser,$style);
1.181     albertel  235: 	my @values = &Apache::run::evaluate($bodytext,$safeeval,
                    236: 					    $$parstack[-1]);
                    237: 	push(@{ $answer{$cur_name}{'answers'} },@values);
                    238:     }
                    239:     return $result;
                    240: }
                    241: 
                    242: sub end_array {
                    243:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                    244:     my $result;
                    245:     return $result;
                    246: }
                    247: 
                    248: sub start_unit {
                    249:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                    250:     my $result;
                    251:     return $result;
                    252: }
                    253: 
                    254: sub end_unit {
                    255:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                    256:     my $result;
                    257:     return $result;
                    258: }
                    259: 
1.89      albertel  260: sub start_numericalresponse {
                    261:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
1.195     albertel  262:     &Apache::lonxml::register('Apache::caparesponse',
                    263: 			      ('answer','answergroup','value','array','unit',
                    264: 			       'vector'));
1.208     albertel  265:     push(@Apache::lonxml::namespace,'caparesponse');
1.89      albertel  266:     my $id = &Apache::response::start_response($parstack,$safeeval);
                    267:     my $result;
1.181     albertel  268:     undef(%answer);
                    269:     undef(%{$safeeval->varglob('LONCAPA::CAPAresponse_args')});
1.89      albertel  270:     if ($target eq 'edit') {
                    271: 	$result.=&Apache::edit::tag_start($target,$token);
                    272: 	$result.=&Apache::edit::text_arg('Answer:','answer',$token);
                    273: 	if ($token->[1] eq 'numericalresponse') {
1.122     albertel  274: 	    $result.=&Apache::edit::text_arg('Incorrect Answers:','incorrect',
1.149     www       275: 					     $token).
                    276: 		&Apache::loncommon::help_open_topic('numerical_wrong_answers');
1.89      albertel  277: 	    $result.=&Apache::edit::text_arg('Unit:','unit',$token,5).
                    278: 		&Apache::loncommon::help_open_topic('Physical_Units');
                    279: 	    $result.=&Apache::edit::text_arg('Format:','format',$token,4).
                    280: 		&Apache::loncommon::help_open_topic('Numerical_Response_Format');
                    281: 	} elsif ($token->[1] eq 'formularesponse') {
                    282: 	    $result.=&Apache::edit::text_arg('Sample Points:','samples',
                    283: 					     $token,40).
                    284: 	      &Apache::loncommon::help_open_topic('Formula_Response_Sampling');
                    285: 	}
1.248     www       286:         $result.=&Apache::edit::text_arg('Pre-Processor Subroutine:','preprocess',
                    287:                                              $token,10);
1.89      albertel  288: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
                    289:     } elsif ($target eq 'modified') {
                    290: 	my $constructtag;
                    291: 	if ($token->[1] eq 'numericalresponse') {
                    292: 	    $constructtag=&Apache::edit::get_new_args($token,$parstack,
                    293: 						      $safeeval,'answer',
1.156     albertel  294:  						      'incorrect','unit',
1.248     www       295: 						      'format','preprocess');
1.89      albertel  296: 	} elsif ($token->[1] eq 'formularesponse') {
                    297: 	    $constructtag=&Apache::edit::get_new_args($token,$parstack,
                    298: 						      $safeeval,'answer',
1.250     www       299: 						      'samples','preprocess');
1.89      albertel  300: 	}
                    301: 	if ($constructtag) {
                    302: 	    $result = &Apache::edit::rebuild_tag($token);
                    303: 	    $result.=&Apache::edit::handle_insert();
1.22      albertel  304: 	}
1.89      albertel  305:     } elsif ($target eq 'meta') {
                    306: 	$result=&Apache::response::meta_package_write('numericalresponse');
                    307:     } elsif ($target eq 'answer' || $target eq 'grade') {
                    308: 	&Apache::response::reset_params();
1.96      albertel  309:     } elsif ($target eq 'web') {
                    310: 	my $partid = $Apache::inputtags::part;
                    311: 	my $hideunit=&Apache::lonnet::EXT('resource.'.$partid.'_'.$id.'.turnoffunit');
                    312: 	&Apache::lonxml::debug("Got unit $hideunit for $partid $id");
                    313: 	#no way to enter units, with radio buttons
1.238     www       314: 	if ((lc($hideunit) eq "yes") && ($Apache::lonhomework::type ne 'exam')) {
1.96      albertel  315: 	    my $unit=&Apache::lonxml::get_param_var('unit',$parstack,
                    316: 						    $safeeval);
                    317: 	    if ($unit =~ /\S/) { $result.=" (in $unit) "; }
                    318: 	}
1.146     albertel  319: 	if (  &Apache::response::show_answer() ) {
1.195     albertel  320: 	    &set_answertext($tag_internal_answer_name,$target,$token,$tagstack,
                    321: 			    $parstack,$parser,$safeeval,-1);
1.194     albertel  322: 	}
                    323:     }
                    324:     return $result;
                    325: }
                    326: 
                    327: sub set_answertext {
                    328:     my ($name,$target,$token,$tagstack,$parstack,$parser,$safeeval,
                    329: 	$response_level) = @_;
1.264     raeburn   330:     my $stringify;
                    331:     if (scalar(@$tagstack)) {
                    332:         if ($$tagstack[-1] eq 'formularesponse') {
                    333:             if (&Apache::lonxml::get_param('samples',$parstack,$safeeval)) {
                    334:                 $stringify = 1;
                    335:             }
                    336:         } elsif ($$tagstack[-1] eq 'numericalresponse') {
                    337:             $stringify = 1;
                    338:         }
                    339:     }
                    340:     &add_in_tag_answer($parstack,$safeeval,$stringify,$response_level);
1.194     albertel  341: 
1.206     albertel  342:     if ($name eq '' || !ref($answer{$name})) {
                    343: 	if (ref($answer{$tag_internal_answer_name})) {
                    344: 	    $name = $tag_internal_answer_name;
                    345: 	} else {
                    346: 	    $name = (sort(keys(%answer)))[0];
                    347: 	}
                    348:     }
1.194     albertel  349:     return if ($name eq '' || !ref($answer{$name}));
                    350: 
                    351:     my (@formats)=&Apache::lonxml::get_param_var('format',$parstack,
                    352: 						 $safeeval,$response_level);
                    353:     my $unit=&Apache::lonxml::get_param_var('unit',$parstack,$safeeval,
                    354: 					    $response_level);
                    355: 
                    356:     &Apache::lonxml::debug("answer looks to be $name");
1.195     albertel  357:     my @answertxt;
1.194     albertel  358:     for (my $i=0; $i < scalar(@{$answer{$name}{'answers'}}); $i++) {
1.195     albertel  359: 	my $answertxt;
1.194     albertel  360: 	my $answer=$answer{$name}{'answers'}[$i];
1.195     albertel  361: 	foreach my $element (@$answer) {
                    362: 	    if ( scalar(@$tagstack)
                    363: 		 && $tagstack->[$response_level] ne 'numericalresponse') {
                    364: 		$answertxt.=$element.',';
1.194     albertel  365: 	    } else {
1.195     albertel  366: 		my $format;
                    367: 		if ($#formats > 0) {
                    368: 		    $format=$formats[$i];
                    369: 		} else {
                    370: 		    $format=$formats[0];
                    371: 		}
                    372: 		if ($unit=~/\$/) { $format="\$".$format; $unit=~s/\$//g; }
                    373: 		if ($unit=~/\,/) { $format="\,".$format; $unit=~s/\,//g; }
                    374: 		my $formatted=&format_number($element,$format,$target,
                    375: 					     $safeeval);
                    376: 		$answertxt.=' '.$formatted.',';
1.146     albertel  377: 	    }
1.195     albertel  378: 	    
                    379: 	}
                    380: 	chop($answertxt);
                    381: 	if ($target eq 'web') {
                    382: 	    $answertxt.=" $unit ";
1.146     albertel  383: 	}
1.195     albertel  384: 
                    385: 	push(@answertxt,$answertxt)
1.16      albertel  386:     }
1.194     albertel  387: 	
                    388:     my $id = $Apache::inputtags::response[-1];
1.195     albertel  389:     $Apache::inputtags::answertxt{$id}=\@answertxt;
1.21      albertel  390: }
                    391: 
1.195     albertel  392: sub setup_capa_args {
                    393:     my ($safeeval,$parstack,$args,$response) = @_;
1.167     albertel  394:     my $args_ref= \%{$safeeval->varglob('LONCAPA::CAPAresponse_args')};
1.195     albertel  395:     undef(%{ $args_ref });
                    396:  
                    397:     foreach my $arg (@{$args}) {
1.167     albertel  398: 	$$args_ref{$arg}=
                    399: 	    &Apache::lonxml::get_param($arg,$parstack,$safeeval);
                    400:     }
                    401:     foreach my $key (keys(%Apache::inputtags::params)) {
                    402: 	$$args_ref{$key}=$Apache::inputtags::params{$key};
                    403:     }
1.195     albertel  404:     &setup_capa_response($args_ref,$response);
                    405:     return $args_ref;
                    406: }
                    407: 
                    408: sub setup_capa_response {
                    409:     my ($args_ref,$response) = @_;   
                    410: 
                    411:     if (ref($response)) {
                    412: 	$$args_ref{'response'}=dclone($response);
                    413:     } else {
1.263     raeburn   414: 	$$args_ref{'response'}=dclone(["$response"]);
1.195     albertel  415:     }
                    416: }
                    417: 
                    418: sub check_submission {
                    419:     my ($response,$partid,$id,$tag,$parstack,$safeeval,$ignore_sig)=@_;
1.247     www       420:     my @args = ('type','tol','sig','format','unit','calc','samples','preprocess');
1.195     albertel  421:     my $args_ref = &setup_capa_args($safeeval,$parstack,\@args,$response);
1.264     raeburn   422:     my $stringify;
1.195     albertel  423: 
                    424:     my $hideunit=
                    425: 	&Apache::lonnet::EXT('resource.'.$partid.'_'.$id.'.turnoffunit');
                    426:         #no way to enter units, with radio buttons
1.167     albertel  427:     if ($Apache::lonhomework::type eq 'exam' ||
                    428: 	lc($hideunit) eq "yes") {
                    429: 	delete($$args_ref{'unit'});
                    430:     }
                    431:     #sig fig don't make much sense either
                    432:     if (($Apache::lonhomework::type eq 'exam' ||
1.171     albertel  433: 	 &Apache::response::submitted('scantron') ||
                    434: 	 $ignore_sig) &&
1.167     albertel  435: 	$tag eq 'numericalresponse') {
                    436: 	delete($$args_ref{'sig'});
                    437:     }
                    438:     
                    439:     if ($tag eq 'formularesponse') {
1.199     www       440: 	if ($$args_ref{'samples'}) {
1.191     www       441: 	    $$args_ref{'type'}='fml';
1.264     raeburn   442:             $stringify = 1;
1.199     www       443: 	} else {
                    444: 	    $$args_ref{'type'}='math';
                    445: 	}
1.167     albertel  446:     } elsif ($tag eq 'numericalresponse') {
                    447: 	$$args_ref{'type'}='float';
1.264     raeburn   448:         $stringify = 1;
1.233     raeburn   449:     } elsif ($tag eq 'stringresponse') {
                    450:         if ($$args_ref{'type'} eq '') {
                    451:             $$args_ref{'type'} = 'ci';
                    452:         }
1.167     albertel  453:     }
1.233     raeburn   454: 
1.264     raeburn   455:     &add_in_tag_answer($parstack,$safeeval,$stringify);
1.194     albertel  456: 
1.218     albertel  457:     if (!%answer) {
                    458: 	&Apache::lonxml::error("No answers are defined");
                    459:     }
                    460: 
1.195     albertel  461:     my (@final_awards,@final_msgs,@names);
1.181     albertel  462:     foreach my $name (keys(%answer)) {
                    463: 	&Apache::lonxml::debug(" doing $name with ".join(':',@{ $answer{$name}{'answers'} }));
1.194     albertel  464: 	
                    465: 	${$safeeval->varglob('LONCAPA::CAPAresponse_answer')}=dclone($answer{$name});
1.195     albertel  466: 	&setup_capa_response($args_ref,$response);
                    467: 	use Time::HiRes;
                    468: 	my $t0 = [Time::HiRes::gettimeofday()];
1.181     albertel  469: 	my ($result,@msgs) = 
1.233     raeburn   470: 	    &Apache::run::run("&caparesponse_check_list()",$safeeval);
1.195     albertel  471: 	&Apache::lonxml::debug("checking $name $result with $response took ".&Time::HiRes::tv_interval($t0));
1.181     albertel  472: 	&Apache::lonxml::debug('msgs are '.join(':',@msgs));
                    473: 	my ($awards)=split(/:/,$result);
                    474: 	my @awards= split(/,/,$awards);
                    475: 	my ($ad, $msg) = &Apache::inputtags::finalizeawards(\@awards,\@msgs);
                    476: 	push(@final_awards,$ad);
                    477: 	push(@final_msgs,$msg);
                    478: 	push(@names,$name);
                    479:     }
                    480:     my ($ad, $msg, $name) = &Apache::inputtags::finalizeawards(\@final_awards,
                    481: 							       \@final_msgs,
                    482: 							       \@names,1);
1.194     albertel  483:     &Apache::lonxml::debug(" name of picked award is $name from ".join(', ',@names));
                    484:     return($ad,$msg, $name);
                    485: }
                    486: 
1.241     raeburn   487: sub stringresponse_gradechange {
                    488:     my ($part,$id,$previous,$caller,$response,$ad,$type) = @_;
                    489:     return unless (ref($previous) eq 'HASH');
                    490:     my ($prevarray,$prevaward);
                    491:     my %typenames = (
                    492:                      cs => 'Case sensitive',
                    493:                      ci => 'Case insensitive',
                    494:                     );
                    495:     if ($caller eq 'cs') {
                    496:         return unless (ref($previous->{'version'}) eq 'ARRAY');
                    497:         $prevarray = $previous->{'version'};
                    498:         $prevaward = $previous->{'award'};
                    499:     } elsif ($caller eq 'ci') {
                    500:         return unless (ref($previous->{'versionci'}) eq 'ARRAY');
                    501:         $prevarray = $previous->{'versionci'};
                    502:         $prevaward = $previous->{'awardci'};
                    503:     } else {
                    504:         return;
                    505:     }
                    506:     my $count=0;
                    507:     my %count_lookup;
                    508:     foreach my $i (1..$Apache::lonhomework::history{'version'}) {
                    509:         my $prefix = $i.":resource.$part";
                    510:         next if (!exists($Apache::lonhomework::history{"$prefix.award"}));
                    511:         $count++;
                    512:         $count_lookup{$i} = $count;
                    513:     }
                    514:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
                    515:     my %coursedesc = &Apache::lonnet::coursedescription($courseid);
                    516:     my $cdom = $coursedesc{'domain'};
                    517:     my $versions = ' (submissions: '.join(', ',map {$count_lookup{$_} } @{$prevarray}).')';
                    518:     my $warning = "String Response ($typenames{$type}) grading discrepancy: award for response of $response changed from $prevaward".$versions." to $ad; user: $name:$domain in course: $courseid for part: $part response: $id for symb: $symb";
                    519:     &Apache::lonnet::logthis($warning);
                    520:     my $origmail = $Apache::lonnet::perlvar{'lonAdmEMail'};
                    521:     my $recipients = &Apache::loncommon::build_recipient_list(undef,'errormail',
                    522:                                                               $cdom,$origmail);
                    523:     if ($recipients ne '') {
                    524:         &Apache::lonmsg::sendemail($recipients,'Stringresponse Grading Discrepancy',$warning);
                    525:     }
                    526:     return;
                    527: }
                    528: 
1.194     albertel  529: sub add_in_tag_answer {
1.264     raeburn   530:     my ($parstack,$safeeval,$stringify,$response_level) = @_;
1.194     albertel  531:     my @answer=&Apache::lonxml::get_param_var('answer',$parstack,$safeeval,
                    532: 					      $response_level);
                    533:     &Apache::lonxml::debug('answer is'.join(':',@answer));
1.213     albertel  534:     if (@answer && $answer[0] =~ /\S/) {
1.264     raeburn   535:         if ($stringify) {
                    536:             @answer = map { $_ .= ''; } @answer;
                    537:         }
1.195     albertel  538: 	$answer{$tag_internal_answer_name}= {'type' => 'ordered',
                    539: 					     'answers' => [\@answer] };
1.194     albertel  540:     }
1.167     albertel  541: }
                    542: 
1.202     www       543: sub capa_formula_fix {
                    544:    my ($expression)=@_;
                    545:    return &Apache::response::implicit_multiplication($expression);
                    546: }
                    547: 
1.89      albertel  548: sub end_numericalresponse {
                    549:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.208     albertel  550: 
                    551:     &Apache::lonxml::deregister('Apache::caparesponse',
                    552: 			      ('answer','answergroup','value','array','unit',
                    553: 			       'vector'));
                    554:     pop(@Apache::lonxml::namespace);
                    555: 
1.90      albertel  556:     my $increment=1;
1.89      albertel  557:     my $result = '';
                    558:     if (!$Apache::lonxml::default_homework_loaded) {
                    559: 	&Apache::lonxml::default_homework_load($safeeval);
1.34      albertel  560:     }
1.167     albertel  561:     my $partid = $Apache::inputtags::part;
                    562:     my $id = $Apache::inputtags::response[-1];
1.264     raeburn   563:     my ($tag,$stringify);
1.190     albertel  564:     my $safehole = new Safe::Hole;
1.168     albertel  565:     $safeeval->share_from('capa',['&caparesponse_capa_check_answer']);
1.190     albertel  566: 
1.125     albertel  567:     if (scalar(@$tagstack)) { $tag=$$tagstack[-1]; }
1.162     albertel  568:     if ( $target eq 'grade' && &Apache::response::submitted() ) {
1.140     albertel  569: 	&Apache::response::setup_params($tag,$safeeval);
1.95      albertel  570: 	if ($Apache::lonhomework::type eq 'exam' && 
1.190     albertel  571: 	    (($tag eq 'formularesponse') || ($tag eq 'mathresponse'))) {
1.95      albertel  572: 	    $increment=&Apache::response::scored_response($partid,$id);
                    573: 	} else {
                    574: 	    my $response = &Apache::response::getresponse();
                    575: 	    if ( $response =~ /[^\s]/) {
                    576: 		my %previous = &Apache::response::check_for_previous($response,$partid,$id);
                    577: 		&Apache::lonxml::debug("submitted a $response<br>\n");
                    578: 		&Apache::lonxml::debug($$parstack[-1] . "\n<br>");
                    579: 		
1.162     albertel  580: 		if ( &Apache::response::submitted('scantron')) {
1.264     raeburn   581:                     if ($tag eq 'numericalresponse') {
                    582:                         $stringify = 1;
                    583:                     } elsif ($tag eq 'formularesponse') {
                    584:                         if (&Apache::lonxml::get_param('samples',$parstack,$safeeval)) {
                    585:                             $stringify = 1;
                    586:                         }
                    587:                     }
                    588: 	            &add_in_tag_answer($parstack,$safeeval,$stringify);
                    589: 	            my ($values,$display)=&make_numerical_bubbles($partid,$id,$target,
                    590: 					                          $parstack,$safeeval);
                    591: 	            $response=$values->[$response];
                    592: 	        }
                    593: 	        $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
1.194     albertel  594: 		my ($ad,$msg,$name)=&check_submission($response,$partid,$id,
                    595: 						      $tag,$parstack,
                    596: 						      $safeeval);
1.167     albertel  597: 
1.142     albertel  598: 		&Apache::lonxml::debug('ad is'.$ad);
                    599: 		if ($ad eq 'SIG_FAIL') {
                    600: 		    my ($sig_u,$sig_l)=
                    601: 			&get_sigrange($Apache::inputtags::params{'sig'});
                    602: 		    $msg=join(':',$msg,$sig_l,$sig_u);
                    603: 		    &Apache::lonxml::debug("sigs bad $sig_u $sig_l ".
                    604: 					   $Apache::inputtags::params{'sig'});
                    605: 		}
1.95      albertel  606: 		&Apache::lonxml::debug("\n<br>result:$result:$Apache::lonxml::curdepth<br>\n");
1.237     raeburn   607:                 if (($ad eq 'INCORRECT' || $ad eq 'APPROX_ANS' ||
                    608:                      $ad eq 'EXACT_ANS')) {
                    609: 		    if ($Apache::lonhomework::type eq 'survey') {
                    610: 		        $ad='SUBMITTED';
                    611: 		    } elsif ($Apache::lonhomework::type eq 'surveycred') {
                    612:                         $ad='SUBMITTED_CREDIT';
                    613:                     } elsif ($Apache::lonhomework::type eq 'anonsurvey') {
                    614:                         $ad='ANONYMOUS';
                    615:                     } elsif ($Apache::lonhomework::type eq 'anonsurveycred') {
                    616:                         $ad='ANONYMOUS_CREDIT';                     
                    617:                     }
                    618:                 }
1.95      albertel  619: 		&Apache::response::handle_previous(\%previous,$ad);
                    620: 		$Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
1.142     albertel  621: 		$Apache::lonhomework::results{"resource.$partid.$id.awardmsg"}=$msg;
1.194     albertel  622: 		$Apache::lonhomework::results{"resource.$partid.$id.answername"}=$name;
1.95      albertel  623: 		$result='';
1.90      albertel  624: 	    }
1.89      albertel  625: 	}
                    626:     } elsif ($target eq 'web' || $target eq 'tex') {
1.264     raeburn   627:         if ($tag eq 'numericalresponse') {
                    628:             $stringify = 1;
                    629:         } elsif ($tag eq 'formularesponse') {
                    630:             if (&Apache::lonxml::get_param('samples',$parstack,$safeeval)) {
                    631:                 $stringify = 1;
                    632:             }
                    633:         }
                    634: 	&check_for_answer_errors($parstack,$safeeval,$stringify);
1.89      albertel  635: 	my $award = $Apache::lonhomework::history{"resource.$Apache::inputtags::part.solved"};
                    636: 	my $status = $Apache::inputtags::status['-1'];
                    637: 	if ($Apache::lonhomework::type eq 'exam') {
1.194     albertel  638: 	    # FIXME support multi dimensional numerical problems
                    639:             #       in exam bubbles
1.184     albertel  640: 	    my ($bubble_values,$bubble_display)=
                    641: 		&make_numerical_bubbles($partid,$id,$target,$parstack,
                    642: 					$safeeval);
                    643: 	    my $number_of_bubbles = scalar(@{ $bubble_values });
1.89      albertel  644: 	    my $unit=&Apache::lonxml::get_param_var('unit',$parstack,
                    645: 						    $safeeval);
                    646: 	    if ($target eq 'web') {
1.125     albertel  647: 		if ($tag eq 'numericalresponse') {
1.89      albertel  648: 		    if ($unit=~/\S/) {$result.=' (in '.$unit.')<br /><br />';}
                    649: 		    $result.= '<table border="1"><tr>';
1.116     albertel  650: 		    my $previous=$Apache::lonhomework::history{"resource.$Apache::inputtags::part.$id.submission"};
1.90      albertel  651: 		    for (my $ind=0;$ind<$number_of_bubbles;$ind++) {
1.116     albertel  652: 			my $checked='';
1.158     albertel  653: 			if ($previous eq $bubble_values->[$ind]) {
1.116     albertel  654: 			    $checked=" checked='on' ";
                    655: 			}
1.90      albertel  656: 			$result.='<td><input type="radio" name="HWVAL_'.$id.
1.158     albertel  657: 			    '" value="'.$bubble_values->[$ind].'" '.$checked
1.116     albertel  658: 			    .' /><b>'.$alphabet[$ind].'</b>: '.
1.158     albertel  659: 			    $bubble_display->[$ind].'</td>';
1.89      albertel  660: 		    }
                    661: 		    $result.='</tr></table>';
                    662: 		}
                    663: 	    } elsif ($target eq 'tex') {
1.107     sakharuk  664: 		if ((defined $unit) and ($unit=~/\S/) and ($Apache::lonhomework::type eq 'exam')) {
1.89      albertel  665: 		    $result.=' \textit{(in} \verb|'.$unit.'|\textit{)} ';
                    666: 		}
1.125     albertel  667: 		if ($tag eq 'numericalresponse') {
1.251     foxr      668: 		    $result .= &make_horizontal_latex_bubbles($bubble_values, $bubble_display,
                    669: 			'$\bigcirc$');
1.89      albertel  670: 		} else {
1.188     albertel  671: 		    $increment = &Apache::response::repetition();
1.89      albertel  672: 		}
                    673: 	    }
                    674: 	}
1.256     raeburn   675: 
1.212     albertel  676: 	&Apache::response::setup_prior_tries_hash(\&format_prior_response_numerical);
1.89      albertel  677:     } elsif ($target eq 'edit') {
                    678: 	$result.='</td></tr>'.&Apache::edit::end_table;
                    679:     } elsif ($target eq 'answer' || $target eq 'analyze') {
1.167     albertel  680: 	my $part_id="$partid.$id";
1.264     raeburn   681:         my $samples;
1.89      albertel  682: 	if ($target eq 'analyze') {
                    683: 	    push (@{ $Apache::lonhomework::analyze{"parts"} },$part_id);
1.125     albertel  684: 	    $Apache::lonhomework::analyze{"$part_id.type"} = $tag;
1.117     albertel  685: 	    my (@incorrect)=&Apache::lonxml::get_param_var('incorrect',$parstack,$safeeval);
1.161     albertel  686: 	    if ($#incorrect eq 0) { @incorrect=(split(/,/,$incorrect[0])); }
1.117     albertel  687: 	    push (@{ $Apache::lonhomework::analyze{"$part_id.incorrect"} }, @incorrect);
1.154     albertel  688: 	    &Apache::response::check_if_computed($token,$parstack,
                    689: 						 $safeeval,'answer');
1.89      albertel  690: 	}
1.125     albertel  691: 	if (scalar(@$tagstack)) {
1.140     albertel  692: 	    &Apache::response::setup_params($tag,$safeeval);
1.125     albertel  693: 	}
1.264     raeburn   694:         if ($tag eq 'numericalresponse') {
                    695:             $stringify = 1;
                    696:         } elsif ($tag eq 'formularesponse') {
                    697:             $samples=&Apache::lonxml::get_param('samples',$parstack,$safeeval);
                    698:             if ($samples) {
                    699:                 $stringify = 1;
                    700:             }
                    701:         }
                    702: 	&add_in_tag_answer($parstack,$safeeval,$stringify);
1.58      sakharuk  703: 	my (@formats)=&Apache::lonxml::get_param_var('format',$parstack,$safeeval);
1.194     albertel  704: 
1.58      sakharuk  705: 	my $unit=&Apache::lonxml::get_param_var('unit',$parstack,$safeeval);
1.259     raeburn   706: 	my ($needsdollar,$needscomma);
                    707: 	if ($unit =~ /\$/) {
                    708: 	    $needsdollar = 1;
                    709: 	}
                    710: 	if ($unit =~ /\,/) {
                    711: 	    $needscomma = 1;
                    712: 	}
                    713: 
1.89      albertel  714: 	if ($target eq 'answer') {
1.195     albertel  715: 	    $result.=&Apache::response::answer_header($tag,undef,
                    716: 						      scalar(keys(%answer)));
1.185     albertel  717: 	    if ($tag eq 'numericalresponse'
                    718: 		&& $Apache::lonhomework::type eq 'exam') {
1.184     albertel  719: 		my ($bubble_values,undef,$correct) = &make_numerical_bubbles($partid,
                    720: 					     $id,$target,$parstack,$safeeval);
                    721: 		$result.=&Apache::response::answer_part($tag,$correct);
                    722: 	    }
1.89      albertel  723: 	}
1.194     albertel  724: 	foreach my $name (sort(keys(%answer))) {
                    725: 	    my @answers = @{ $answer{$name}{'answers'} };
1.200     albertel  726: 	    if ($target eq 'analyze') {
                    727: 		foreach my $info ('answer','ans_high','ans_low','format') {
                    728: 		    $Apache::lonhomework::analyze{"$part_id.$info"}{$name}=[];
                    729: 		}
                    730: 	    }
1.194     albertel  731: 	    my ($sigline,$tolline);
1.195     albertel  732: 	    if ($name ne $tag_internal_answer_name 
                    733: 		|| scalar(keys(%answer)) > 1) {
                    734: 		$result.=&Apache::response::answer_part($tag,$name);
                    735: 	    }
1.194     albertel  736: 	    for(my $i=0;$i<=$#answers;$i++) {
                    737: 		my $ans=$answers[$i];
                    738: 		my $fmt=$formats[0];
                    739: 		if (@formats && $#formats) {$fmt=$formats[$i];}
                    740: 		my ($sighigh,$siglow);
                    741: 		if ($Apache::inputtags::params{'sig'}) {
                    742: 		    ($sighigh,$siglow)=&get_sigrange($Apache::inputtags::params{'sig'});
                    743: 		}
1.195     albertel  744: 		my @vector;
                    745: 		if (ref($ans)) {
                    746: 		    @vector = @{ $ans };
                    747: 		} else {
                    748: 		    @vector = ($ans);
1.194     albertel  749: 		}
1.200     albertel  750: 		my @all_answer_info;
                    751: 		foreach my $element (@vector) {
                    752: 		    my ($high,$low);
                    753: 		    if ($Apache::inputtags::params{'tol'}) {
                    754: 			($high,$low)=&get_tolrange($element,$Apache::inputtags::params{'tol'});
                    755: 		    }
                    756: 		    if ($target eq 'answer') {
1.195     albertel  757: 			if ($fmt && $tag eq 'numericalresponse') {
                    758: 			    $fmt=~s/e/E/g;
                    759: 			    if ($unit=~/\$/) { $fmt="\$".$fmt; $unit=~s/\$//g; }
                    760: 			    if ($unit=~/\,/) { $fmt="\,".$fmt; $unit=~s/\,//g; }
                    761: 			    $element = &format_number($element,$fmt,$target,$safeeval);
                    762: 			    #if ($high) {
                    763: 			    #    $high=&format_number($high,$fmt,$target,$safeeval);
                    764: 			    #    $low =&format_number($low,$fmt,$target,$safeeval);
                    765: 			    #}
                    766: 			}
                    767: 			if ($high && $tag eq 'numericalresponse') {
1.224     www       768: 			    $element.='; ['.$low.'; '.$high.']';
1.195     albertel  769: 			    $tolline .= "[$low, $high]";
                    770: 			}
                    771: 			if (defined($sighigh) && $tag eq 'numericalresponse') {
                    772: 			    if ($env{'form.answer_output_mode'} eq 'tex') {
1.224     www       773: 				$element.= "; Sig $siglow - $sighigh";
1.195     albertel  774: 			    } else {
                    775: 				$element.= " Sig <i>$siglow - $sighigh</i>";
                    776: 				$sigline .= "[$siglow, $sighigh]";
                    777: 			    }
1.194     albertel  778: 			}
1.195     albertel  779: 			push(@all_answer_info,$element);
1.200     albertel  780: 			
                    781: 		    } elsif ($target eq 'analyze') {
                    782: 			push (@{ $Apache::lonhomework::analyze{"$part_id.answer"}{$name}[$i] }, $element);
                    783: 			if ($high) {
                    784: 			    push (@{ $Apache::lonhomework::analyze{"$part_id.ans_high"}{$name}[$i] }, $high);
                    785: 			    push (@{ $Apache::lonhomework::analyze{"$part_id.ans_low"}{$name}[$i] }, $low);
                    786: 			}
                    787: 			if ($fmt) {
                    788: 			    push (@{ $Apache::lonhomework::analyze{"$part_id.format"}{$name}[$i] }, $fmt);
                    789: 			}
1.194     albertel  790: 		    }
1.200     albertel  791: 		}
                    792: 		if ($target eq 'answer') {
1.223     www       793: 		    $result.= &Apache::response::answer_part($tag,join('; ',@all_answer_info));
1.194     albertel  794: 		}
                    795: 	    }
                    796: 
                    797: 	    my @fmt_ans;
                    798: 	    for(my $i=0;$i<=$#answers;$i++) {
                    799: 		my $ans=$answers[$i];
                    800: 		my $fmt=$formats[0];
                    801: 		if (@formats && $#formats) {$fmt=$formats[$i];}
1.260     raeburn   802: 		my @answers;
                    803: 		if (ref($ans) eq 'ARRAY') {
                    804: 		    @answers = (@{$ans});
                    805: 		}
                    806: 		foreach my $element (@answers) {		    
1.195     albertel  807: 		    if ($fmt && $tag eq 'numericalresponse') {
                    808: 			$fmt=~s/e/E/g;
                    809: 			if ($unit=~/\$/) { $fmt="\$".$fmt; $unit=~s/\$//g; }
                    810: 			if ($unit=~/\,/) { $fmt="\,".$fmt; $unit=~s/\,//g; }
                    811: 			$element = &format_number($element,$fmt,$target,
                    812: 						  $safeeval);
1.259     raeburn   813: 			if ($fmt=~/\$/ && !$needsdollar) { $element=~s/\$//; }
1.195     albertel  814: 		    }
1.194     albertel  815: 		}
1.260     raeburn   816: 		push(@fmt_ans,join(',',@answers));
1.194     albertel  817: 	    }
1.195     albertel  818: 	    my $response=\@fmt_ans;
                    819: 
1.194     albertel  820: 	    my $hideunit=&Apache::lonnet::EXT('resource.'.$partid.'_'.
                    821: 					      $id.'.turnoffunit');
                    822: 	    if ($unit ne ''  && 
                    823: 		! ($Apache::lonhomework::type eq 'exam' ||
                    824: 		   lc($hideunit) eq "yes") )  {
                    825: 		my $cleanunit=$unit;
1.259     raeburn   826: 		$cleanunit=~s/[\$,]//g;
1.195     albertel  827: 		foreach my $ans (@fmt_ans) {
                    828: 		    $ans.=" $cleanunit";
                    829: 		}
1.60      sakharuk  830: 	    }
1.194     albertel  831: 	    my ($ad,$msg)=&check_submission($response,$partid,$id,$tag,
                    832: 					    $parstack,$safeeval);
                    833: 	    if ($ad ne 'EXACT_ANS' && $ad ne 'APPROX_ANS') {
                    834: 		my $error;
                    835: 		if ($tag eq 'formularesponse') {
1.236     bisitz    836: 		    $error=&mt("Computer's answer is incorrect ([_1]).",'"'.join(', ',@$response).'"');
1.194     albertel  837: 		} else {
                    838: 		    # answer failed check if it is sig figs that is failing
                    839: 		    my ($ad,$msg)=&check_submission($response,$partid,$id,
                    840: 						    $tag,$parstack,
                    841: 						    $safeeval,1);
1.236     bisitz    842: 		    $error=&mt("Computer's answer is incorrect ([_1]).",'"'.join(', ',@$response).'"').' ';
1.259     raeburn   843:                     if (($ad eq 'NO_UNIT') && $needsdollar) {
                    844:                         $error.=&mt('The unit attribute includes [_1] but the answer format does not.','$').' '.
                    845:                                 &mt('Either remove the [_1] from the unit or prepend [_1] to the answer format.','$');    
                    846:                     } elsif (($ad eq 'COMMA_FAIL') && $needscomma) {
                    847:                         $error.=&mt('The unit attribute includes [_1] but the answer format does not.',',').' '.
                    848:                                 &mt('Either remove the [_1] from the unit or prepend [_1] to the answer format.',',');
                    849:                     } elsif ($ad eq 'UNIT_INVALID_STUDENT') {
1.257     raeburn   850:                         $error.=&mt('Unable to interpret units. Computer reads units as "[_1]".',$msg).' '.
                    851:                                 &mt('The unit attribute in the numericalresponse item needs to be a supported physical unit.');
                    852: 		    } elsif ($sigline ne '') {
1.236     bisitz    853: 			$error.=&mt('It is likely that the tolerance range [_1] or significant figures [_2] need to be adjusted.',$tolline,$sigline);
1.98      sakharuk  854: 		    } else {
1.236     bisitz    855: 			$error.=&mt('It is likely that the tolerance range [_1] needs to be adjusted.',$tolline);
1.98      sakharuk  856: 		    }
                    857: 		}
1.194     albertel  858: 		if ($ad ne 'EXACT_ANS' && $ad ne 'APPROX_ANS') {
                    859: 		    &Apache::lonxml::error($error);
                    860: 		} else {
                    861: 		    &Apache::lonxml::warning($error);
1.165     albertel  862: 		}
1.79      sakharuk  863: 	    }
1.176     albertel  864: 
1.194     albertel  865: 	    if (defined($unit) and ($unit ne '') and
                    866: 		$tag eq 'numericalresponse') {
                    867: 		if ($target eq 'answer') {
                    868: 		    if ($env{'form.answer_output_mode'} eq 'tex') {
                    869: 			$result.=&Apache::response::answer_part($tag,
                    870: 								" Unit: $unit ");
                    871: 		    } else {
                    872: 			$result.=&Apache::response::answer_part($tag,
                    873: 								"Unit: <b>$unit</b>");
                    874: 		    }
                    875: 		} elsif ($target eq 'analyze') {
                    876: 		    push (@{ $Apache::lonhomework::analyze{"$part_id.unit"} }, $unit);
1.171     albertel  877: 		}
1.167     albertel  878: 	    }
1.194     albertel  879: 	    if ($tag eq 'formularesponse' && $target eq 'answer') {
                    880: 		$result.=&Apache::response::answer_part($tag,$samples);
1.89      albertel  881: 	    }
1.195     albertel  882: 	    $result.=&Apache::response::next_answer($tag,$name);
1.89      albertel  883: 	}
                    884: 	if ($target eq 'answer') {
1.125     albertel  885: 	    $result.=&Apache::response::answer_footer($tag);
1.89      albertel  886: 	}
1.69      sakharuk  887:     }
1.121     sakharuk  888:     if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' || 
1.90      albertel  889: 	$target eq 'tex' || $target eq 'analyze') {
1.221     raeburn   890:         if (($tag eq 'formularesponse') && ($target eq 'analyze')) {
                    891:             my $type = &Apache::lonnet::EXT('resource.'.$partid.'_'.$id.'.type');
                    892:             if ($type eq 'exam') {
                    893:                 $increment = &Apache::response::repetition();
                    894:             }
                    895:         }
1.220     albertel  896: 	&Apache::lonxml::increment_counter($increment,"$partid.$id");
                    897: 	if ($target eq 'analyze') {
                    898: 	    &Apache::lonhomework::set_bubble_lines();
                    899: 	}
1.90      albertel  900:     }
1.196     albertel  901:     &Apache::response::end_response();
1.89      albertel  902:     return $result;
1.90      albertel  903: }
                    904: 
1.212     albertel  905: sub format_prior_response_numerical {
                    906:     my ($mode,$answer) = @_;
1.213     albertel  907:     if (ref($answer)) {
                    908: 	my $result = '<table class="LC_prior_numerical"><tr>';
                    909: 	foreach my $element (@{ $answer }) {
                    910: 	    $result.= '<td><span class="LC_prior_numerical">'.
                    911: 		&HTML::Entities::encode($element,'"<>&').'</span></td>';
                    912: 	}
                    913: 	$result.='</tr></table>';
                    914: 	return $result;
                    915:     }
1.212     albertel  916:     return '<span class="LC_prior_numerical">'.
                    917: 	    &HTML::Entities::encode($answer,'"<>&').'</span>';
                    918: 
1.209     albertel  919: }
                    920: 
1.196     albertel  921: sub check_for_answer_errors {
1.264     raeburn   922:     my ($parstack,$safeeval,$stringify) = @_;
                    923:     &add_in_tag_answer($parstack,$safeeval,$stringify);
1.196     albertel  924:     my %counts;
                    925:     foreach my $name (keys(%answer)) {
                    926: 	push(@{$counts{scalar(@{$answer{$name}{'answers'}})}},$name);
                    927:     }
                    928:     if (scalar(keys(%counts)) > 1) {
                    929: 	my $counts = join(' ',map {
                    930: 	    my $count = $_;
                    931: 	    &mt("Answers [_1] had [_2] components.",
                    932: 		'<tt>'.join(', ',@{$counts{$count}}).'</tt>',
                    933: 		$count);
                    934: 	} (sort(keys(%counts))));
                    935: 	&Apache::lonxml::error(&mt("All answers must have the same number of components. Varying numbers of answers were seen. ").$counts);
                    936:     }
                    937:     my $expected_number_of_inputs = (keys(%counts))[0];
1.214     albertel  938:     if ( $expected_number_of_inputs > 0 
                    939: 	 && $expected_number_of_inputs != scalar(@Apache::inputtags::inputlist)) {
1.196     albertel  940: 	&Apache::lonxml::error(&mt("Expected [_1] input fields, but there were only [_2] seen.", 
                    941: 				   $expected_number_of_inputs,
                    942: 				   scalar(@Apache::inputtags::inputlist)));
                    943:     }
                    944: }
                    945: 
1.90      albertel  946: sub get_table_sizes {
1.128     sakharuk  947:     my ($number_of_bubbles,$rbubble_values)=@_;
                    948:     my $scale=2; #mm for one digit
                    949:     my $cell_width=0;
                    950:     foreach my $member (@$rbubble_values) {
                    951: 	my $cell_width_real=0;
1.258     raeburn   952: 	if ($member=~/(\+|-)?(\d*)\.?(\d*)\s*\$?\\times\s*10\^\{(\+|-)?(\d+)}\$?/) {
1.138     sakharuk  953: 	    $cell_width_real=(length($2)+length($3)+length($5)+7)*$scale;
                    954: 	} elsif ($member=~/(\d*)\.?(\d*)(E|e)(\+|-)?(\d*)/) {
1.128     sakharuk  955: 	    $cell_width_real=(length($1)+length($2)+length($5)+9)*$scale;
1.138     sakharuk  956:         } elsif ($member=~/(\d*)\.(\d*)/) {
1.132     sakharuk  957: 	    $cell_width_real=(length($1)+length($2)+3)*$scale;
1.128     sakharuk  958: 	} else {
1.138     sakharuk  959: 	    $cell_width_real=(length($member)+1)*$scale*0.9;
1.128     sakharuk  960: 	}
                    961: 	if ($cell_width_real>$cell_width) {$cell_width=$cell_width_real;}
1.90      albertel  962:     }
1.132     sakharuk  963:     $cell_width+=8; 
1.130     sakharuk  964:     my $textwidth;
1.166     albertel  965:     if ($env{'form.textwidth'} ne '') {
                    966: 	$env{'form.textwidth'}=~/(\d*)\.?(\d*)/;
1.132     sakharuk  967: 	$textwidth=$1.'.'.$2;
1.130     sakharuk  968:     } else {
1.166     albertel  969: 	$env{'form.textwidth'}=~/(\d+)\.?(\d*)/;
1.132     sakharuk  970: 	$textwidth=$1.'.'.$2;
1.130     sakharuk  971:     }
1.128     sakharuk  972:     my $bubbles_per_line=int($textwidth/$cell_width);
1.151     sakharuk  973:     if ($bubbles_per_line > $number_of_bubbles) {
                    974: 	$bubbles_per_line=$number_of_bubbles;
1.216     albertel  975:     } elsif (($bubbles_per_line > $number_of_bubbles/2) 
                    976: 	     && ($number_of_bubbles % 2==0)) {
                    977: 	$bubbles_per_line=$number_of_bubbles/2;
                    978:     }
                    979:     if ($bubbles_per_line < 1) {
                    980: 	$bubbles_per_line=1;
                    981:     }
1.128     sakharuk  982:     my $number_of_tables = int($number_of_bubbles/$bubbles_per_line);
1.90      albertel  983:     my @table_range = ();
1.128     sakharuk  984:     for (my $i=0;$i<$number_of_tables;$i++) {push @table_range,$bubbles_per_line;}
                    985:     if ($number_of_bubbles % $bubbles_per_line) {
1.90      albertel  986: 	$number_of_tables++;
1.128     sakharuk  987: 	push @table_range,($number_of_bubbles % $bubbles_per_line);
1.90      albertel  988:     }
1.128     sakharuk  989:     $cell_width-=8;
1.136     sakharuk  990:     $cell_width=$cell_width*3/4;
1.128     sakharuk  991:     return ($cell_width,$number_of_tables,@table_range);
1.90      albertel  992: }
                    993: 
                    994: sub format_number {
1.153     albertel  995:     my ($number,$format,$target,$safeeval)=@_;
1.90      albertel  996:     my $ans;
1.153     albertel  997:     if ($format eq '') {
1.90      albertel  998: 	#What is the number? (integer,decimal,floating point)
1.187     albertel  999: 	if ($number=~/^(\d*\.?\d*)(E|e)[+\-]?(\d*)$/) {
1.113     sakharuk 1000: 	    $format = '3e';
1.90      albertel 1001: 	} elsif ($number=~/^(\d*)\.(\d*)$/) {
                   1002: 	    $format = '4f';
                   1003: 	} elsif ($number=~/^(\d*)$/) {
                   1004: 	    $format = 'd';
                   1005: 	}
                   1006:     }
1.156     albertel 1007:     if (!$Apache::lonxml::default_homework_loaded) {
                   1008: 	&Apache::lonxml::default_homework_load($safeeval);
                   1009:     }
1.153     albertel 1010:     $ans=&Apache::run::run("&prettyprint(q\0$number\0,q\0$format\0,q\0$target\0)",$safeeval);
1.90      albertel 1011:     return $ans;
                   1012: }
                   1013: 
                   1014: sub make_numerical_bubbles {
1.184     albertel 1015:     my ($part,$id,$target,$parstack,$safeeval) =@_;
1.215     albertel 1016: 
                   1017:     if (!%answer) {
                   1018: 	&Apache::lonxml::error(&mt("No answers defined for response [_1] in part [_2] to make bubbles for.",$id,$part));
                   1019: 	return ([],[],undef);
                   1020:     }
1.184     albertel 1021:     
                   1022:     my $number_of_bubbles = 
                   1023: 	&Apache::response::get_response_param($part.'_'.$id,'numbubbles',8);
                   1024: 
1.252     foxr     1025:     #
                   1026:     # Fixes for BZ 6519 - number of bubbles <= 0 or non-integer.
                   1027:     # 
                   1028:     $number_of_bubbles = int($number_of_bubbles + 0.5);
                   1029:     if ($number_of_bubbles <= 0) {
                   1030: 	$number_of_bubbles = 8;
                   1031:     }
                   1032:     
                   1033: 
1.184     albertel 1034:     my ($format)=&Apache::lonxml::get_param_var('format',$parstack,$safeeval);
1.201     albertel 1035:     my $name = (exists($answer{$tag_internal_answer_name}) 
                   1036: 		? $tag_internal_answer_name
                   1037: 		: (sort(keys(%answer)))[0]);
                   1038: 
                   1039:     if ( scalar(@{$answer{$name}{'answers'}}) > 1) {
                   1040: 	&Apache::lonxml::error("Only answers with 1 component are supported in exam mode");
                   1041:     }
                   1042:     if (scalar(@{$answer{$name}{'answers'}[0]}) > 1) {
                   1043: 	&Apache::lonxml::error("Vector answers are unsupported in exam mode.");
                   1044:     }
                   1045: 
                   1046:     my $answer = $answer{$name}{'answers'}[0][0];
1.184     albertel 1047:     my (@incorrect)=&Apache::lonxml::get_param_var('incorrect',$parstack,
                   1048: 						   $safeeval);
                   1049:     if ($#incorrect eq 0) { @incorrect=(split(/,/,$incorrect[0])); }
                   1050:     
1.158     albertel 1051:     my @bubble_values=();
1.184     albertel 1052:     my @alphabet=('A'..'Z');
                   1053: 
                   1054:     &Apache::lonxml::debug("answer is $answer incorrect is @incorrect");
1.119     albertel 1055:     my @oldseed=&Math::Random::random_get_seed();
1.184     albertel 1056:     if (@incorrect) {
                   1057: 	&Apache::lonxml::debug("inside ".(scalar(@incorrect)+1 gt $number_of_bubbles));
                   1058: 	if (defined($incorrect[0]) &&
                   1059: 	    scalar(@incorrect)+1 >= $number_of_bubbles) {
                   1060: 	    &Apache::lonxml::debug("inside ".(scalar(@incorrect)+1).":$number_of_bubbles");
1.117     albertel 1061: 	    &Apache::response::setrandomnumber();
1.184     albertel 1062: 	    my @rand_inc=&Math::Random::random_permutation(@incorrect);
1.117     albertel 1063: 	    @bubble_values=@rand_inc[0..($number_of_bubbles-2)];
                   1064: 	    @bubble_values=sort {$a <=> $b} (@bubble_values,$answer);
1.184     albertel 1065: 	    &Apache::lonxml::debug("Answer was :$answer: returning :".$#bubble_values.": which are :".join(':',@bubble_values));
1.119     albertel 1066: 	    &Math::Random::random_set_seed(@oldseed);
1.184     albertel 1067: 
                   1068: 	    my $correct;
                   1069: 	    for(my $i=0; $i<=$#bubble_values;$i++) {
                   1070: 		if ($bubble_values[$i] eq $answer) {
                   1071: 		    $correct = $alphabet[$i];
                   1072: 		    last;
                   1073: 		}
                   1074: 	    }
                   1075: 
1.134     albertel 1076: 	    if (defined($format) && $format ne '') {
1.158     albertel 1077: 		my @bubble_display;
1.137     albertel 1078: 		foreach my $value (@bubble_values) {
1.158     albertel 1079: 		    push(@bubble_display,
                   1080: 			 &format_number($value,$format,$target,$safeeval));
1.134     albertel 1081: 		}
1.184     albertel 1082: 		return (\@bubble_values,\@bubble_display,$correct);
1.158     albertel 1083: 	    } else {
1.184     albertel 1084: 		return (\@bubble_values,\@bubble_values,$correct);
1.134     albertel 1085: 	    }
1.117     albertel 1086: 	}
1.184     albertel 1087: 	if (defined($incorrect[0]) &&
                   1088: 	    scalar(@incorrect)+1 < $number_of_bubbles) {
                   1089: 	    &Apache::lonxml::warning("Not enough incorrect answers were specified in the incorrect array, ignoring the specified incorrect answers and instead generating them (".join(',',@incorrect).").");
1.127     albertel 1090: 	}
1.117     albertel 1091:     }
1.90      albertel 1092:     my @factors = (1.13,1.17,1.25,1.33,1.45); #default values of factors
1.126     albertel 1093:     my @powers = (1..$number_of_bubbles);
1.90      albertel 1094:     &Apache::response::setrandomnumber();
                   1095:     my $ind=&Math::Random::random_uniform_integer(1,0,$#powers);
                   1096:     my $power = $powers[$ind];
                   1097:     $ind=&Math::Random::random_uniform_integer(1,0,$#factors);
                   1098:     my $factor = $factors[$ind];
1.158     albertel 1099:     my @bubble_display;
1.222     www      1100:     my $answerfactor=$answer;
                   1101:     if ($answer==0) { 
                   1102:        $answerfactor=&Math::Random::random_uniform_integer(1,1,100)/
                   1103:                      &Math::Random::random_uniform_integer(1,1,10);
                   1104:     }
1.90      albertel 1105:     for ($ind=0;$ind<$number_of_bubbles;$ind++) {
1.261     raeburn  1106: 	my $exponent = $power-$powers[$#powers-$ind];
1.262     raeburn  1107: 	$bubble_values[$ind] = $answerfactor*($factor**$exponent);
                   1108: 
                   1109: 	# If bubble is for correct answer (i.e., exponent = 0), and value
                   1110: 	# of $answerfactor * factor**$exponent is an integer with more than
                   1111: 	# 15 digits, assign $answerfactor itself as bubble value.
                   1112: 	# This prevents a "use fewer digits" issue on 64bit servers
                   1113: 	# when correct answer is >= 1e+16, and when correct bubble is A.
                   1114: 
1.261     raeburn  1115: 	if ($exponent == 0) {
1.262     raeburn  1116: 	    if ($bubble_values[$ind] =~ /^-?(\d+)$/) {
                   1117: 		if (length($1) > 15) {
                   1118: 		    $bubble_values[$ind] = $answerfactor;
                   1119: 		}
                   1120: 	    }
1.261     raeburn  1121: 	}
1.262     raeburn  1122: 
1.158     albertel 1123: 	$bubble_display[$ind] = &format_number($bubble_values[$ind],
1.153     albertel 1124: 					       $format,$target,$safeeval);
1.90      albertel 1125:     }
1.184     albertel 1126:     my $correct = $alphabet[$number_of_bubbles-$power];
1.222     www      1127:     if ($answer==0) {
                   1128:        $correct='A';
                   1129:        $bubble_values[0]=0;
                   1130:        $bubble_display[0] = &format_number($bubble_values[0],
                   1131:                                            $format,$target,$safeeval);
                   1132:     }
1.119     albertel 1133:     &Math::Random::random_set_seed(@oldseed);
1.184     albertel 1134:     return (\@bubble_values,\@bubble_display,$correct);
1.51      albertel 1135: }
                   1136: 
1.251     foxr     1137: ##
                   1138: # Produce LaTeX bubbles laid out horizontally given a set of bubble values:
                   1139: #
                   1140: # @param bubble_values  - reference to an array of bubble 'values'
                   1141: # @param bubble_display - reference to the array of texts to display to the user
                   1142: #                         for each bubble_value (this is mostly for numerical response
                   1143: #                         when the displayed value may not be an exact
                   1144: #                         representation of the bubble value. 
                   1145: # @param bubble_fragment- The LaTeX fragment that will be plugged in to make
                   1146: #                         the bubble itself. Note that the code will autonomously
                   1147: #                         label each bubble with a lable...and that it's perfectly
                   1148: #                         acceptable to use "" for the bubble_fragment.
                   1149: # 
                   1150: # @return string - the LaTeX fragment that produces the bubbles.
                   1151: #
                   1152: sub make_horizontal_latex_bubbles {
                   1153:     my ($bubble_values, $bubble_display, $bubble_fragment)     = @_;
                   1154:     my $result;
                   1155: 
                   1156:     my $number_of_bubbles = scalar(@{$bubble_values}); 
                   1157: 
                   1158:     # Get the number of rows and columns in each row of the bubble
                   1159:     # table:
                   1160: 
                   1161:     my ($celllength, $number_of_tables, @table_range) =
                   1162: 	&get_table_sizes($number_of_bubbles, $bubble_display);
                   1163: 
                   1164:     my $j=0;
                   1165:     my $cou=0;
                   1166:     $result.='\vskip 2mm \noindent ';
1.265   ! raeburn  1167:     if ($Apache::lonhomework::type eq 'exam') {
        !          1168:         $result .= '\textbf{'.$Apache::lonxml::counter.'.} \vskip -3mm ';
        !          1169:     }
1.251     foxr     1170: 
                   1171:     for (my $i=0;$i<$number_of_tables;$i++) {
                   1172: 	if ($i == 0) {
                   1173: 	    $result .= '\vskip -1mm ';
                   1174: 	} else {
                   1175: 	    $result .= '\vskip 1mm ';
                   1176: 	}
                   1177: 	$result.='\noindent \setlength{\tabcolsep}{2 mm}\hskip 2pc\begin{tabular}{';
                   1178: 	for (my $ind=0;$ind<$table_range[$j];$ind++) {
                   1179: 	    $result.='p{4 mm}p{'.$celllength.' mm}';
                   1180: 	}
                   1181: 	$result.='}';
                   1182: 	for (my $ind=$cou;$ind<$cou+$table_range[$j];$ind++) {
                   1183: 	    $result.='\hskip -4 mm {\small \textbf{ '.$alphabet[$ind].'}}'
                   1184: 		. $bubble_fragment 
                   1185: 		. '& \hskip -3 mm {\small '.$bubble_display->[$ind].'} ';
                   1186: 	    if ($ind != $cou+$table_range[$j]-1) {
                   1187: 		$result.=' & ';
                   1188: 	    }
                   1189: 	}
                   1190: 	$cou += $table_range[$j];
                   1191: 	$j++;
                   1192: 	$result.='\\\\\end{tabular}\vskip 0 mm ';
                   1193:     }
                   1194:     return $result;
                   1195: }
                   1196: 
1.51      albertel 1197: sub get_tolrange {
1.89      albertel 1198:     my ($ans,$tol)=@_;
                   1199:     my ($high,$low);
                   1200:     if ($tol =~ /%$/) {
                   1201: 	chop($tol);
                   1202: 	my $change=$ans*($tol/100.0);
                   1203: 	$high=$ans+$change;
                   1204: 	$low=$ans-$change;
                   1205:     } else {
                   1206: 	$high=$ans+$tol;
                   1207: 	$low=$ans-$tol;
                   1208:     }
                   1209:     return ($high,$low);
1.52      albertel 1210: }
                   1211: 
                   1212: sub get_sigrange {
1.89      albertel 1213:     my ($sig)=@_;
1.195     albertel 1214:     #&Apache::lonxml::debug("Got a sig of :$sig:");
1.166     albertel 1215:     my $courseid=$env{'request.course.id'};
1.219     albertel 1216:     if ($env{'request.state'} ne 'construct'
                   1217: 	&& lc($env{"course.$courseid.disablesigfigs"}) eq 'yes') {
1.147     albertel 1218: 	return (15,0);
                   1219:     }
1.89      albertel 1220:     my $sig_lbound;
                   1221:     my $sig_ubound;
                   1222:     if ($sig eq '') {
                   1223: 	$sig_lbound = 0; #SIG_LB_DEFAULT
                   1224: 	$sig_ubound =15; #SIG_UB_DEFAULT
                   1225:     } else {
                   1226: 	($sig_lbound,$sig_ubound) = split(/,/,$sig);
1.145     albertel 1227: 	if (!defined($sig_lbound)) {
1.89      albertel 1228: 	    $sig_lbound = 0; #SIG_LB_DEFAULT
                   1229: 	    $sig_ubound =15; #SIG_UB_DEFAULT
                   1230: 	}
1.145     albertel 1231: 	if (!defined($sig_ubound)) { $sig_ubound=$sig_lbound; }
1.133     albertel 1232:     }
                   1233:     if (($sig_ubound<$sig_lbound) ||
                   1234: 	($sig_lbound > 15) ||
                   1235: 	($sig =~/(\+|-)/ ) ) {
                   1236: 	my $errormsg=&mt("Invalid Significant figures detected")." ($sig)";
1.166     albertel 1237: 	if ($env{'request.state'} eq 'construct') {
1.133     albertel 1238: 	    $errormsg.=
                   1239: 		&Apache::loncommon::help_open_topic('Significant_Figures');
                   1240: 	}
                   1241: 	&Apache::lonxml::error($errormsg);
1.52      albertel 1242:     }
1.89      albertel 1243:     return ($sig_ubound,$sig_lbound);
1.34      albertel 1244: }
                   1245: 
1.212     albertel 1246: sub format_prior_response_string {
                   1247:     my ($mode,$answer) =@_;
                   1248:     return '<span class="LC_prior_string">'.
                   1249: 	    &HTML::Entities::encode($answer,'"<>&').'</span>';
1.211     albertel 1250: }
                   1251: 
1.34      albertel 1252: sub start_stringresponse {
1.89      albertel 1253:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1254:     my $result;
1.122     albertel 1255:     my $id = &Apache::response::start_response($parstack,$safeeval);
1.246     raeburn  1256:     undef(%answer);
1.89      albertel 1257:     if ($target eq 'meta') {
                   1258: 	$result=&Apache::response::meta_package_write('stringresponse');
1.122     albertel 1259:     } elsif ($target eq 'edit') {
                   1260: 	$result.=&Apache::edit::tag_start($target,$token);
                   1261: 	$result.=&Apache::edit::text_arg('Answer:','answer',$token);
                   1262: 	$result.=&Apache::edit::select_arg('Type:','type',
                   1263: 			 [['cs','Case Sensitive'],['ci','Case Insensitive'],
                   1264: 			  ['mc','Case Insensitive, Any Order'],
                   1265: 			  ['re','Regular Expression']],$token);
1.152     albertel 1266: 	$result.=&Apache::edit::text_arg('String to display for answer:',
                   1267: 					 'answerdisplay',$token);
1.248     www      1268:         $result.=&Apache::edit::text_arg('Pre-Processor Subroutine:','preprocess',
                   1269:                                              $token,10);
1.122     albertel 1270: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
                   1271:     } elsif ($target eq 'modified') {
1.146     albertel 1272: 	my $constructtag;
                   1273: 	$constructtag=&Apache::edit::get_new_args($token,$parstack,
                   1274: 						  $safeeval,'answer',
1.248     www      1275: 						  'type','answerdisplay','preprocess');
1.146     albertel 1276: 	if ($constructtag) {
                   1277: 	    $result = &Apache::edit::rebuild_tag($token);
                   1278: 	    $result.=&Apache::edit::handle_insert();
                   1279: 	}
                   1280:     } elsif ($target eq 'web') {
                   1281: 	if (  &Apache::response::show_answer() ) {
1.152     albertel 1282: 	    my $answer=
                   1283: 	       &Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval);
                   1284: 	    if (!defined $answer || $answer eq '') {
                   1285: 		$answer=
                   1286: 		    &Apache::lonxml::get_param('answer',$parstack,$safeeval);
                   1287: 	    }
1.195     albertel 1288: 	    $Apache::inputtags::answertxt{$id}=[$answer];
1.146     albertel 1289: 	} 
1.122     albertel 1290:     } elsif ($target eq 'answer' || $target eq 'grade') {
                   1291: 	&Apache::response::reset_params();
1.89      albertel 1292:     }
                   1293:     return $result;
1.34      albertel 1294: }
                   1295: 
                   1296: sub end_stringresponse {
1.122     albertel 1297:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.189     albertel 1298: 
1.122     albertel 1299:     my $result = '';
                   1300:     my $part=$Apache::inputtags::part;
                   1301:     my $id=$Apache::inputtags::response[-1];
                   1302:     my $answer=&Apache::lonxml::get_param('answer',$parstack,$safeeval);
                   1303:     my $type=&Apache::lonxml::get_param('type',$parstack,$safeeval);
1.129     www      1304:     my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval);
1.122     albertel 1305:     &Apache::lonxml::debug("current $answer ".$token->[2]);
                   1306:     if (!$Apache::lonxml::default_homework_loaded) {
                   1307: 	&Apache::lonxml::default_homework_load($safeeval);
                   1308:     }
1.264     raeburn  1309:     my $tag;
                   1310:     if (scalar(@$tagstack)) { $tag=$$tagstack[-1]; }
1.162     albertel 1311:     if ( $target eq 'grade' && &Apache::response::submitted() ) {
1.140     albertel 1312: 	&Apache::response::setup_params('stringresponse',$safeeval);
1.122     albertel 1313: 	$safeeval->share_from('capa',['&caparesponse_capa_check_answer']);
                   1314: 	if ($Apache::lonhomework::type eq 'exam' ||
1.162     albertel 1315: 	    &Apache::response::submitted('scantron')) {
1.189     albertel 1316: 	    &Apache::response::scored_response($part,$id);
                   1317: 
1.122     albertel 1318: 	} else {
                   1319: 	    my $response = &Apache::response::getresponse();
                   1320: 	    if ( $response =~ /[^\s]/) {
                   1321: 		my %previous = &Apache::response::check_for_previous($response,
1.241     raeburn  1322: 								    $part,$id,
                   1323:                                                                     undef,$type);
1.122     albertel 1324: 		&Apache::lonxml::debug("submitted a $response<br>\n");
                   1325: 		&Apache::lonxml::debug($$parstack[-1] . "\n<br>");
                   1326: 		$Apache::lonhomework::results{"resource.$part.$id.submission"}=
                   1327: 		    $response;
1.142     albertel 1328: 		my ($ad,$msg);
1.122     albertel 1329: 		if ($type eq 're' ) { 
                   1330: 		    # if the RE wasn't in a var it likely got munged,
                   1331:                     # thus grab it from the var directly
                   1332: #		    my $testans=$token->[2]->{'answer'};
                   1333: #		    if ($testans !~ m/^\s*\$/) {
                   1334: #			$answer=$token->[2]->{'answer'};
                   1335: #		    }
1.143     albertel 1336: 		    ${$safeeval->varglob('LONCAPA::response')}=$response;
1.248     www      1337:                     my $preprocess=&Apache::lonxml::get_param('preprocess',$parstack,$safeeval);
                   1338:                     $preprocess=~s/^\&//;
                   1339:                     if (defined($preprocess)) {
                   1340:                         &Apache::run::run('$LONCAPA::response=&'.$preprocess.'($LONCAPA::response);',$safeeval);
                   1341:                     }
1.179     albertel 1342: 		    $result = &Apache::run::run('if ($LONCAPA::response=~m'.$answer.') { return 1; } else { return 0; }',$safeeval);
1.122     albertel 1343: 		    &Apache::lonxml::debug("current $response");
                   1344: 		    &Apache::lonxml::debug("current $answer");
                   1345: 		    $ad = ($result) ? 'APPROX_ANS' : 'INCORRECT';
                   1346: 		} else {
1.248     www      1347: 		    my @args = ('type','preprocess');
1.195     albertel 1348: 		    my $args_ref = &setup_capa_args($safeeval,$parstack,
                   1349: 						    \@args,$response);
1.233     raeburn  1350:                     if ($$args_ref{'type'} eq '') {
                   1351:                         $$args_ref{'type'} = 'ci';
                   1352:                     }
1.264     raeburn  1353:                     my $stringify = 1;
                   1354: 		    &add_in_tag_answer($parstack,$safeeval,$stringify);
1.243     raeburn  1355: 		    my (@final_awards,@final_msgs,@names,%ansstring);
1.195     albertel 1356: 		    foreach my $name (keys(%answer)) {
                   1357: 			&Apache::lonxml::debug(" doing $name with ".join(':',@{ $answer{$name}{'answers'} }));
                   1358: 			${$safeeval->varglob('LONCAPA::CAPAresponse_answer')}=dclone($answer{$name});
1.233     raeburn  1359: 			my ($result, @msgs)=&Apache::run::run("&caparesponse_check_list()",$safeeval);
1.241     raeburn  1360:                         if ($$args_ref{'type'} =~ /^c[si]$/) {
1.243     raeburn  1361:                             $ansstring{$name} = pop(@msgs);
1.242     raeburn  1362:                             my $control_chars_removed = pop(@msgs);
1.241     raeburn  1363:                             my $error = pop(@msgs);
1.242     raeburn  1364:                             if (($error ne '') || 
1.245     raeburn  1365:                                 ($control_chars_removed)) {
1.243     raeburn  1366:                                 my ($symb,$courseid,$sdomain,$sname) =
1.241     raeburn  1367:                                     &Apache::lonnet::whichuser();
1.245     raeburn  1368:                                 if ($control_chars_removed) {
1.242     raeburn  1369:                                     my $showresponse = $response;
                   1370:                                     if ($response =~ /[\000-\037]/) {
                   1371:                                         $response =~ s/[\000-\037]//g;
                   1372:                                     }
                   1373:                                     if ($showresponse  =~ /[\r\n\f]/) {
                   1374:                                         my @lines = split(/[\r\n\f]+/,$showresponse);
                   1375:                                         $showresponse = join('\\n',@lines);
                   1376:                                     }
1.243     raeburn  1377:                                     &Apache::lonnet::logthis("Stringresponse grading: control characters stripped from submission ".$showresponse." for $sname:$sdomain in $courseid for part: $part response: $id and symb: $symb");
1.242     raeburn  1378:                                     $Apache::lonhomework::results{"resource.$part.$id.submission"} = $response;
                   1379:                                 }
                   1380:                                 if ($error ne '') {
1.243     raeburn  1381:                                     &Apache::lonnet::logthis("Stringresponse grading error: $error for $sname:$sdomain in $courseid for part: $part response: $id and symb: $symb");
1.242     raeburn  1382:                                 }
1.241     raeburn  1383:                             }
                   1384:                         }
1.195     albertel 1385: 			&Apache::lonxml::debug('msgs are'.join(':',@msgs));
                   1386: 			my ($awards)=split(/:/,$result);
                   1387: 			my (@awards) = split(/,/,$awards);
                   1388: 			($ad,$msg) = 
                   1389: 			    &Apache::inputtags::finalizeawards(\@awards,\@msgs);
                   1390: 			push(@final_awards,$ad);
                   1391: 			push(@final_msgs,$msg);
                   1392: 			push(@names,$name);
                   1393: 			&Apache::lonxml::debug("\n<br>result:$result:$Apache::lonxml::curdepth<br>\n");
1.122     albertel 1394: 		    }
1.240     raeburn  1395: 		    ($ad, $msg, my $name) = 
1.195     albertel 1396: 			&Apache::inputtags::finalizeawards(\@final_awards,
                   1397: 							   \@final_msgs,
                   1398: 							   \@names,1);
1.243     raeburn  1399:                     if (keys(%ansstring) > 0) {
                   1400:                         $Apache::lonhomework::results{"resource.$part.$id.answerstring"} = &Apache::lonnet::hash2str(%ansstring);
                   1401:                     }
1.122     albertel 1402: 		}
1.237     raeburn  1403:                 if (($ad eq 'INCORRECT' || $ad eq 'APPROX_ANS' ||
                   1404:                      $ad eq 'EXACT_ANS')) {
                   1405: 		    if ($Apache::lonhomework::type eq 'survey') {
                   1406: 		        $ad='SUBMITTED';
                   1407: 		    } elsif ($Apache::lonhomework::type eq 'surveycred') {
                   1408:                         $ad='SUBMITTED_CREDIT';
                   1409:                     } elsif ($Apache::lonhomework::type eq 'anonsurvey') {
                   1410:                         $ad='ANONYMOUS';
                   1411:                     } elsif ($Apache::lonhomework::type eq 'anonsurveycred') {
                   1412:                         $ad='ANONYMOUS_CREDIT';
                   1413:                     }
                   1414:                 }
1.244     raeburn  1415:                 unless (($env{'request.state'} eq 'construct') || 
                   1416:                         ($Apache::lonhomework::type eq 'randomizetry')) {
                   1417:                     if (($ad eq 'INCORRECT' || $ad eq 'APPROX_ANS' || $ad eq 'EXACT_ANS')) {
                   1418:                         if ($previous{'used'}) {
                   1419:                             if ($ad ne $previous{'award'}) {
                   1420:                                 if (($previous{'award'} eq 'INCORRECT' || 
                   1421:                                      $previous{'award'} eq 'APPROX_ANS' ||
                   1422:                                      $previous{'award'} eq 'EXACT_ANS')) {
                   1423:                                     &stringresponse_gradechange($part,$id,\%previous,
                   1424:                                                                 'cs',$response,$ad,$type);
                   1425:                                 }
                   1426:                             }
                   1427:                         } elsif ($previous{'usedci'}) {
                   1428:                             if ($ad ne $previous{'awardci'}) {
                   1429:                                 if (($previous{'awardci'} eq 'INCORRECT' || 
                   1430:                                      $previous{'awardci'} eq 'APPROX_ANS' ||
                   1431:                                      $previous{'awardci'} eq 'EXACT_ANS')) {
                   1432:                                     &stringresponse_gradechange($part,$id,\%previous,
                   1433:                                                                 'ci',$response,$ad,$type);
                   1434:                                 }
                   1435:                             }
1.241     raeburn  1436:                         }
                   1437:                     }
                   1438:                 }
1.122     albertel 1439: 		&Apache::response::handle_previous(\%previous,$ad);
                   1440: 		$Apache::lonhomework::results{"resource.$part.$id.awarddetail"}=$ad;
1.142     albertel 1441: 		$Apache::lonhomework::results{"resource.$part.$id.awardmsg"}=$msg;
1.122     albertel 1442: 	    }
                   1443: 	}
                   1444:     } elsif ($target eq 'answer' || $target eq 'analyze') {
1.264     raeburn  1445:         my $stringify;
                   1446:         if ($type ne 're') {
                   1447:             $stringify = 1;
                   1448:         }
                   1449: 	&add_in_tag_answer($parstack,$safeeval,$stringify);
1.122     albertel 1450: 	if ($target eq 'analyze') {
                   1451: 	    push (@{ $Apache::lonhomework::analyze{"parts"} },"$part.$id");
1.125     albertel 1452: 	    $Apache::lonhomework::analyze{"$part.$id.type"} = 'stringresponse';
1.154     albertel 1453: 	    &Apache::response::check_if_computed($token,$parstack,$safeeval,
                   1454: 						 'answer');
1.122     albertel 1455: 	}
1.140     albertel 1456: 	&Apache::response::setup_params('stringresponse',$safeeval);
1.122     albertel 1457: 	if ($target eq 'answer') {
1.125     albertel 1458: 	    $result.=&Apache::response::answer_header('stringresponse');
1.122     albertel 1459: 	}
1.200     albertel 1460: 	foreach my $name (keys(%answer)) {
                   1461: 	    my @answers = @{ $answer{$name}{'answers'} };
                   1462: 	    for (my $i=0;$i<=$#answers;$i++) {
                   1463: 		my $answer_part = $answers[$i];
                   1464: 		foreach my $element (@{$answer_part}) {
                   1465: 		    if ($target eq 'answer') {
                   1466: 			$result.=&Apache::response::answer_part('stringresponse',
                   1467: 								$element);
1.243     raeburn  1468:                         if ($env{'form.grade_retrieveanswers'}) {
                   1469:                             $env{'form.grade_answers.resource.'.$part.'.'.$id} = $element;
                   1470:                         }
1.200     albertel 1471: 		    } elsif ($target eq 'analyze') {
                   1472: 			push (@{ $Apache::lonhomework::analyze{"$part.$id.answer"}{$name}[$i] },
                   1473: 			      $element);
                   1474: 		    }
                   1475: 		}
                   1476: 		if ($target eq 'answer' && $type eq 're') {
1.178     albertel 1477: 		    $result.=&Apache::response::answer_part('stringresponse',
                   1478: 							    $answerdisplay);
                   1479: 		}
1.122     albertel 1480: 	    }
1.200     albertel 1481: 	}
1.122     albertel 1482: 	my $string='Case Insensitive';
                   1483: 	if ($type eq 'mc') {
                   1484: 	    $string='Multiple Choice';
                   1485: 	} elsif ($type eq 'cs') {
                   1486: 	    $string='Case Sensitive';
                   1487: 	} elsif ($type eq 'ci') {
                   1488: 	    $string='Case Insensitive';
                   1489: 	} elsif ($type eq 're') {
                   1490: 	    $string='Regular Expression';
                   1491: 	}
                   1492: 	if ($target eq 'answer') {
1.166     albertel 1493: 	    if ($env{'form.answer_output_mode'} eq 'tex') {
1.125     albertel 1494: 		$result.=&Apache::response::answer_part('stringresponse',
1.122     albertel 1495: 							"$string");
                   1496: 	    } else {
1.125     albertel 1497: 		$result.=&Apache::response::answer_part('stringresponse',
1.122     albertel 1498: 							"<b>$string</b>");
                   1499: 	    }
                   1500: 	} elsif ($target eq 'analyze') {
                   1501: 	    push (@{$Apache::lonhomework::analyze{"$part.$id.str_type"}},
                   1502: 		  $type);
                   1503: 	}
                   1504: 	if ($target eq 'answer') {
1.125     albertel 1505: 	    $result.=&Apache::response::answer_footer('stringresponse');
1.122     albertel 1506: 	}
                   1507:     } elsif ($target eq 'edit') {
                   1508: 	$result.='</td></tr>'.&Apache::edit::end_table;
1.211     albertel 1509:     } elsif ($target eq 'web' || $target eq 'tex') {
1.212     albertel 1510: 	&Apache::response::setup_prior_tries_hash(\&format_prior_response_string);
1.122     albertel 1511:     }
                   1512:     if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' || 
                   1513: 	$target eq 'tex' || $target eq 'analyze') {
1.249     raeburn  1514:         my $repetition = &Apache::response::repetition();
                   1515: 	&Apache::lonxml::increment_counter($repetition,"$part.$id");
1.220     albertel 1516: 	if ($target eq 'analyze') {
                   1517: 	    &Apache::lonhomework::set_bubble_lines();
                   1518: 	}
1.122     albertel 1519:     }
                   1520:     &Apache::response::end_response;
                   1521:     return $result;
1.44      albertel 1522: }
                   1523: 
                   1524: sub start_formularesponse {
1.89      albertel 1525:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1526:     my $result;
                   1527:     if ($target eq 'meta') {
1.104     bowersj2 1528: 	&Apache::response::start_response($parstack,$safeeval);
1.89      albertel 1529: 	$result=&Apache::response::meta_package_write('formularesponse');
1.104     bowersj2 1530: 	&Apache::response::end_response();
1.89      albertel 1531:     } else {
                   1532: 	$result.=&start_numericalresponse(@_);
                   1533:     }
                   1534:     return $result;
1.44      albertel 1535: }
                   1536: 
                   1537: sub end_formularesponse {
1.89      albertel 1538:     return end_numericalresponse(@_);
1.3       albertel 1539: }
                   1540: 
1.1       albertel 1541: 1;
1.3       albertel 1542: __END__
1.89      albertel 1543: 

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