File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.318: download - view: text, annotated - select for diffs
Fri Jun 7 20:31:50 2013 UTC (10 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 5685.
  Show timestamps in student's "Previous Tries" view unless award is
  'ASSIGNED_SCORE' (i.e., Bubblesheet grading) or submission resulted in
  not being charged a try.

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

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