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

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

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