File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.310: download - view: text, annotated - select for diffs
Mon Sep 24 10:34:19 2012 UTC (11 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Support internationalized spellchecking.

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

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