File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.313: download - view: text, annotated - select for diffs
Fri Dec 28 16:12:07 2012 UTC (11 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Modify change in rev 1.309.
- Print textfields without error when print option is "Without Formfields".

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

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