File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.315: download - view: text, annotated - select for diffs
Thu Apr 11 14:59:40 2013 UTC (11 years, 1 month ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Consistent wording: "file name" vs. "filename"
Use "filename" since this is more commonly used.

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

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