File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.312: download - view: text, annotated - select for diffs
Wed Dec 19 17:35:34 2012 UTC (11 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Punctuation.

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

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