File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.326: download - view: text, annotated - select for diffs
Mon Sep 15 17:45:35 2014 UTC (9 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bug 6740
Eliminate multiple submissions of same form. Work in progress.
- Pressing "Enter" key within a text input field submits form.
- When this occurs make textbox readonly, and submit button disabled.

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

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