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

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

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