File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.308: download - view: text, annotated - select for diffs
Mon Sep 10 09:50:57 2012 UTC (11 years, 8 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
bz838 - add spellchecking to <input type='text'> and <textarea>

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

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