File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.296: download - view: text, annotated - select for diffs
Tue Nov 29 13:24:38 2011 UTC (12 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
- Bug 2802.
  - optionresponse::is_nonlenient() moved to inputtags::grading_is_nonlenient()
    to facilitate re-use.
  - where solved is "correct", awarded value < 1 permits new submission,
    only if lenient grading applies.
  - add lenient parameter to custompartial.problem template.

    1: # The LearningOnline Network with CAPA
    2: # input  definitons
    3: #
    4: # $Id: inputtags.pm,v 1.296 2011/11/29 13:24:38 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: 
   28: =pod
   29: 
   30: =head1 NAME
   31: 
   32: Apache::inputtags
   33: 
   34: =head1 SYNOPSIS
   35: 
   36: 
   37: 
   38: This is part of the LearningOnline Network with CAPA project
   39: described at http://www.lon-capa.org.
   40: 
   41: 
   42: =head1 NOTABLE SUBROUTINES
   43: 
   44: =over
   45: 
   46: =item 
   47: 
   48: =back
   49: 
   50: =cut
   51: 
   52: package Apache::inputtags;
   53: use HTML::Entities();
   54: use strict;
   55: use Apache::loncommon;
   56: use Apache::lonhtmlcommon;
   57: use Apache::lonlocal;
   58: use Apache::lonnet;
   59: use LONCAPA;
   60:  
   61: 
   62: BEGIN {
   63:     &Apache::lonxml::register('Apache::inputtags',('hiddensubmission','hiddenline','textfield','textline'));
   64: }
   65: 
   66: =pod
   67: 
   68: =item initialize_inputtags()
   69: 
   70: Initializes a set of global variables used during the parse of the problem.
   71: 
   72: @Apache::inputtags::input        - List of current input ids.
   73: @Apache::inputtags::inputlist    - List of all input ids seen this problem.
   74: @Apache::inputtags::response     - List of all current resopnse ids.
   75: @Apache::inputtags::responselist - List of all response ids seen this 
   76:                                      problem.
   77: @Apache::inputtags::hint         - List of all hint ids.
   78: @Apache::inputtags::hintlist     - List of all hint ids seen this problem.
   79: @Apache::inputtags::previous     - List describing if specific responseds
   80:                                      have been used
   81: @Apache::inputtags::previous_version - Submission responses were used in.
   82: $Apache::inputtags::part         - Current part id (valid only in 
   83:                                      <problem>)
   84:                                    0 if not in a part.
   85: @Apache::inputtags::partlist     - List of part ids seen in the current
   86:                                      <problem>
   87: @Apache::inputtags::status       - List of problem  statuses. First 
   88:                                    element is the status of the <problem>
   89:                                    the remainder are for individual <part>s.
   90: %Apache::inputtags::params       - Hash of defined parameters for the
   91:                                    current response.
   92: @Apache::inputtags::import       - List of all ids for <import> thes get
   93:                                    join()ed and prepended.
   94: @Apache::inputtags::importlist   - List of all import ids seen.
   95: $Apache::inputtags::response_with_no_part
   96:                                  - Flag set true if we have seen a response
   97:                                    that is not inside a <part>
   98: %Apache::inputtags::answertxt    - <*response> tags store correct
   99:                                    answer strings for display by <textline/>
  100:                                    in this hash.
  101: %Apache::inputtags::submission_display
  102:                                  - <*response> tags store improved display
  103:                                    of submission strings for display by part
  104:                                    end.
  105: 
  106: =cut
  107: 
  108: sub initialize_inputtags {
  109:     @Apache::inputtags::input=();
  110:     @Apache::inputtags::inputlist=();
  111:     @Apache::inputtags::response=();
  112:     @Apache::inputtags::responselist=();
  113:     @Apache::inputtags::hint=();
  114:     @Apache::inputtags::hintlist=();
  115:     @Apache::inputtags::previous=();
  116:     @Apache::inputtags::previous_version=();
  117:     $Apache::inputtags::part='';
  118:     @Apache::inputtags::partlist=();
  119:     @Apache::inputtags::status=();
  120:     %Apache::inputtags::params=();
  121:     @Apache::inputtags::import=();
  122:     @Apache::inputtags::importlist=();
  123:     $Apache::inputtags::response_with_no_part=0;
  124:     %Apache::inputtags::answertxt=();
  125:     %Apache::inputtags::submission_display=();
  126: }
  127: 
  128: sub check_for_duplicate_ids {
  129:     my %check;
  130:     foreach my $id (@Apache::inputtags::partlist,
  131: 		    @Apache::inputtags::responselist,
  132: 		    @Apache::inputtags::hintlist,
  133: 		    @Apache::inputtags::importlist) {
  134: 	$check{$id}++;
  135:     }
  136:     my @duplicates;
  137:     foreach my $id (sort(keys(%check))) {
  138: 	if ($check{$id} > 1) {
  139: 	    push(@duplicates,$id);
  140: 	}
  141:     }
  142:     if (@duplicates) {
  143: 	&Apache::lonxml::error("Duplicated ids found, problem will operate incorrectly. Duplicated ids seen: ",join(', ',@duplicates));
  144:     }
  145: }
  146: 
  147: sub start_input {
  148:     my ($parstack,$safeeval)=@_;
  149:     my $id = &Apache::lonxml::get_id($parstack,$safeeval);
  150:     push (@Apache::inputtags::input,$id);
  151:     push (@Apache::inputtags::inputlist,$id);
  152:     return $id;
  153: }
  154: 
  155: sub end_input {
  156:     pop @Apache::inputtags::input;
  157:     return '';
  158: }
  159: 
  160: sub addchars {
  161:     my ($fieldid,$addchars)=@_;
  162:     my $output='';
  163:     foreach (split(/\,/,$addchars)) {
  164: 	$output.='<a href="javascript:void(document.forms.lonhomework.'.
  165: 	    $fieldid.'.value+=\''.$_.'\')">'.$_.'</a> ';
  166:     }
  167:     return $output;
  168: }
  169: 
  170: sub start_textfield {
  171:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  172:     my $result = "";
  173:     my $id = &start_input($parstack,$safeeval);
  174:     my $resid=$Apache::inputtags::response[-1];
  175:     if ($target eq 'web') {
  176: 	$Apache::lonxml::evaluate--;
  177: 	my $partid=$Apache::inputtags::part;
  178:         my ($oldresponse,$newvariation);
  179:         if ((($Apache::lonhomework::history{"resource.$partid.type"} eq 'randomizetry') ||
  180:              ($Apache::lonhomework::type eq 'randomizetry')) &&
  181:              ($Apache::inputtags::status[-1] eq 'CAN_ANSWER')) {
  182:             if ($env{'form.'.$partid.'.rndseed'} ne
  183:                 $Apache::lonhomework::history{"resource.$partid.rndseed"}) {
  184:                 $newvariation = 1;
  185:             }
  186:         }
  187:         unless ($newvariation) {
  188: 	    $oldresponse = &HTML::Entities::encode($Apache::lonhomework::history{"resource.$partid.$resid.submission"},'<>&"');
  189:         }
  190: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  191: 	    my $cols = &Apache::lonxml::get_param('cols',$parstack,$safeeval);
  192: 	    if ( $cols eq '') { $cols = 80; }
  193: 	    my $rows = &Apache::lonxml::get_param('rows',$parstack,$safeeval);
  194: 	    if ( $rows eq '') { $rows = 16; }
  195: 	    my $addchars=&Apache::lonxml::get_param('addchars',$parstack,$safeeval);
  196: 	    $result='';
  197: 	    if ($addchars) {
  198: 		$result.=&addchars('HWVAL_'.$resid,$addchars);
  199: 	    }
  200:             my $textareaclass = 'class="LC_richDetectHtml"';
  201: 	    $result.= '<textarea wrap="hard" name="HWVAL_'.$resid.'" id="HWVAL_'.$resid.'" '.
  202: 		      'rows="'.$rows.'" cols="'.$cols.'" '.$textareaclass.'>'.
  203:                       $oldresponse;
  204: 	    if ($oldresponse ne '') {
  205: 
  206: 		#get rid of any startup text if the user has already responded
  207: 		&Apache::lonxml::get_all_text("/textfield",$parser,$style);
  208: 	    }
  209: 	} else {
  210: 	    #show past answer in the essayresponse case
  211: 	    if ($oldresponse =~ /\S/
  212: 		&& &Apache::londefdef::is_inside_of($tagstack,
  213: 						    'essayresponse') ) {
  214: 		$result='<table class="LC_pastsubmission"><tr><td>'.
  215: 		    $oldresponse.'</td></tr></table>';
  216: 	    }
  217: 	    #get rid of any startup text
  218: 	    &Apache::lonxml::get_all_text("/textfield",$parser,$style);
  219: 	}
  220:     } elsif ($target eq 'grade') {
  221: 	my $seedtext=&Apache::lonxml::get_all_text("/textfield",$parser,
  222: 						   $style);
  223: 	if ($seedtext eq $env{'form.HWVAL_'.$resid}) {
  224: 	    # if the seed text is still there it wasn't a real submission
  225: 	    $env{'form.HWVAL_'.$resid}='';
  226: 	}
  227:     } elsif ($target eq 'edit') {
  228: 	$result.=&Apache::edit::tag_start($target,$token);
  229: 	$result.=&Apache::edit::text_arg('Rows:','rows',$token,4);
  230: 	$result.=&Apache::edit::text_arg('Columns:','cols',$token,4);
  231: 	$result.=&Apache::edit::text_arg
  232: 	    ('Click-On Texts (comma sep):','addchars',$token,10);
  233: 	my $bodytext=&Apache::lonxml::get_all_text("/textfield",$parser,
  234: 						   $style);
  235: 	$result.=&Apache::edit::editfield($token->[1],$bodytext,'Text you want to appear by default:',80,2);
  236:     } elsif ($target eq 'modified') {
  237: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  238: 						     $safeeval,'rows','cols',
  239: 						     'addchars');
  240: 	if ($constructtag) {
  241: 	    $result = &Apache::edit::rebuild_tag($token);
  242: 	} else {
  243: 	    $result=$token->[4];
  244: 	}
  245: 	$result.=&Apache::edit::modifiedfield("/textfield",$parser);
  246:     } elsif ($target eq 'tex') {
  247: 	my $number_of_lines = &Apache::lonxml::get_param('rows',$parstack,$safeeval);
  248: 	my $width_of_box = &Apache::lonxml::get_param('cols',$parstack,$safeeval);
  249: 	if ($$tagstack[-2] eq 'essayresponse' and $Apache::lonhomework::type eq 'exam') {
  250: 	    $result = '\fbox{\fbox{\parbox{\textwidth-5mm}{';
  251: 	    for (my $i=0;$i<int $number_of_lines*2;$i++) {$result.='\strut \\\\ ';}
  252: 	    $result.='\strut \\\\\strut \\\\\strut \\\\\strut \\\\}}}';
  253: 	} else {
  254: 	    my $TeXwidth=$width_of_box/80;
  255: 	    $result = '\vskip 1 mm \fbox{\fbox{\parbox{'.$TeXwidth.'\textwidth-5mm}{';
  256: 	    for (my $i=0;$i<int $number_of_lines*2;$i++) {$result.='\strut \\\\ ';}
  257: 	    $result.='}}}\vskip 2 mm ';
  258: 	}
  259:     }
  260:     return $result;
  261: }
  262: 
  263: sub end_textfield {
  264:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  265:     my $result;
  266:     if ($target eq 'web') {
  267: 	$Apache::lonxml::evaluate++;
  268: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  269: 	    return "</textarea>";
  270: 	}
  271:     } elsif ($target eq 'edit') {
  272: 	$result=&Apache::edit::end_table();
  273:     }
  274:     &end_input;
  275:     return $result;
  276: }
  277: 
  278: sub exam_score_line {
  279:     my ($target) = @_;
  280: 
  281:     my $result;
  282:     if ($target eq 'tex') {
  283: 	my $repetition = &Apache::response::repetition();
  284: 	$result.='\begin{enumerate}';
  285: 	if ($env{'request.state'} eq "construct" ) {$result.='\item[\strut]';}
  286: 	foreach my $i (0..$repetition-1) {
  287: 	    $result.='\item[\textbf{'.
  288: 		($Apache::lonxml::counter+$i).
  289: 		'}.]\textit{Leave blank on scoring form}\vskip 0 mm';
  290: 	}
  291: 	$result.= '\end{enumerate}';
  292:     }
  293: 
  294:     return $result;
  295: }
  296: 
  297: sub exam_box {
  298:     my ($target) = @_;
  299:     my $result;
  300: 
  301:     if ($target eq 'tex') {
  302: 	$result .= '\fbox{\fbox{\parbox{\textwidth-5mm}{\strut\\\\\strut\\\\\strut\\\\\strut\\\\}}}';
  303: 	$result .= &exam_score_line($target);
  304:     } elsif ($target eq 'web') {
  305: 	my $id=$Apache::inputtags::response[-1];
  306: 	$result.= '<br /><br />
  307:                    <textarea name="HWVAL_'.$id.'" rows="4" cols="50">
  308:                    </textarea> <br /><br />';
  309:     }
  310:     return $result;
  311: }
  312: 
  313: sub needs_exam_box {
  314:     my ($tagstack) = @_;
  315:     my @tags = ('formularesponse',
  316: 		'stringresponse',
  317: 		'reactionresponse',
  318: 		'organicresponse',
  319: 		);
  320: 
  321:     foreach my $tag (@tags) {
  322: 	if (grep(/\Q$tag\E/,@$tagstack)) {
  323: 	    return 1;
  324: 	}
  325:     }
  326:     return 0;
  327: }
  328: 
  329: sub start_textline {
  330:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  331:     my $result = "";
  332:     my $input_id = &start_input($parstack,$safeeval);
  333:     if ($target eq 'web') {
  334: 	$Apache::lonxml::evaluate--;
  335: 	my $partid=$Apache::inputtags::part;
  336: 	my $id=$Apache::inputtags::response[-1];
  337: 	if (!&Apache::response::show_answer()) {
  338: 	    my $size = &Apache::lonxml::get_param('size',$parstack,$safeeval);
  339: 	    my $maxlength;
  340: 	    if ($size eq '') { $size=20; } else {
  341: 		if ($size < 20) {
  342: 		    $maxlength = ' maxlength="'.$size.'"';
  343: 		}
  344: 	    }
  345:             my ($oldresponse,$newvariation);
  346:             if ((($Apache::lonhomework::history{"resource.$partid.type"} eq 'randomizetry') ||
  347:                  ($Apache::lonhomework::type eq 'randomizetry')) &&
  348:                  ($Apache::inputtags::status[-1] eq 'CAN_ANSWER')) {
  349:                 if ($env{'form.'.$partid.'.rndseed'} ne
  350:                     $Apache::lonhomework::history{"resource.$partid.rndseed"}) {
  351:                     $newvariation = 1;
  352:                 }
  353:             }
  354:             unless ($newvariation) {
  355: 	        $oldresponse = $Apache::lonhomework::history{"resource.$partid.$id.submission"};
  356: 	        &Apache::lonxml::debug("oldresponse $oldresponse is ".ref($oldresponse));
  357: 	        if (ref($oldresponse) eq 'ARRAY') {
  358: 		    $oldresponse = $oldresponse->[$#Apache::inputtags::inputlist];
  359: 	        }
  360: 	        $oldresponse = &HTML::Entities::encode($oldresponse,'<>&"');
  361:                 $oldresponse =~ s/^\s+//;
  362:                 $oldresponse =~ s/\s+$//;
  363:                 $oldresponse =~ s/\s+/ /g;
  364:             }
  365: 	    if ($Apache::lonhomework::type ne 'exam') {
  366: 		my $addchars=&Apache::lonxml::get_param('addchars',$parstack,$safeeval);
  367: 		$result='';
  368: 		if ($addchars) {
  369: 		    $result.=&addchars('HWVAL_'.$id,$addchars);
  370: 		}
  371: 		my $readonly=&Apache::lonxml::get_param('readonly',$parstack,
  372: 							$safeeval);
  373: 		if (lc($readonly) eq 'yes' 
  374: 		    || $Apache::inputtags::status[-1] eq 'CANNOT_ANSWER') {
  375: 		    $readonly=' readonly="readonly" ';
  376: 		} else {
  377: 		    $readonly='';
  378: 		}
  379: 		my $name = 'HWVAL_'.$id;
  380: 		if ($Apache::inputtags::status[-1] eq 'CANNOT_ANSWER') {
  381: 		    $name = "none";
  382: 		}
  383: 		$result.= '<input onkeydown="javascript:setSubmittedPart(\''.$partid.'\');" type="text" '.$readonly.' name="'.$name.'" value="'.
  384: 		    $oldresponse.'" size="'.$size.'"'.$maxlength.' />';
  385: 	    }
  386: 	    if ($Apache::lonhomework::type eq 'exam'
  387: 		&& &needs_exam_box($tagstack)) {
  388: 		$result.=&exam_box($target);
  389: 	    }
  390: 	} else {
  391: 	    #right or wrong don't show what was last typed in.
  392: 	    my $count = scalar(@Apache::inputtags::inputlist)-1;
  393: 	    $result='<b>'.$Apache::inputtags::answertxt{$id}[$count].'</b>';
  394: 	    #$result='';
  395: 	}
  396:     } elsif ($target eq 'edit') {
  397: 	$result=&Apache::edit::tag_start($target,$token);
  398: 	$result.=&Apache::edit::text_arg('Size:','size',$token,'5').
  399: 	    &Apache::edit::text_arg('Click-On Texts (comma sep):',
  400: 				    'addchars',$token,10);
  401:         $result.=&Apache::edit::select_arg('Readonly:','readonly',
  402: 					   ['no','yes'],$token);
  403: 	$result.=&Apache::edit::end_row();
  404: 	$result.=&Apache::edit::end_table();
  405:     } elsif ($target eq 'modified') {
  406: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  407: 						     $safeeval,'size',
  408: 						     'addchars','readonly');
  409: 	if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
  410:     } elsif ($target eq 'tex' 
  411: 	     && $Apache::lonhomework::type ne 'exam') {
  412: 	my $size = &Apache::lonxml::get_param('size',$parstack,$safeeval);
  413: 	if ($size != 0) {$size=$size*2; $size.=' mm';} else {$size='40 mm';}
  414: 	if ($env{'form.pdfFormFields'} eq 'yes'
  415:             && $Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  416:             my $fieldname = $env{'request.symb'}.
  417:                                  '&part_'. $Apache::inputtags::part.
  418:                                  '&textresponse'.
  419:                                  '&HWVAL_' . $Apache::inputtags::response['-1'];
  420:             $result='\textField{'.$fieldname.'}{'.$size.'}{12 bp}';
  421:         } else {
  422:             $result='\framebox['.$size.'][s]{\tiny\strut}';
  423:         }
  424:     } elsif ($target eq 'tex' 
  425: 	     && $Apache::lonhomework::type eq 'exam'
  426: 	     && &needs_exam_box($tagstack)) {
  427: 	$result.=&exam_box($target);
  428:     }
  429:     return $result;
  430: }
  431: 
  432: sub end_textline {
  433:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  434:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  435:     elsif ($target eq 'edit') { return ('','no'); }
  436:     &end_input();
  437:     return "";
  438: }
  439: 
  440: sub start_hiddenline {
  441:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  442:     my $result = "";
  443:     my $input_id = &start_input($parstack,$safeeval);
  444:     if ($target eq 'web') {
  445: 	$Apache::lonxml::evaluate--;
  446: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  447: 	    my $partid=$Apache::inputtags::part;
  448: 	    my $id=$Apache::inputtags::response[-1];
  449: 	    my $oldresponse = $Apache::lonhomework::history{"resource.$partid.$id.submission"};
  450: 	    if (ref($oldresponse) eq 'ARRAY') {
  451: 		$oldresponse = $oldresponse->[$#Apache::inputtags::inputlist];
  452: 	    }
  453: 	    $oldresponse = &HTML::Entities::encode($oldresponse,'<>&"');
  454: 
  455: 	    if ($Apache::lonhomework::type ne 'exam') {
  456: 		$result= '<input type="hidden" name="HWVAL_'.$id.'" value="'.
  457: 		    $oldresponse.'" />';
  458: 	    }
  459: 	}
  460:     } elsif ($target eq 'edit') {
  461: 	$result=&Apache::edit::tag_start($target,$token);
  462: 	$result.=&Apache::edit::end_table;
  463:     }
  464: 
  465:     if ( ($target eq 'web' || $target eq 'tex')
  466: 	 && $Apache::lonhomework::type eq 'exam'
  467: 	 && &needs_exam_box($tagstack)) {
  468: 	$result.=&exam_box($target);
  469:     }
  470:     return $result;
  471: }
  472: 
  473: sub end_hiddenline {
  474:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  475:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  476:     elsif ($target eq 'edit') { return ('','no'); }
  477:     &end_input();
  478:     return "";
  479: }
  480: 
  481: 
  482: sub start_hiddensubmission {
  483:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  484:     my $result = "";
  485:     my $input_id = &start_input($parstack,$safeeval);
  486:     if ($target eq 'web') {
  487:         $Apache::lonxml::evaluate--;
  488:         if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  489:             my $partid=$Apache::inputtags::part;
  490:             my $id=$Apache::inputtags::response[-1];
  491:             if ($Apache::lonhomework::type ne 'exam') {
  492:                 my $value = &Apache::lonxml::get_param('value',$parstack,$safeeval);
  493:                 $value = &HTML::Entities::encode($value,'<>&"');
  494:                 $result= '<input type="hidden" name="HWVAL_'.$id.'" value="'.$value.'" />';
  495:             }
  496:         }
  497:     } elsif ($target eq 'edit') {
  498:         $result=&Apache::edit::tag_start($target,$token);
  499:         $result.=&Apache::edit::text_arg('Value:','value',$token,'15');
  500:         $result.=&Apache::edit::end_row();
  501:         $result.=&Apache::edit::end_table();
  502:     } elsif ($target eq 'modified') {
  503:         my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  504:                                                      $safeeval,'value');
  505:         if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
  506:     }
  507: 
  508:     if ( ($target eq 'web' || $target eq 'tex')
  509:          && $Apache::lonhomework::type eq 'exam'
  510:          && &needs_exam_box($tagstack)) {
  511:         $result.=&exam_box($target);
  512:     }
  513:     return $result;
  514: }
  515: 
  516: sub end_hiddensubmission {
  517:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  518:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  519:     elsif ($target eq 'edit') { return ('','no'); }
  520:     &end_input();
  521:     return "";
  522: }
  523: 
  524: =pod
  525: 
  526: =item file_selector()
  527: 
  528: $part -> partid
  529: $id -> responseid
  530: $uploadefiletypes -> comma seperated list of extensions allowed or * for any
  531: $which -> 'uploadonly'  -> only newly uploaded files
  532:           'portfolioonly' -> only allow files from portfolio
  533:           'both' -> allow files from either location
  534: $extratext -> additional text to go between the link and the input box
  535: $maxfilesize -> maximum cumulative filesize for submitted files (in MB).
  536: returns a table row <tr> 
  537: 
  538: =cut
  539: 
  540: sub file_selector {
  541:     my ($part,$id,$uploadedfiletypes,$which,$extratext,$maxfilesize)=@_;
  542:     if (!$uploadedfiletypes) { return ''; }
  543: 
  544:     my $jspart=$part;
  545:     $jspart=~s/\./_/g;
  546: 
  547:     my $result;
  548:     my $current_files_display = &current_file_submissions($part,$id);
  549:     my $addfiles;
  550:     if ($current_files_display) {
  551:         $result .= &Apache::lonhtmlcommon::row_title(&mt('Currently submitted files')).
  552:                    $current_files_display.
  553:                    &Apache::lonhtmlcommon::row_closure();
  554:         $addfiles = &mt('Submit other file(s)');
  555:     } else {
  556:         $addfiles = &mt('Choose file(s) to submit');
  557:     }
  558:     $result .= &Apache::lonhtmlcommon::row_title($addfiles);
  559:     my $constraints;
  560:     if ($uploadedfiletypes ne '*') {
  561: 	$constraints =
  562: 	    &mt('Allowed filetypes: [_1]','<b>'.$uploadedfiletypes.'</b>').'<br />';
  563:     }
  564:     if ($maxfilesize) {
  565:         $constraints .= &mt('Combined size of all files not to exceed: [_1] MB[_2].',
  566:                         '<b>'.$maxfilesize.'</b>').'<br />';
  567:     }
  568:     if ($constraints) {
  569:         $result .= $constraints.'<br />';
  570:     }
  571:     if ($which eq 'uploadonly' || $which eq 'both') { 
  572: 	$result.=&mt('Submit a file: (only one file per submission)').
  573: 	    ' <br /><input type="file" size="50" name="HWFILE'.
  574: 	    $jspart.'_'.$id.'" id="HWFILE'.$jspart.'_'.$id.'" /><br />';
  575:     }
  576:     if ( $which eq 'both') {
  577: 	$result.='<br />'.'<strong>'.&mt('OR:').'</strong><br />';
  578:     }
  579:     if ($which eq 'portfolioonly' || $which eq 'both') { 
  580: 	$result.=$extratext.'<a href='."'".'javascript:void(window.open("/adm/portfolio?mode=selectfile&amp;fieldname='.$env{'form.request.prefix'}.'HWPORT'.$jspart.'_'.$id.'","cat","height=600,width=800,scrollbars=1,resizable=1,menubar=2,location=1"))'."'".'>'.
  581: 	    &mt('Select Portfolio Files: (one or more files per submission)').'</a><br />'.
  582: 	    '<input type="text" size="50" name="HWPORT'.$jspart.'_'.$id.'" value="" />'.
  583: 	    '<br />';
  584: 
  585:     }
  586:     $result.=&Apache::lonhtmlcommon::row_closure(1);
  587:     return $result;
  588: }
  589: 
  590: sub current_file_submissions {
  591:     my ($part,$id) = @_;
  592:     my $jspart=$part;
  593:     $jspart=~s/\./_/g;
  594:     my $uploadedfile=$Apache::lonhomework::history{"resource.$part.$id.uploadedfile"};
  595:     my $portfiles=$Apache::lonhomework::history{"resource.$part.$id.portfiles"};
  596:     return if (($uploadedfile eq '') && ($portfiles !~/[^\s]/));
  597:     my $header = &Apache::loncommon::start_data_table().
  598:                  &Apache::loncommon::start_data_table_header_row();
  599:     if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  600:         $header .= '<th>'.&mt('Delete?').'</th>';
  601:     }
  602:     $header .=   '<th>'.&mt('File').'</th>'.
  603:                  '<th>'.&mt('Size (MB)').'</th>'.
  604:                  '<th>'.&mt('Last Modified').'</th>'.
  605:                  &Apache::loncommon::end_data_table_header_row();
  606:     my (undef,$crsid,$udom,$uname)=&Apache::lonnet::whichuser();
  607:     my ($cdom,$cnum) = ($crsid =~ /^($LONCAPA::match_domain)_($LONCAPA::match_courseid)$/);
  608:     my ($result,$header_shown,%okfiles,%rows,%legacy,@bad_file_list);
  609:     if ($uploadedfile) {
  610:         my $url=$Apache::lonhomework::history{"resource.$part.$id.uploadedurl"};
  611:         my $link = &HTML::Entities::encode($url,'<>&"');
  612:         my ($path,$name) = ($url =~ m{^(/uploaded/\Q$udom\E/\Q$uname\E/essayresponse.*/)([^/]+)$});
  613:         my ($status,$hashref,$error) =
  614:             &current_file_info($url,$link,$name,$path);
  615:         if ($status eq 'ok') {
  616:             push(@{$okfiles{$name}},$url);
  617:             $rows{$url} = $hashref;
  618:             $legacy{$url} = 1;
  619:             &Apache::lonxml::extlink($url);
  620:             &Apache::lonnet::allowuploaded('/adm/essayresponse',$url);
  621:         } else {
  622:             push(@bad_file_list,$error);
  623:         }
  624:     }
  625:     if ($portfiles =~ /[^\s]/) {
  626:         my $prefix = "/uploaded/$udom/$uname/portfolio";
  627:         foreach my $file (split(/\s*,\s*/,&unescape($portfiles))) {
  628:             my ($path,$name) = ($file =~ m{^(.*/)([^/]+)$});
  629:             my $url = $prefix.$path.$name;
  630:             my $uploadedfile = &HTML::Entities::encode($url,'<>&"');
  631:             my ($status,$hashref,$error) =
  632:                 &current_file_info($url,$uploadedfile,$name,$path);
  633:             if ($status eq 'ok') {
  634:                 push(@{$okfiles{$name}},$url);
  635:                 $rows{$url} = $hashref;
  636:             } else {
  637:                 push(@bad_file_list,$error);
  638:             }
  639:         }
  640:     }
  641:     my $num = 0;
  642:     foreach my $name (sort(keys(%okfiles))) {
  643:         if (ref($okfiles{$name}) eq 'ARRAY') {
  644:             foreach my $url (@{$okfiles{$name}}) {
  645:                 if (ref($rows{$url}) eq 'HASH') {
  646:                     my $link = $rows{$url}{link};
  647:                     my $portfile = $rows{$url}{path}.$rows{$url}{name};
  648:                     $portfile = &HTML::Entities::encode($portfile,'<>&"');
  649:                     if ($link) {
  650:                         my $icon=&Apache::loncommon::icon($url);
  651:                         unless ($header_shown) {
  652:                             $result .= $header;
  653:                             $header_shown = 1;
  654:                         }
  655:                         $result.=
  656:                             &Apache::loncommon::start_data_table_row()."\n";
  657:                         if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  658:                             $result .=
  659:                                  '<td valign="bottom"><input type="checkbox" name="HWFILE'.$jspart.'_'.$id.'_delete"'.
  660:                                  ' value="'.$portfile.'" id="HWFILE'.$jspart.'_'.$id.'_'.$num.'_delete" /></td>'."\n";
  661:                             $num ++;
  662:                         }
  663:                         my $showname = $rows{$url}{path}.$name;
  664:                         if ($legacy{$url}) {
  665:                             $showname = $name.' '.&mt('not in portfolio');
  666:                         }
  667:                         $result .= 
  668:                             '<td><a href="'.$link.'"><img src="'.$icon.
  669:                             '" border="0" alt="" />'.$showname.'</a></td>'."\n".
  670:                             '<td align="right" valign="bottom">'.$rows{$url}{size}.'</td>'."\n".
  671:                             '<td align="right" valign="bottom">'.$rows{$url}{lastmodified}.'</td>'."\n".
  672:                             &Apache::loncommon::end_data_table_row();
  673:                     }
  674:                 }
  675:             }
  676:         }
  677:     }
  678:     if ($header_shown) {
  679:         $result .= &Apache::loncommon::end_data_table().
  680:                    '<br /><span class="LC_warning">'.
  681:                    &mt('Exclude existing file(s) from grading by checking the "Delete?" checkbox(es) and clicking "Submit Answer"').'</span>';
  682:     }
  683:     if (@bad_file_list) {
  684:         my $bad_files = '<span class="LC_filename">'.
  685:             join('</span>, <span class="LC_filename">',@bad_file_list).
  686:             '</span>';
  687:         $result.='<p class="LC_error">'.
  688:                  &mt("These file(s) don't exist: [_1]",$bad_files).
  689:                  '</p>';
  690:     }
  691:     return $result;
  692: }
  693: 
  694: sub current_file_info {
  695:     my ($url,$uploadedfile,$name,$path) = @_;
  696:     my ($status,$error,%info);
  697:     my @stat = &Apache::lonnet::stat_file($url);
  698:     if ((@stat) && ($stat[0] ne 'no_such_dir')) {
  699:         my ($lastmod,$size);
  700:         if ($stat[9] =~ /^\d+$/) {
  701:             $lastmod = &Apache::lonlocal::locallocaltime($stat[9]);
  702:         }
  703:         $size = $stat[7]/(1024*1024);
  704:         $size = sprintf("%.3f",$size);
  705:         %info = (
  706:                     link         => $uploadedfile,
  707:                     name         => $name,
  708:                     path         => $path,
  709:                     size         => $size,
  710:                     lastmodified => $lastmod,
  711:                 );
  712:         $status = 'ok';
  713:     } else {
  714:         &Apache::lonnet::logthis("bad file is $url");
  715:         my $icon=&Apache::loncommon::icon($url);
  716:         $error = '<a href="'.$url.'"><img src="'.$icon.
  717:                  '" border="0" />'.$uploadedfile.'</a>';
  718:     }
  719:     return ($status,\%info,$error);
  720: }
  721: 
  722: sub valid_award {
  723:     my ($award) =@_;
  724:     foreach my $possibleaward ('EXTRA_ANSWER','MISSING_ANSWER', 'ERROR',
  725: 			       'NO_RESPONSE',
  726: 			       'TOO_LONG', 'UNIT_INVALID_INSTRUCTOR',
  727: 			       'UNIT_INVALID_STUDENT', 'UNIT_IRRECONCIBLE',
  728: 			       'UNIT_FAIL', 'NO_UNIT',
  729: 			       'UNIT_NOTNEEDED', 'WANTED_NUMERIC',
  730: 			       'BAD_FORMULA', 'NOT_FUNCTION', 'WRONG_FORMAT', 
  731:                                'INTERNAL_ERROR', 'SIG_FAIL', 'INCORRECT', 
  732: 			       'MISORDERED_RANK', 'INVALID_FILETYPE',
  733:                                'EXCESS_FILESIZE', 'FILENAME_INUSE', 
  734: 			       'DRAFT', 'SUBMITTED', 'SUBMITTED_CREDIT', 
  735:                                'ANONYMOUS', 'ANONYMOUS_CREDIT',
  736:                                'ASSIGNED_SCORE', 'APPROX_ANS',
  737: 			       'EXACT_ANS','COMMA_FAIL') {
  738: 	if ($award eq $possibleaward) { return 1; }
  739:     }
  740:     return 0;
  741: }
  742: 
  743: {
  744:     my @awards = ('EXTRA_ANSWER', 'MISSING_ANSWER', 'ERROR', 'NO_RESPONSE',
  745: 		  'TOO_LONG',
  746: 		  'UNIT_INVALID_INSTRUCTOR', 'UNIT_INVALID_STUDENT',
  747: 		  'UNIT_IRRECONCIBLE', 'UNIT_FAIL', 'NO_UNIT',
  748: 		  'UNIT_NOTNEEDED', 'WANTED_NUMERIC', 'BAD_FORMULA',  'NOT_FUNCTION', 
  749:                   'WRONG_FORMAT', 'INTERNAL_ERROR',
  750: 		  'COMMA_FAIL', 'SIG_FAIL', 'INCORRECT', 'MISORDERED_RANK',
  751: 		  'INVALID_FILETYPE', 'EXCESS_FILESIZE', 'FILENAME_INUSE', 
  752:                   'DRAFT', 'SUBMITTED',
  753:                   'SUBMITTED_CREDIT', 'ANONYMOUS', 'ANONYMOUS_CREDIT',
  754:                   'ASSIGNED_SCORE', 'APPROX_ANS', 'EXACT_ANS');
  755:     my $i=0;
  756:     my %fwd_awards = map { ($_,$i++) } @awards;
  757:     my $max=scalar(@awards);
  758:     @awards=reverse(@awards);
  759:     $i=0;
  760:     my %rev_awards = map { ($_,$i++) } @awards;
  761: 
  762: sub awarddetail_to_awarded {
  763:     my ($awarddetail) = @_;
  764:     if ($awarddetail eq 'EXACT_ANS'
  765: 	|| $awarddetail eq 'APPROX_ANS') {
  766: 	return 1;
  767:     }
  768:     return 0;
  769: }
  770: 
  771: sub hide_award {
  772:     my ($award) = @_;
  773:     if (&Apache::lonhomework::show_no_problem_status()) {
  774: 	return 1;
  775:     }
  776:     if ($award =~
  777: 	/^(?:EXACT_ANS|APPROX_ANS|SUBMITTED|SUBMITTED_CREDIT|ANONYMOUS|ANONYMOUS_CREDIT|ASSIGNED_SCORE|INCORRECT)/) {
  778: 	return 1;
  779:     }
  780:     return 0;
  781: }
  782: 
  783: sub finalizeawards {
  784:     my ($awardref,$msgref,$nameref,$reverse,$final_scantron)=@_;
  785:     my $result;
  786:     if ($#$awardref == -1) { $result = "NO_RESPONSE"; }
  787:     if ($result eq '' ) {
  788: 	my $blankcount;
  789: 	foreach my $award (@$awardref) {
  790: 	    if ($award eq '') {
  791: 		$result='MISSING_ANSWER';
  792: 		$blankcount++;
  793: 	    }
  794: 	}
  795: 	if ($blankcount == ($#$awardref + 1)) {
  796: 	    return ('NO_RESPONSE');
  797: 	}
  798:     }
  799: 
  800:     if ($Apache::lonxml::internal_error) { $result='INTERNAL_ERROR'; }
  801: 
  802:     if (!$final_scantron && defined($result)) { return ($result); }
  803: 
  804:     # if in scantron mode, if the award for any response is 
  805:     # assigned score, then the part gets an assigned score
  806:     if ($final_scantron 
  807: 	&& grep {$_ eq 'ASSIGNED_SCORE'} (@$awardref)) {
  808: 	return ('ASSIGNED_SCORE');
  809:     }
  810: 
  811:     # if in scantron mode, if the award for any response is 
  812:     # correct and there are non-correct responses,
  813:     # then the part gets an assigned score
  814:     if ($final_scantron 
  815: 	&& (grep { $_ eq 'EXACT_ANS' ||
  816: 		   $_ eq 'APPROX_ANS'  } (@$awardref))
  817: 	&& (grep { $_ ne 'EXACT_ANS' &&
  818: 		   $_ ne 'APPROX_ANS'  } (@$awardref))) {
  819: 	return ('ASSIGNED_SCORE');
  820:     }
  821:     # these awards are ordered from most important error through best correct
  822:     my $awards = (!$reverse) ? \%fwd_awards : \%rev_awards ;
  823: 
  824:     my $best = $max;
  825:     my $j=0;
  826:     my $which;
  827:     foreach my $award (@$awardref) {
  828: 	if ($awards->{$award} < $best) {
  829: 	    $best  = $awards->{$award};
  830: 	    $which = $j;
  831: 	}
  832: 	$j++;
  833:     }
  834: 
  835:     if (defined($which)) {
  836: 	if (ref($nameref)) {
  837: 	    return ($$awardref[$which],$$msgref[$which],$$nameref[$which]);
  838: 	} else {
  839: 	    return ($$awardref[$which],$$msgref[$which]);
  840: 	}
  841:     }
  842:     return ('ERROR',undef);
  843: }
  844: }
  845: 
  846: sub grading_is_nonlenient {
  847:     my ($part) = @_;
  848: # Web mode: we are non-lenient unless told otherwise
  849:     my $defaultparm = 'off';
  850:     my $nonlenient = 0;
  851: # Grading a bubblesheet exam: we are grading lenient unless told otherwise
  852:     if ($Apache::lonhomework::scantronmode) {
  853:         $defaultparm = 'on';
  854:         $nonlenient = 1;
  855:     }
  856:     my $lenientparm =
  857:         &Apache::response::get_response_param($part,'lenient',$defaultparm);
  858:     if ($lenientparm=~/^0|off|no$/i) {
  859:         $nonlenient = 1;
  860:     } elsif ($lenientparm=~/^1|on|yes$/i) {
  861:         $nonlenient = 0;
  862:     }
  863:     return $nonlenient;
  864: }
  865: 
  866: sub decideoutput {
  867:     my ($award,$awarded,$awardmsg,$solved,$previous,$target,$nocorrect)=@_;
  868: 
  869:     my $message='';
  870:     my $button=0;
  871:     my $previousmsg;
  872:     my $css_class='orange';
  873:     my $added_computer_text=0;
  874:     my %possible_class =
  875: 	( 'correct'         => 'LC_answer_correct',
  876: 	  'charged_try'     => 'LC_answer_charged_try',
  877: 	  'not_charged_try' => 'LC_answer_not_charged_try',
  878: 	  'no_grade'        => 'LC_answer_no_grade',
  879: 	  'no_message'      => 'LC_no_message',
  880: 	  );
  881: 
  882:     my $part = $Apache::inputtags::part;
  883:     my $tohandgrade = &Apache::lonnet::EXT("resource.$part.handgrade");
  884:     my $handgrade = ('yes' eq lc($tohandgrade)); 
  885: #
  886: # Should "Computer's Answer" be displayed?
  887: # Should not be displayed if still answerable,
  888: # if the problem is handgraded,
  889: # or if the problem does not give a correct answer
  890: #
  891:     
  892:     my $computer = ($handgrade || $nocorrect)? ''
  893: 	                       : " ".&mt("Computer's answer now shown above.");
  894:     &Apache::lonxml::debug("handgrade has :$handgrade:");
  895: 
  896:     if ($previous) { $previousmsg=&mt('You have entered that answer before'); }
  897:     
  898:     if ($solved =~ /^correct/) {
  899:         $css_class=$possible_class{'correct'};
  900: 	$message=&mt('You are correct.');
  901: 	if ($awarded < 1 && $awarded > 0) {
  902: 	    $message=&mt('You are partially correct.');
  903: 	    $css_class=$possible_class{'not_charged_try'};
  904: 	} elsif ($awarded < 1) {
  905: 	    $message=&mt('Incorrect.');
  906: 	    $css_class=$possible_class{'charged_try'};
  907: 	}
  908: 	if ($handgrade || 
  909:             ($env{'request.filename'}=~/\/res\/lib\/templates\/(examupload|DropBox).problem$/)) {
  910: 	    $message = &mt("A score has been assigned.");
  911: 	    $added_computer_text=1;
  912: 	} else {
  913: 	    if ($target eq 'tex') {
  914: 		$message = '\textbf{'.$message.'}';
  915: 	    } else {
  916: 		$message = "<b>".$message."</b>";
  917: 		$message.= $computer;
  918: 	    }
  919: 	    $added_computer_text=1;
  920: 	    if ($awarded > 0) {
  921: 		my ($symb) = &Apache::lonnet::whichuser();
  922: 		if (($symb ne '') 
  923: 		    &&
  924: 		    ($env{'course.'.$env{'request.course.id'}.
  925: 			      '.disable_receipt_display'} ne 'yes') &&
  926:                     ($Apache::lonhomework::type ne 'practice')) { 
  927: 		    $message.=(($target eq 'web')?'<br />':' ').
  928: 			&mt('Your receipt no. is [_1]',
  929: 			    (&Apache::lonnet::receipt($Apache::inputtags::part).
  930: 			     (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'')));
  931: 		}
  932: 	    }
  933: 	}
  934:         if (&grading_is_nonlenient($part)) {
  935:             $button=0;
  936:         } elsif ($awarded==1) {
  937:             $button=0;
  938:         } else { 
  939:             $button=1;
  940:         }
  941: 	$previousmsg='';
  942:     } elsif ($solved =~ /^excused/) {
  943: 	if ($target eq 'tex') {
  944: 	    $message = ' \textbf{'.&mt('You are excused from the problem.').'} ';
  945: 	} else {
  946: 	    $message = "<b>".&mt('You are excused from the problem.')."</b>";
  947: 	}
  948: 	$css_class=$possible_class{'charged_try'};
  949: 	$button=0;
  950: 	$previousmsg='';
  951:     } elsif ($award eq 'EXACT_ANS' || $award eq 'APPROX_ANS' ) {
  952: 	if ($solved =~ /^incorrect/ || $solved eq '') {
  953: 	    $message = &mt("Incorrect").".";
  954: 	    $css_class=$possible_class{'charged_try'};
  955: 	    $button=1;
  956: 	} else {
  957: 	    if ($target eq 'tex') {
  958: 		$message = '\textbf{'.&mt('You are correct.').'}';
  959: 	    } else {
  960: 		$message = "<b>".&mt('You are correct.')."</b>";
  961: 		$message.= $computer;
  962: 	    }
  963: 	    $added_computer_text=1;
  964: 	    if  ($awarded > 0 
  965: 		 && $env{'course.'.
  966: 			     $env{'request.course.id'}.
  967: 			     '.disable_receipt_display'} ne 'yes') { 
  968: 		$message.=(($target eq 'web')?'<br />':' ').
  969: 		    &mt('Your receipt is [_1]',
  970: 			(&Apache::lonnet::receipt($Apache::inputtags::part).
  971: 			 (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'')));
  972: 	    }
  973: 	    $css_class=$possible_class{'correct'};
  974: 	    $button=0;
  975: 	    $previousmsg='';
  976: 	}
  977:     } elsif ($award eq 'NO_RESPONSE') {
  978: 	$message = '';
  979: 	$css_class=$possible_class{'no_feedback'};
  980: 	$button=1;
  981:     } elsif ($award eq 'EXTRA_ANSWER') {
  982: 	$message = &mt('Some extra items were submitted.');
  983: 	$css_class=$possible_class{'not_charged_try'};
  984: 	$button = 1;
  985:     } elsif ($award eq 'MISSING_ANSWER') {
  986: 	$message = &mt('Some items were not submitted.');
  987:         if ($target ne 'tex') {
  988:            $message .= &Apache::loncommon::help_open_topic('Some_Items_Were_Not_Submitted');
  989:         }
  990: 	$css_class=$possible_class{'not_charged_try'};
  991: 	$button = 1;
  992:     } elsif ($award eq 'ERROR') {
  993: 	$message = &mt('An error occurred while grading your answer.');
  994: 	$css_class=$possible_class{'not_charged_try'};
  995: 	$button = 1;
  996:     } elsif ($award eq 'TOO_LONG') {
  997: 	$message = &mt("The submitted answer was too long.");
  998: 	$css_class=$possible_class{'not_charged_try'};
  999: 	$button=1;
 1000:     } elsif ($award eq 'WANTED_NUMERIC') {
 1001: 	$message = &mt("This question expects a numeric answer.");
 1002: 	$css_class=$possible_class{'not_charged_try'};
 1003: 	$button=1;
 1004:     } elsif ($award eq 'MISORDERED_RANK') {
 1005:         $message = &mt('You have provided an invalid ranking.');
 1006:         if ($target ne 'tex') {
 1007:             $message.=' '.&mt('Please refer to [_1]',&Apache::loncommon::help_open_topic('Ranking_Problems',&mt('help on ranking problems')));
 1008:         }
 1009: 	$css_class=$possible_class{'not_charged_try'};
 1010: 	$button=1;
 1011:     } elsif ($award eq 'EXCESS_FILESIZE') {
 1012:         $message = &mt('Submission won\'t be graded. The combined size of submitted files exceeded the amount allowed.');
 1013:         $css_class=$possible_class{'not_charged_try'};
 1014:         $button=1;
 1015:     } elsif ($award eq 'FILENAME_INUSE') {
 1016:         $message = &mt('You have already uploaded a file with that filename.');
 1017:         if ($target eq 'tex') {
 1018:             $message.= "\\\\\n";
 1019:         } else {
 1020:             $message .= '<br />';
 1021:         }
 1022:         $message .= &mt('Please use a different file name.');
 1023:         $css_class=$possible_class{'not_charged_try'};
 1024:         $button=1;
 1025:     } elsif ($award eq 'INVALID_FILETYPE') {
 1026: 	$message = &mt("Submission won't be graded. The type of file submitted is not allowed.");
 1027: 	$css_class=$possible_class{'not_charged_try'};
 1028: 	$button=1;
 1029:     } elsif ($award eq 'SIG_FAIL') {
 1030: 	my ($used,$min,$max)=split(':',$awardmsg);
 1031: 	my $word = ($used < $min) ? 'more' : 'fewer';
 1032: 	$message = &mt("Submission not graded. Use $word digits.",$used);
 1033: 	$css_class=$possible_class{'not_charged_try'};
 1034: 	$button=1;
 1035:     } elsif ($award eq 'UNIT_INVALID_INSTRUCTOR') {
 1036: 	$message = &mt('Error in instructor specifed unit. This error has been reported to the instructor.', $awardmsg);
 1037: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
 1038: 	$css_class=$possible_class{'not_charged_try'};
 1039: 	$button=1;
 1040:     } elsif ($award eq 'UNIT_INVALID_STUDENT') {
 1041: 	$message = &mt('Unable to interpret units. Computer reads units as "[_1]".',&markup_unit($awardmsg,$target));
 1042: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
 1043: 	$css_class=$possible_class{'not_charged_try'};
 1044: 	$button=1;
 1045:     } elsif ($award eq 'UNIT_FAIL' || $award eq 'UNIT_IRRECONCIBLE') {
 1046: 	$message = &mt('Incompatible units. No conversion found between "[_1]" and the required units.',&markup_unit($awardmsg,$target));
 1047: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
 1048: 	$css_class=$possible_class{'not_charged_try'};
 1049: 	$button=1;
 1050:     } elsif ($award eq 'UNIT_NOTNEEDED') {
 1051: 	$message = &mt('Only a number required. Computer reads units of "[_1]".',&markup_unit($awardmsg,$target));
 1052: 	$css_class=$possible_class{'not_charged_try'};
 1053: 	$button=1;
 1054:     } elsif ($award eq 'NO_UNIT') {
 1055: 	$message = &mt("Units required").'.';
 1056: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units')};
 1057: 	$css_class=$possible_class{'not_charged_try'};
 1058: 	$button=1;
 1059:     } elsif ($award eq 'COMMA_FAIL') {
 1060: 	$message = &mt("Proper comma separation is required").'.';
 1061: 	$css_class=$possible_class{'not_charged_try'};
 1062: 	$button=1;
 1063:     } elsif ($award eq 'BAD_FORMULA') {
 1064: 	$message = &mt("Unable to understand formula").'.';
 1065:         if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Formula_Answers')};
 1066: 	$css_class=$possible_class{'not_charged_try'};
 1067: 	$button=1;
 1068:     } elsif ($award eq 'NOT_FUNCTION') {
 1069:         $message = &mt("Not a function").'.';
 1070:         $css_class=$possible_class{'not_charged_try'};
 1071:         $button=1;
 1072:     } elsif ($award eq 'WRONG_FORMAT') {
 1073:         $message = &mt("Wrong format").'.';
 1074:         $css_class=$possible_class{'not_charged_try'};
 1075:         $button=1;
 1076:      } elsif ($award eq 'INTERNAL_ERROR') {
 1077:         $message = &mt("An internal error occurred while processing your answer. Please try again later.");
 1078:         $css_class=$possible_class{'not_charged_try'};
 1079:         $button=1;
 1080:     } elsif ($award eq 'INCORRECT') {
 1081: 	$message = &mt("Incorrect").'.';
 1082: 	$css_class=$possible_class{'charged_try'};
 1083: 	$button=1;
 1084:     } elsif ($award eq 'SUBMITTED') {
 1085: 	$message = &mt("Your submission has been recorded.");
 1086: 	$css_class=$possible_class{'no_grade'};
 1087: 	$button=1;
 1088:     } elsif ($award eq 'SUBMITTED_CREDIT') {
 1089:         $message = &mt("Your submission has been recorded, and credit awarded.");
 1090:         $css_class=$possible_class{'correct'};
 1091:         $button=1;
 1092:     } elsif ($award eq 'ANONYMOUS') {
 1093:         $message = &mt("Your anonymous submission has been recorded.");
 1094:         $css_class=$possible_class{'no_grade'};
 1095:         $button=1;
 1096:     } elsif ($award eq 'ANONYMOUS_CREDIT') {
 1097:         $message = &mt("Your anonymous submission has been recorded, and credit awarded.");
 1098:         $css_class=$possible_class{'correct'};
 1099:     } elsif ($award eq 'DRAFT') {
 1100: 	$message = &mt("Copy saved but not submitted.");
 1101: 	$css_class=$possible_class{'not_charged_try'};
 1102: 	$button=1;
 1103:     } elsif ($award eq 'ASSIGNED_SCORE') {
 1104: 	$message = &mt("A score has been assigned.");
 1105: 	$css_class=$possible_class{'correct'};
 1106: 	$button=0;
 1107:     } elsif ($award eq '') {
 1108: 	if ($handgrade && $Apache::inputtags::status[-1] eq 'SHOW_ANSWER') {
 1109: 	    $message = &mt("Nothing submitted.");
 1110: 	    $css_class=$possible_class{'charged_try'};
 1111: 	} else {
 1112: 	    $css_class=$possible_class{'not_charged_try'};
 1113: 	}
 1114: 	$button=1;
 1115:     } else {
 1116: 	$message = &mt("Unknown message").": $award";
 1117: 	$button=1;
 1118:     }
 1119:     my (undef,undef,$domain,$user)=&Apache::lonnet::whichuser();
 1120:     foreach my $resid(@Apache::inputtags::response){
 1121:         if ($Apache::lonhomework::history{"resource.$part.$resid.handback"}) {
 1122:             if ($target eq 'tex') {
 1123:                 $message.= "\\\\\n";
 1124:             } else {
 1125:                 $message.='<br />';
 1126:             }
 1127: 	    my @files = split(/\s*,\s*/,
 1128: 			      $Apache::lonhomework::history{"resource.$part.$resid.handback"});
 1129: 	    my $file_msg;
 1130: 	    foreach my $file (@files) {
 1131:                 if ($target eq 'tex') {
 1132:                     $file_msg.= "\\\\\n".$file;
 1133:                 } else {
 1134:                     $file_msg.= '<br /><a href="/uploaded/'."$domain/$user".'/'.$file.'">'.$file.'</a>';
 1135:                 }
 1136: 	    }
 1137: 	    $message .= &mt('Returned file(s): [_1]',$file_msg);
 1138:             if ($target eq 'tex') {
 1139:                 $message.= "\\\\\n";
 1140:             } else {
 1141:                 $message.='<br />';
 1142:             }
 1143: 	}
 1144:     }
 1145: 
 1146:     if (&Apache::lonhomework::hide_problem_status()
 1147: 	&& $Apache::inputtags::status[-1] ne 'SHOW_ANSWER'
 1148: 	&& &hide_award($award)) {
 1149: 	$message = &mt("Answer Submitted: Your final submission will be graded after the due date.");
 1150: 	$css_class=$possible_class{'no_grade'};
 1151: 	$button=1;
 1152:     }
 1153:     if ($Apache::inputtags::status[-1] eq 'SHOW_ANSWER' && 
 1154: 	!$added_computer_text && $target ne 'tex') {
 1155: 	$message.= $computer;
 1156: 	$added_computer_text=1;
 1157:     }
 1158:     if ($Apache::lonhomework::type eq 'practice') {
 1159:        if ($target eq 'web') {
 1160:            $message .= '<br />';
 1161:        } else {
 1162:            $message .= ' ';      
 1163:        }
 1164:        $message.=&mt('Submissions to practice problems are not permanently recorded.');
 1165:     }
 1166:     return ($button,$css_class,$message,$previousmsg);
 1167: }
 1168: 
 1169: sub markup_unit {
 1170:     my ($unit,$target)=@_;
 1171:     if ($target eq 'tex') {
 1172: 	return '\texttt{'.&Apache::lonxml::latex_special_symbols($unit).'}'; 
 1173:     } else {
 1174: 	return "<tt>".$unit."</tt>";
 1175:     }
 1176: }
 1177: 
 1178: sub removealldata {
 1179:     my ($id)=@_;
 1180:     foreach my $key (keys(%Apache::lonhomework::results)) {
 1181: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
 1182: 	    &Apache::lonxml::debug("Removing $key");
 1183: 	    delete($Apache::lonhomework::results{$key});
 1184: 	}
 1185:     }
 1186: }
 1187: 
 1188: sub hidealldata {
 1189:     my ($id)=@_;
 1190:     foreach my $key (keys(%Apache::lonhomework::results)) {
 1191: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
 1192: 	    &Apache::lonxml::debug("Hidding $key");
 1193: 	    my $newkey=$key;
 1194: 	    $newkey=~s/^(resource\.\Q$id\E\.[^\.]+\.)(.*)$/${1}hidden${2}/;
 1195: 	    $Apache::lonhomework::results{$newkey}=
 1196: 		$Apache::lonhomework::results{$key};
 1197: 	    delete($Apache::lonhomework::results{$key});
 1198: 	}
 1199:     }
 1200: }
 1201: 
 1202: sub setgradedata {
 1203:     my ($award,$msg,$id,$previously_used) = @_;
 1204:     if ($Apache::lonhomework::scantronmode && 
 1205: 	&Apache::lonnet::validCODE($env{'form.CODE'})) {
 1206: 	$Apache::lonhomework::results{"resource.CODE"}=$env{'form.CODE'};
 1207:     } elsif ($Apache::lonhomework::scantronmode && 
 1208: 	     $env{'form.CODE'} eq '' &&
 1209: 	     $Apache::lonhomework::history{"resource.CODE"} ne '') {
 1210: 	$Apache::lonhomework::results{"resource.CODE"}='';
 1211:     }
 1212: 
 1213:     if (!$Apache::lonhomework::scantronmode &&
 1214: 	$Apache::inputtags::status['-1'] ne 'CAN_ANSWER' &&
 1215: 	$Apache::inputtags::status['-1'] ne 'CANNOT_ANSWER') {
 1216: 	$Apache::lonhomework::results{"resource.$id.afterduedate"}=$award;
 1217: 	return '';
 1218:     } elsif ( $Apache::lonhomework::history{"resource.$id.awarded"} < 1
 1219: 	      || $Apache::lonhomework::scantronmode 
 1220: 	      || &Apache::lonhomework::hide_problem_status()  ) {
 1221:         # the student doesn't already have it correct,
 1222: 	# or we are in a mode (scantron orno problem status) where a correct 
 1223:         # can become incorrect
 1224: 	# handle assignment of tries and solved status
 1225: 	my $solvemsg;
 1226: 	if ($Apache::lonhomework::scantronmode) {
 1227: 	    $solvemsg='correct_by_scantron';
 1228: 	} else {
 1229: 	    $solvemsg='correct_by_student';
 1230: 	}
 1231: 	if ($Apache::lonhomework::history{"resource.$id.afterduedate"}) {
 1232: 	    $Apache::lonhomework::results{"resource.$id.afterduedate"}='';
 1233: 	}
 1234: 	if ( $award eq 'ASSIGNED_SCORE') {
 1235: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1236: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1237: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1238: 		$solvemsg;
 1239: 	    my $numawards=scalar(@Apache::inputtags::response);
 1240: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1241: 	    foreach my $res (@Apache::inputtags::response) {
 1242: 		if (defined($Apache::lonhomework::results{"resource.$id.$res.awarded"})) {
 1243: 		    $Apache::lonhomework::results{"resource.$id.awarded"}+=
 1244: 			$Apache::lonhomework::results{"resource.$id.$res.awarded"};
 1245: 		} else {
 1246: 		    $Apache::lonhomework::results{"resource.$id.awarded"}+=
 1247: 			&awarddetail_to_awarded($Apache::lonhomework::results{"resource.$id.$res.awarddetail"});
 1248: 		}
 1249: 	    }
 1250: 	    if ($numawards > 0) {
 1251: 		$Apache::lonhomework::results{"resource.$id.awarded"}/=
 1252: 		    $numawards;
 1253: 	    }
 1254: 	} elsif ( $award eq 'APPROX_ANS' || $award eq 'EXACT_ANS' ) {
 1255: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1256: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1257: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1258: 		$solvemsg;
 1259: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
 1260:         } elsif ( $award eq 'SUBMITTED_CREDIT' ) {
 1261:             $Apache::lonhomework::results{"resource.$id.tries"} =
 1262:                 $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1263:             $Apache::lonhomework::results{"resource.$id.solved"} =
 1264:                 'credit_attempted';
 1265:             $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
 1266:         }  elsif ( $award eq 'ANONYMOUS_CREDIT' ) {
 1267:             $Apache::lonhomework::results{"resource.$id.tries"} =
 1268:                 $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1269:             $Apache::lonhomework::results{"resource.$id.solved"} =
 1270:                 'credit_attempted';
 1271:             $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
 1272: 	} elsif ( $award eq 'INCORRECT' ) {
 1273: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1274: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1275: 	    if (&Apache::lonhomework::hide_problem_status()
 1276: 		|| $Apache::lonhomework::scantronmode) {
 1277: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1278: 	    }
 1279: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1280: 		'incorrect_attempted';
 1281: 	} elsif ( $award eq 'SUBMITTED' ) {
 1282: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1283: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1284: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1285: 		'ungraded_attempted';
 1286:         }  elsif ( $award eq 'ANONYMOUS' ) {
 1287:             $Apache::lonhomework::results{"resource.$id.tries"} =
 1288:                 $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1289:             $Apache::lonhomework::results{"resource.$id.solved"} =
 1290:                 'ungraded_attempted';
 1291: 	} elsif ( $award eq 'DRAFT' ) {
 1292: 	    $Apache::lonhomework::results{"resource.$id.solved"} = '';
 1293: 	} elsif ( $award eq 'NO_RESPONSE' ) {
 1294: 	    #no real response so delete any data that got stored
 1295: 	    &removealldata($id);
 1296: 	    return '';
 1297: 	} else {
 1298: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1299: 		'incorrect_attempted';
 1300: 	    if (&Apache::lonhomework::show_no_problem_status()
 1301: 		|| $Apache::lonhomework::scantronmode) {
 1302: 		$Apache::lonhomework::results{"resource.$id.tries"} =
 1303: 		    $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1304: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1305: 	    }
 1306: 
 1307: 	    if (&Apache::lonhomework::show_some_problem_status()) {
 1308: 		# clear out the awarded if they had gotten it wrong/right
 1309: 		# and are now in an error mode	
 1310: 		$Apache::lonhomework::results{"resource.$id.awarded"} = '';
 1311: 	    }
 1312: 	}
 1313: 	if (defined($msg)) {
 1314: 	    $Apache::lonhomework::results{"resource.$id.awardmsg"} = $msg;
 1315: 	}
 1316: 	# did either of the overall awards chage? If so ignore the 
 1317: 	# previous check
 1318: 	if (($Apache::lonhomework::results{"resource.$id.awarded"} eq
 1319: 	     $Apache::lonhomework::history{"resource.$id.awarded"}) &&
 1320: 	    ($Apache::lonhomework::results{"resource.$id.solved"} eq
 1321: 	     $Apache::lonhomework::history{"resource.$id.solved"})) {
 1322: 	    # check if this was a previous submission if it was delete the
 1323: 	    # unneeded data and update the previously_used attribute
 1324: 	    if ( $previously_used eq 'PREVIOUSLY_USED') {
 1325: 		if (&Apache::lonhomework::show_problem_status()) {
 1326: 		    delete($Apache::lonhomework::results{"resource.$id.tries"});
 1327: 		    $Apache::lonhomework::results{"resource.$id.previous"} = '1';
 1328: 		}
 1329: 	    } elsif ( $previously_used eq 'PREVIOUSLY_LAST') {
 1330: 		#delete all data as they student didn't do anything, but save
 1331: 		#the list of collaborators.
 1332: 		&removealldata($id);
 1333: 		#and since they didn't do anything we were never here
 1334: 		return '';
 1335: 	    } else {
 1336: 		$Apache::lonhomework::results{"resource.$id.previous"} = '0';
 1337: 	    }
 1338: 	}
 1339:     } elsif ( $Apache::lonhomework::history{"resource.$id.awarded"} == 1 ) {
 1340: 	#delete all data as they student already has it correct
 1341: 	&removealldata($id);
 1342: 	#and since they didn't do anything we were never here
 1343: 	return '';
 1344:     }
 1345:     $Apache::lonhomework::results{"resource.$id.award"} = $award;
 1346:     if ($award eq 'SUBMITTED') {
 1347: 	&Apache::response::add_to_gradingqueue();
 1348:     }
 1349:     $Apache::lonhomework::results{"resource.$id.type"} = $Apache::lonhomework::type;
 1350:     $Apache::lonhomework::results{"resource.$id.duedate"} = &Apache::lonnet::EXT("resource.$id.duedate");
 1351:     $Apache::lonhomework::results{"resource.$id.hinttries"} = &Apache::lonnet::EXT("resource.$id.hinttries");
 1352:     $Apache::lonhomework::results{"resourse.$id.version"} = &Apache::lonnet::usedversion(); 
 1353: }
 1354: 
 1355: sub find_which_previous {
 1356:     my ($version) = @_;
 1357:     my $part = $Apache::inputtags::part;
 1358:     my (@previous_version);
 1359:     foreach my $resp (@Apache::inputtags::response) {
 1360: 	my $key = "$version:resource.$part.$resp.submission";
 1361: 	my $submission = $Apache::lonhomework::history{$key};
 1362: 	my %previous = &Apache::response::check_for_previous($submission,
 1363: 							     $part,$resp,
 1364: 							     $version);
 1365: 	push(@previous_version,$previous{'version'});
 1366:     }
 1367:     return &previous_match(\@previous_version,
 1368: 			   scalar(@Apache::inputtags::response));
 1369: }
 1370: 
 1371: sub previous_match {
 1372:     my ($previous_array,$count) = @_;
 1373:     my $match = 0;
 1374:     my @matches;
 1375:     foreach my $versionar (@$previous_array) {
 1376: 	foreach my $version (@$versionar) {
 1377: 	    $matches[$version]++;
 1378: 	}
 1379:     }
 1380:     my $which=0;
 1381:     foreach my $elem (@matches) {
 1382: 	if ($elem eq $count) {
 1383: 	    $match=1;
 1384: 	    last;
 1385: 	}
 1386: 	$which++;
 1387:     }
 1388:     return ($match,$which);
 1389: }
 1390: 
 1391: sub grade {
 1392:     my ($target) = @_;
 1393:     my $id = $Apache::inputtags::part;
 1394:     my $response='';
 1395:     if ( defined $env{'form.submitted'}) {
 1396: 	my (@awards,@msgs);
 1397: 	foreach $response (@Apache::inputtags::response) {
 1398: 	    &Apache::lonxml::debug("looking for response.$id.$response.awarddetail");
 1399: 	    my $value=$Apache::lonhomework::results{"resource.$id.$response.awarddetail"};
 1400: 	    &Apache::lonxml::debug("keeping $value from $response for $id");
 1401: 	    push (@awards,$value);
 1402: 	    $value=$Apache::lonhomework::results{"resource.$id.$response.awardmsg"};
 1403: 	    &Apache::lonxml::debug("got message $value from $response for $id");
 1404: 	    push (@msgs,$value);
 1405: 	}
 1406: 	my ($finalaward,$msg) = 
 1407: 	    &finalizeawards(\@awards,\@msgs,undef,undef,
 1408: 			    $Apache::lonhomework::scantronmode);
 1409: 	my $previously_used;
 1410: 	if ( $#Apache::inputtags::previous eq $#awards ) {
 1411: 	    my ($match) =
 1412: 		&previous_match(\@Apache::inputtags::previous_version,
 1413: 				scalar(@Apache::inputtags::response));
 1414: 
 1415: 	    if ($match) {
 1416: 		$previously_used = 'PREVIOUSLY_LAST';
 1417: 		foreach my $value (@Apache::inputtags::previous) {
 1418: 		    if ($value eq 'PREVIOUSLY_USED' ) {
 1419: 			$previously_used = $value;
 1420: 			last;
 1421: 		    }
 1422: 		}
 1423: 	    }
 1424: 	}
 1425: 	&Apache::lonxml::debug("final award $finalaward, $previously_used, message $msg");
 1426: 	&setgradedata($finalaward,$msg,$id,$previously_used);
 1427:     }
 1428:     return '';
 1429: }
 1430: 
 1431: sub get_grade_messages {
 1432:     my ($id,$prefix,$target,$status,$nocorrect) = @_;
 1433: # nocorrect suppresses "Computer's answer now shown above"
 1434:     my ($message,$latemessage,$trystr,$previousmsg);
 1435:     my $showbutton = 1;
 1436: 
 1437:     my $award = $Apache::lonhomework::history{"$prefix.award"};
 1438:     my $awarded = $Apache::lonhomework::history{"$prefix.awarded"};
 1439:     my $solved = $Apache::lonhomework::history{"$prefix.solved"};
 1440:     my $previous = $Apache::lonhomework::history{"$prefix.previous"};
 1441:     my $awardmsg = $Apache::lonhomework::history{"$prefix.awardmsg"};
 1442:     &Apache::lonxml::debug("Found Award |$award|$solved|$awardmsg");
 1443:     if ( $award ne '' || $solved ne '' || $status eq 'SHOW_ANSWER') {
 1444: 	&Apache::lonxml::debug('Getting message');
 1445: 	($showbutton,my $css_class,$message,$previousmsg) =
 1446: 	    &decideoutput($award,$awarded,$awardmsg,$solved,$previous,
 1447: 			  $target,(($status eq 'CAN_ANSWER') || $nocorrect));
 1448: 	if ($target eq 'tex') {
 1449: 	    $message='\vskip 2 mm '.$message.' ';
 1450: 	} else {
 1451: 	    $message="<td class=\"$css_class\">$message</td>";
 1452: 	    if ($previousmsg) {
 1453: 		$previousmsg="<td class=\"LC_answer_previous\">$previousmsg</td>";
 1454: 	    }
 1455: 	}
 1456:     }
 1457:     my $tries = $Apache::lonhomework::history{"$prefix.tries"};
 1458:     my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
 1459:     &Apache::lonxml::debug("got maxtries of :$maxtries:");
 1460:     #if tries are set to negative turn off the Tries/Button and messages
 1461:     if (defined($maxtries) && $maxtries < 0) { return ''; }
 1462:     if ( $tries eq '' ) { $tries = '0'; }
 1463:     if ( $maxtries eq '' ) { $maxtries = '2'; } 
 1464:     if ( $maxtries eq 'con_lost' ) { $maxtries = '0'; } 
 1465:     my $tries_text= &get_tries_text();
 1466:     if ($showbutton) {
 1467: 	if ($target eq 'tex') {
 1468: 	    if ($env{'request.state'} ne "construct"
 1469: 		&& $Apache::lonhomework::type ne 'exam'
 1470: 		&& $env{'form.suppress_tries'} ne 'yes') {
 1471: 		$trystr ='{\vskip 1 mm \small '
 1472:                         .&mt('[_1]'.$tries_text.'[_2] [_3]'
 1473: 				,'\textit{','}',$tries.'/'.$maxtries ) 
 1474:                         .'} \vskip 2 mm';
 1475: 	    } else {
 1476: 		$trystr = '\vskip 0 mm ';
 1477: 	    }
 1478: 	} else {
 1479: 	    my $trial =$tries;
 1480: 	    if ($Apache::lonhomework::parsing_a_task) {
 1481: 	    } elsif($env{'request.state'} ne 'construct') {
 1482: 		$trial.="/".&Apache::lonhtmlcommon::direct_parm_link($maxtries,$env{'request.symb'},'maxtries',$id,$target);
 1483: 	    } else {
 1484: 		if (defined($Apache::inputtags::params{'maxtries'})) {
 1485: 		    $trial.="/".$Apache::inputtags::params{'maxtries'};
 1486: 		}
 1487: 	    }
 1488: 	    $trystr = '<td><span class="LC_nobreak">'.&mt($tries_text.' [_1]',$trial).'</span></td>';
 1489: 	}
 1490:     }
 1491: 
 1492:     if ($Apache::lonhomework::history{"$prefix.afterduedate"}) {
 1493: 	#last submissions was after due date
 1494: 	$latemessage=&mt(' The last submission was after the Due Date ');;
 1495: 	if ($target eq 'web') {
 1496: 	    $latemessage='<td class="LC_answer_late">'.$latemessage.'</td>';
 1497: 	}
 1498:     }
 1499:     return ($previousmsg,$latemessage,$message,$trystr,$showbutton);
 1500: }
 1501: 
 1502: sub gradestatus {
 1503:     my ($id,$target,$no_previous) = @_;
 1504:     my $showbutton = 1;
 1505:     my $message = '';
 1506:     my $latemessage = '';
 1507:     my $trystr='';
 1508:     my $button='';
 1509:     my $previousmsg='';
 1510: 
 1511:     my $status = $Apache::inputtags::status['-1'];
 1512:     &Apache::lonxml::debug("gradestatus has :$status:");
 1513:     if ( $status ne 'CLOSED' 
 1514: 	 && $status ne 'UNAVAILABLE' 
 1515: 	 && $status ne 'INVALID_ACCESS' 
 1516: 	 && $status ne 'NEEDS_CHECKIN' 
 1517: 	 && $status ne 'NOT_IN_A_SLOT') {  
 1518: 
 1519: 	($previousmsg,$latemessage,$message,$trystr) =
 1520: 	    &get_grade_messages($id,"resource.$id",$target,$status,
 1521: 				$showbutton);
 1522: 	if ( $status eq 'SHOW_ANSWER' || $status eq 'CANNOT_ANSWER') {
 1523: 	    $showbutton = 0;
 1524: 	}
 1525: 	if ( $status eq 'SHOW_ANSWER') {
 1526: 	    undef($previousmsg);
 1527: 	}
 1528: 	if ( $showbutton ) { 
 1529: 	    if ($target ne 'tex') {
 1530: 		$button = 
 1531:             '<input onmouseup="javascript:setSubmittedPart(\''.$id.'\');this.form.action+=\'#'.&escape($id).'\';"
 1532:                     type="submit" name="submit_'.$id.'"
 1533:                     value="'.&mt('Submit Answer').'" />';
 1534: 	    }
 1535: 	}
 1536: 
 1537:     }
 1538:     my $output= $previousmsg.$latemessage.$message.$trystr;
 1539:     if ($output =~ /^\s*$/) {
 1540: 	return $button;
 1541:     } else {
 1542: 	if ($target eq 'tex') {
 1543: 	    return $button.' \vskip 0 mm '.$output.' ';
 1544: 	} else {
 1545: 	    $output =
 1546: 		'<table><tr><td>'.$button.'</td>'.$output;
 1547: 	    if (!$no_previous) {
 1548: 		$output.='<td>'.&previous_tries($id,$target).'</td>';
 1549: 	    }
 1550: 	    $output.= '</tr></table>';
 1551: 	    return $output;
 1552: 	}
 1553:     }
 1554: }
 1555: 
 1556: sub previous_tries {
 1557:     my ($id,$target) = @_;
 1558:     my $output;
 1559:     my $status = $Apache::inputtags::status['-1'];
 1560: 
 1561:     my $count;
 1562:     my %count_lookup;
 1563:     my $lastrndseed;
 1564: 
 1565:     foreach my $i (1..$Apache::lonhomework::history{'version'}) {
 1566: 	my $prefix = $i.":resource.$id";
 1567:         my $is_anon; 
 1568:         if (defined($env{'form.grade_symb'})) {
 1569:             if (($Apache::lonhomework::history{"$prefix.type"} eq 'anonsurvey') || 
 1570:                 ($Apache::lonhomework::history{"$prefix.type"} eq 'anonsurveycred')) {
 1571:                 $is_anon = 1;
 1572:             }
 1573:         }
 1574: 	next if (!exists($Apache::lonhomework::history{"$prefix.award"}));
 1575: 	$count++;
 1576: 	$count_lookup{$i} = $count;
 1577:         my $curr_rndseed = $Apache::lonhomework::history{"$prefix.rndseed"};
 1578: 	my ($previousmsg,$latemessage,$message,$trystr);
 1579: 
 1580: 	($previousmsg,$latemessage,$message,$trystr) =
 1581: 	    &get_grade_messages($id,"$prefix",$target,$status);
 1582: 
 1583: 	if ($previousmsg ne '') {
 1584: 	    my ($match,$which) = &find_which_previous($i);
 1585: 	    $message=$previousmsg;
 1586: 	    my $previous = $count_lookup{$which};
 1587: 	    $message =~ s{(</td>)}{ as submission \# $previous $1};
 1588: 	} elsif ($Apache::lonhomework::history{"$prefix.tries"}) {
 1589: 	    if (!(&Apache::lonhomework::hide_problem_status()
 1590: 		  && $Apache::inputtags::status[-1] ne 'SHOW_ANSWER')
 1591: 		&& $Apache::lonhomework::history{"$prefix.solved"} =~/^correct/
 1592: 		) {
 1593: 		
 1594:                 my $txt_correct = &mt('Correct');
 1595:                 my $awarded = $Apache::lonhomework::history{"$prefix.awarded"};
 1596:                 if ($awarded < 1 && $awarded > 0) {
 1597:                     $txt_correct=&mt('Partially Correct');
 1598:                 } elsif ($awarded < 1) {
 1599:                     if ($awarded eq '') {
 1600:                         $txt_correct='';
 1601:                     } else {
 1602:                         $txt_correct=&mt('Incorrect');
 1603:                     }
 1604:                 }
 1605: 		$message =~ s{(<td.*?>)(.*?)(</td>)}
 1606:                              {$1 <strong>$txt_correct</strong>. $3}s;
 1607: 	    }
 1608:             my $trystr = "(".&mt('Try [_1]',$Apache::lonhomework::history{"$prefix.tries"}).")";
 1609:             if (($curr_rndseed || $lastrndseed) && ($i > 1)) {
 1610:                 if ($curr_rndseed ne $lastrndseed) {
 1611:                     $trystr .= '<br /><span style="color: green; white-space: nowrap; font-style: italic; font-weight: bold; font-size: 80%;">'.&mt('New problem variation this try.').'</span>';
 1612:                 }
 1613:             } 
 1614: 	    $message =~ s{(</td>)}{ $trystr $1};
 1615: 	}
 1616: 	my ($class) = ($message =~ m{<td.*class="([^"]*)"}); #"
 1617: 	$message =~ s{(<td.*?>)}{<td>};
 1618: 	
 1619: 
 1620: 	$output.='<tr class="'.$class.'">';
 1621: 	$output.='<td align="center">'.$count.'</td>';
 1622: 	$output.=$message;
 1623: 
 1624: 	foreach my $resid (@Apache::inputtags::response) {
 1625: 	    my $prefix = $prefix.".$resid";
 1626: 	    if (exists($Apache::lonhomework::history{"$prefix.submission"})) {
 1627: 		my $submission =
 1628: 		    $Apache::inputtags::submission_display{"$prefix.submission"};
 1629: 		if (!defined($submission)) {
 1630: 		    $submission = 
 1631: 			$Apache::lonhomework::history{"$prefix.submission"};
 1632: 		}
 1633:                 if ($is_anon) {
 1634:                     $output.='<td>'.&mt('(only shown to submitter)').'</td>';
 1635:                 } else {
 1636: 		    $output.='<td>'.$submission.'</td>';
 1637:                 }
 1638: 	    } else {
 1639: 		$output.='<td></td>';
 1640: 	    }
 1641: 	}
 1642: 	$output.=&Apache::loncommon::end_data_table_row()."\n";
 1643:         $lastrndseed = $curr_rndseed;
 1644:     }
 1645:     return if ($output eq '');
 1646:     my $headers = 
 1647: 	'<tr>'.'<th>'.&mt('Submission #').'</th><th>'.&mt('Try').
 1648: 	'</th><th colspan="'.scalar(@Apache::inputtags::response).'">'.
 1649: 	&mt('Submitted Answer').'</th>';
 1650:     $output ='<table class="LC_prior_tries">'.$headers.$output.'</table>';
 1651:     #return $output;
 1652:     $output = &Apache::loncommon::js_ready($output); 
 1653:     $output.='<br /><form action=""><center><input type="button" name="close" value="'.&mt('Close Window').'" onClick="window.close()" /></center></form>';
 1654: 
 1655:     my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
 1656:     my $tries_text = &get_tries_text('link');
 1657:     my $start_page =
 1658: 	&Apache::loncommon::start_page($tries_text, undef,
 1659: 				       {'only_body'      => 1,
 1660: 					'bgcolor'        => '#FFFFFF',
 1661: 					'js_ready'       => 1,
 1662: 				        'inherit_jsmath' => 1, });
 1663:     my $end_page =
 1664: 	&Apache::loncommon::end_page({'js_ready' => 1,});
 1665:     my $prefix = $env{'form.request.prefix'};
 1666:     $prefix =~ tr{.}{_};
 1667:     my $function_name = "LONCAPA_previous_tries_".$prefix.
 1668: 	$Apache::lonxml::curdepth.'_'.$env{'form.counter'};
 1669:     my $result ="<script type=\"text/javascript\">
 1670: // <![CDATA[
 1671:     function $function_name() {newWindow=open('','new_W','width=500,height=500,scrollbars=1,resizable=yes');newWindow.$windowopen;newWindow.document.writeln('$start_page $output $end_page');newWindow.document.close();newWindow.focus()}
 1672: // ]]>
 1673: </script><a href=\"javascript:$function_name();void(0);\">".&mt($tries_text)."</a><br />";
 1674:     #use Data::Dumper;
 1675:     #&Apache::lonnet::logthis(&Dumper(\%Apache::inputtags::submission_display));
 1676:     return $result;
 1677: }
 1678: 
 1679: sub get_tries_text {
 1680:     my ($context) = @_;
 1681:     my $tries_text;
 1682:     if ($context eq 'link') {
 1683:         $tries_text = 'Previous Tries';
 1684:     } else {
 1685:         $tries_text = 'Tries';
 1686:     }
 1687:     if ( $Apache::lonhomework::type eq 'survey' ||
 1688:          $Apache::lonhomework::type eq 'surveycred' ||
 1689:          $Apache::lonhomework::type eq 'anonsurvey' ||
 1690:          $Apache::lonhomework::type eq 'anonsurveycred' ||
 1691:          $Apache::lonhomework::parsing_a_task) {
 1692:         if ($context eq 'link') {
 1693:             $tries_text = 'Previous Submissions';
 1694:         } else {
 1695:             $tries_text = 'Submissions';
 1696:         }
 1697:     }
 1698:     return $tries_text;
 1699: }
 1700: 
 1701: 1;
 1702: __END__
 1703: 
 1704: =pod
 1705: 
 1706: =back
 1707: 
 1708: =cut
 1709:  

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