File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.323: download - view: text, annotated - select for diffs
Mon Jan 13 15:29:10 2014 UTC (10 years, 4 months ago) by bisitz
Branches: MAIN
CVS tags: version_2_11_0_RC3, HEAD
Proper display of submitted answer in problem view (response types: external, essay)

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

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