File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.333.2.12.2.4: download - view: text, annotated - select for diffs
Mon Sep 11 12:09:06 2023 UTC (8 months ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.333.2.12: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.359

    1: # The LearningOnline Network with CAPA
    2: # input  definitons
    3: #
    4: # $Id: inputtags.pm,v 1.333.2.12.2.4 2023/09/11 12:09:06 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 $numrespclass;
  454: 		my $readonly=&Apache::lonxml::get_param('readonly',$parstack,
  455: 							$safeeval);
  456: 		if (lc($readonly) eq 'yes' 
  457: 		    || $Apache::inputtags::status[-1] eq 'CANNOT_ANSWER') {
  458: 		    $readonly=' readonly="readonly" ';
  459: 		} else {
  460: 		    $readonly='';
  461:                     if (($Apache::inputtags::status['-1'] eq 'CAN_ANSWER') &&
  462:                         ($tagstack->[-2] eq 'numericalresponse')) {
  463:                         $numrespclass = ' LC_numresponse_text';
  464:                     }
  465: 		}
  466: 		my $name = 'HWVAL_'.$id;
  467:                 my $itemid = 'HWVAL_'.$partid.'_'.$id;
  468:                 my $input_tag_id = $itemid.'_'.$input_id;
  469: 		if ($Apache::inputtags::status[-1] eq 'CANNOT_ANSWER') {
  470: 		    $name = "none";
  471: 		}
  472: 		$result.= '<input onkeydown="javascript:setSubmittedPart(\''.$partid.'\');"'
  473: 		     . ' onfocus="javascript:disableAutoComplete(\''.$input_tag_id.'\');"'
  474: 		     . ' type="text" '.$readonly.' name="'. $name . '"'
  475: 		     . ' id="' . $input_tag_id . '"'
  476: 		     . ' value="'.  $oldresponse.'"'
  477: 		     . ' class="LC_textline spellchecked'.$numrespclass.'" size="'.$size.'"'.$maxlength.' />';
  478: 
  479: 		$result .= &spellcheck_onblur($itemid, $spellcheck);
  480:                 if (($Apache::inputtags::status['-1'] eq 'CAN_ANSWER') &&
  481:                     (((($tagstack->[-2] eq 'formularesponse') || ($tagstack->[-2] eq 'mathresponse')) &&
  482:                       (&Apache::lonnet::EXT('resource.'.$partid.'_'.$id.'.turnoffeditor') ne 'yes')) ||
  483:                      (($tagstack->[-2] eq 'customresponse') &&
  484:                        (&Apache::lonnet::EXT('resource.'.$partid.'_'.$id.'.turnoffeditor') eq 'no')))) {
  485:                     $result.=&edit_mathresponse_button($input_tag_id);
  486:                 }
  487: 	    }
  488: 	    if ($Apache::lonhomework::type eq 'exam'
  489: 		&& &needs_exam_box($tagstack)) {
  490: 		$result.=&exam_box($target);
  491: 	    }
  492: 	} else {
  493: 	    #right or wrong don't show what was last typed in.
  494: 	    my $count = scalar(@Apache::inputtags::inputlist)-1;
  495: 	    $result='<b>'.$Apache::inputtags::answertxt{$id}[$count].'</b>';
  496: 	    #$result='';
  497: 	}
  498:     } elsif ($target eq 'edit') {
  499: 	$result=&Apache::edit::tag_start($target,$token);
  500: 	$result.=&Apache::edit::text_arg('Size:','size',$token,'5').
  501: 	    &Apache::edit::text_arg('Click-On Texts (comma sep):',
  502: 				    'addchars',$token,10);
  503:         $result.=&Apache::edit::select_arg('Readonly:','readonly',
  504: 					   ['no','yes'],$token);
  505:         my $spell_langs = &spelling_languages();
  506: 	$result.=&Apache::edit::select_arg('Spellcheck for:', 'spellcheck',
  507: 					   $spell_langs, $token);
  508: 	$result.=&Apache::edit::end_row();
  509: 	$result.=&Apache::edit::end_table();
  510:     } elsif ($target eq 'modified') {
  511: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  512: 						     $safeeval,'size',
  513: 						     'addchars','readonly', 'spellcheck');
  514: 	if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
  515:     } elsif ($target eq 'tex' 
  516: 	     && $Apache::lonhomework::type ne 'exam') {
  517: 	my $size = &Apache::lonxml::get_param('size',$parstack,$safeeval);
  518: 	if ($size != 0) {$size=$size*2; $size.=' mm';} else {$size='40 mm';}
  519: 	if ($env{'form.pdfFormFields'} eq 'yes'
  520:             && $Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  521:             my $fieldname = $env{'request.symb'}.
  522:                                  '&part_'. $Apache::inputtags::part.
  523:                                  '&textresponse'.
  524:                                  '&HWVAL_' . $Apache::inputtags::response['-1'];
  525:             $result='\textField{'.$fieldname.'}{'.$size.'}{12 bp}';
  526:         } else {
  527:             $result='\framebox['.$size.'][s]{\tiny\strut}';
  528:         }
  529:     } elsif ($target eq 'tex' 
  530: 	     && $Apache::lonhomework::type eq 'exam'
  531: 	     && &needs_exam_box($tagstack)) {
  532: 	$result.=&exam_box($target);
  533:     }
  534:     return $result;
  535: }
  536: 
  537: sub end_textline {
  538:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  539:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  540:     elsif ($target eq 'edit') { return ('','no'); }
  541:     &end_input();
  542:     return "";
  543: }
  544: 
  545: sub start_hiddenline {
  546:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  547:     my $result = "";
  548:     my $input_id = &start_input($parstack,$safeeval);
  549:     if ($target eq 'web') {
  550: 	$Apache::lonxml::evaluate--;
  551: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  552: 	    my $partid=$Apache::inputtags::part;
  553: 	    my $id=$Apache::inputtags::response[-1];
  554: 	    my $oldresponse = $Apache::lonhomework::history{"resource.$partid.$id.submission"};
  555: 	    if (ref($oldresponse) eq 'ARRAY') {
  556: 		$oldresponse = $oldresponse->[$#Apache::inputtags::inputlist];
  557: 	    }
  558: 	    $oldresponse = &HTML::Entities::encode($oldresponse,'<>&"');
  559: 
  560: 	    if ($Apache::lonhomework::type ne 'exam') {
  561: 		$result= '<input type="hidden" name="HWVAL_'.$id.'" value="'.
  562: 		    $oldresponse.'" />';
  563: 	    }
  564: 	}
  565:     } elsif ($target eq 'edit') {
  566: 	$result=&Apache::edit::tag_start($target,$token);
  567: 	$result.=&Apache::edit::end_table;
  568:     }
  569: 
  570:     if ( ($target eq 'web' || $target eq 'tex')
  571: 	 && $Apache::lonhomework::type eq 'exam'
  572: 	 && &needs_exam_box($tagstack)) {
  573: 	$result.=&exam_box($target);
  574:     }
  575:     return $result;
  576: }
  577: 
  578: sub end_hiddenline {
  579:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  580:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  581:     elsif ($target eq 'edit') { return ('','no'); }
  582:     &end_input();
  583:     return "";
  584: }
  585: 
  586: 
  587: sub start_hiddensubmission {
  588:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  589:     my $result = "";
  590:     my $input_id = &start_input($parstack,$safeeval);
  591:     if ($target eq 'web') {
  592:         $Apache::lonxml::evaluate--;
  593:         if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  594:             my $partid=$Apache::inputtags::part;
  595:             my $id=$Apache::inputtags::response[-1];
  596:             if ($Apache::lonhomework::type ne 'exam') {
  597:                 my $value = &Apache::lonxml::get_param('value',$parstack,$safeeval);
  598:                 $value = &HTML::Entities::encode($value,'<>&"');
  599:                 $result= '<input type="hidden" name="HWVAL_'.$id.'" value="'.$value.'" />';
  600:             }
  601:         }
  602:     } elsif ($target eq 'edit') {
  603:         $result=&Apache::edit::tag_start($target,$token);
  604:         $result.=&Apache::edit::text_arg('Value:','value',$token,'15');
  605:         $result.=&Apache::edit::end_row();
  606:         $result.=&Apache::edit::end_table();
  607:     } elsif ($target eq 'modified') {
  608:         my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  609:                                                      $safeeval,'value');
  610:         if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
  611:     }
  612: 
  613:     if ( ($target eq 'web' || $target eq 'tex')
  614:          && $Apache::lonhomework::type eq 'exam'
  615:          && &needs_exam_box($tagstack)) {
  616:         $result.=&exam_box($target);
  617:     }
  618:     return $result;
  619: }
  620: 
  621: sub end_hiddensubmission {
  622:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  623:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  624:     elsif ($target eq 'edit') { return ('','no'); }
  625:     &end_input();
  626:     return "";
  627: }
  628: 
  629: =pod
  630: 
  631: =item file_selector()
  632: 
  633: $part -> partid
  634: $id -> responseid
  635: $uploadefiletypes -> comma seperated list of extensions allowed or * for any
  636: $which -> 'uploadonly'  -> only newly uploaded files
  637:           'portfolioonly' -> only allow files from portfolio
  638:           'both' -> allow files from either location
  639: $extratext -> additional text to go between the link and the input box
  640: $maxfilesize -> maximum cumulative filesize for submitted files (in MB).
  641: returns a table row <tr> 
  642: 
  643: =cut
  644: 
  645: sub file_selector {
  646:     my ($part,$id,$uploadedfiletypes,$which,$extratext,$maxfilesize)=@_;
  647:     if (!$uploadedfiletypes) { return ''; }
  648: 
  649:     my $jspart=$part;
  650:     $jspart=~s/\./_/g;
  651: 
  652:     my $result;
  653:     my $current_files_display = &current_file_submissions($part,$id);
  654:     my $addfiles;
  655:     if ($current_files_display) {
  656:         $result .= &Apache::lonhtmlcommon::row_title(&mt('Currently submitted files')).
  657:                    $current_files_display.
  658:                    &Apache::lonhtmlcommon::row_closure();
  659:         $addfiles = &mt('Submit other file(s)');
  660:     } else {
  661:         $addfiles = &mt('Choose file(s) to submit');
  662:     }
  663:     $result .= &Apache::lonhtmlcommon::row_title($addfiles);
  664:     my $constraints;
  665:     if ($uploadedfiletypes ne '*') {
  666: 	$constraints =
  667: 	    &mt('Allowed filetypes: [_1]','<b>'.$uploadedfiletypes.'</b>').'<br />';
  668:     }
  669:     if ($maxfilesize) {
  670:         $constraints .= &mt('Combined size of all files not to exceed: [_1] MB.',
  671:                         '<b>'.$maxfilesize.'</b>').'<br />';
  672:     }
  673:     if ($constraints) {
  674:         $result .= $constraints.'<br />';
  675:     }
  676:     if ($which eq 'uploadonly' || $which eq 'both') {
  677:         my $free_space = $maxfilesize * 1048576;
  678:         $result .= &mt('Submit a file: (only one file per submission)').
  679:             ' <br /><input type="file" size="50" name="HWFILE'.$jspart.'_'.$id.
  680:             '" id="HWFILE'.$jspart.'_'.$id.'" class="LC_flUpload LC_hwkfile" />'.
  681:             '<input type="hidden" id="LC_free_space_'.$jspart.'_'.$id.'"'.
  682:             ' value="'.$free_space.'" /><br />';
  683:     }
  684:     if ( $which eq 'both') {
  685: 	$result.='<br />'.'<strong>'.&mt('OR:').'</strong><br />';
  686:     }
  687:     if ($which eq 'portfolioonly' || $which eq 'both') {
  688:         my $symb = $env{'request.symb'};
  689:         (undef,undef,my $res)=&Apache::lonnet::decode_symb($symb);
  690:         my $showsymb;
  691:         # If resource is a .task and URL is unencrypted, include symb in query string
  692:         # for url opened in portfolio file selection window. Can be used to override
  693:         # blocking of portfolio access resulting from an exam event in a different course. 
  694:         if ($res =~ /\.task$/i) {
  695:             my $encsymb = &Apache::lonenc::check_encrypt($symb);
  696:             if ($symb eq $encsymb) {
  697:                 $showsymb = $symb;
  698:             }
  699:         }
  700: 	$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"))'."'".'>'.
  701: 	    &mt('Select Portfolio Files: (one or more files per submission)').'</a><br />'.
  702: 	    '<input type="text" size="50" name="HWPORT'.$jspart.'_'.$id.'" value="" />'.
  703: 	    '<br />';
  704:     }
  705:     $result.=&Apache::lonhtmlcommon::row_closure(1);
  706:     return $result;
  707: }
  708: 
  709: sub current_file_submissions {
  710:     my ($part,$id) = @_;
  711:     my $jspart=$part;
  712:     $jspart=~s/\./_/g;
  713:     my $uploadedfile=$Apache::lonhomework::history{"resource.$part.$id.uploadedfile"};
  714:     my $portfiles=$Apache::lonhomework::history{"resource.$part.$id.portfiles"};
  715:     return if (($uploadedfile eq '') && ($portfiles !~/[^\s]/));
  716:     my $header = &portpath_popup_js().
  717:                  &Apache::loncommon::start_data_table().
  718:                  &Apache::loncommon::start_data_table_header_row();
  719:     if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  720:         $header .= '<th>'.&mt('Delete?').'</th>';
  721:     }
  722:     $header .=   '<th>'.&mt('File').'</th>'.
  723:                  '<th>'.&mt('Size (MB)').'</th>'.
  724:                  '<th>'.&mt('Last Modified').'</th>'.
  725:                  &Apache::loncommon::end_data_table_header_row();
  726:     my (undef,$crsid,$udom,$uname)=&Apache::lonnet::whichuser();
  727:     my ($cdom,$cnum) = ($crsid =~ /^($LONCAPA::match_domain)_($LONCAPA::match_courseid)$/);
  728:     my ($result,$header_shown,%okfiles,%rows,%legacy,@bad_file_list);
  729:     if ($uploadedfile) {
  730:         my $url=$Apache::lonhomework::history{"resource.$part.$id.uploadedurl"};
  731:         my $link = &HTML::Entities::encode($url,'<>&"');
  732:         my ($path,$name) = ($url =~ m{^(/uploaded/\Q$udom\E/\Q$uname\E/essayresponse.*/)([^/]+)$});
  733:         my ($status,$hashref,$error) =
  734:             &current_file_info($url,$link,$name,$path);
  735:         if ($status eq 'ok') {
  736:             push(@{$okfiles{$name}},$url);
  737:             $rows{$url} = $hashref;
  738:             $legacy{$url} = 1;
  739:             &Apache::lonxml::extlink($url);
  740:             &Apache::lonnet::allowuploaded('/adm/essayresponse',$url);
  741:         } else {
  742:             push(@bad_file_list,$error);
  743:         }
  744:     }
  745:     if ($portfiles =~ /[^\s]/) {
  746:         my $prefix = "/uploaded/$udom/$uname/portfolio";
  747:         foreach my $file (split(/\s*,\s*/,&unescape($portfiles))) {
  748:             my ($path,$name) = ($file =~ m{^(.*/)([^/]+)$});
  749:             my $url = $prefix.$path.$name;
  750:             my $uploadedfile = &HTML::Entities::encode($url,'<>&"');
  751:             my ($status,$hashref,$error) =
  752:                 &current_file_info($url,$uploadedfile,$name,$path);
  753:             if ($status eq 'ok') {
  754:                 push(@{$okfiles{$name}},$url);
  755:                 $rows{$url} = $hashref;
  756:             } else {
  757:                 push(@bad_file_list,$error);
  758:             }
  759:         }
  760:     }
  761:     my $num = 0;
  762:     foreach my $name (sort(keys(%okfiles))) {
  763:         if (ref($okfiles{$name}) eq 'ARRAY') {
  764:             foreach my $url (@{$okfiles{$name}}) {
  765:                 if (ref($rows{$url}) eq 'HASH') {
  766:                     my $link = $rows{$url}{link};
  767:                     my $portfile = $rows{$url}{path}.$rows{$url}{name};
  768:                     $portfile = &HTML::Entities::encode($portfile,'<>&"');
  769:                     if ($link) {
  770:                         my $icon=&Apache::loncommon::icon($url);
  771:                         unless ($header_shown) {
  772:                             $result .= $header;
  773:                             $header_shown = 1;
  774:                         }
  775:                         $result.=
  776:                             &Apache::loncommon::start_data_table_row()."\n";
  777:                         if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  778:                             $result .=
  779:                                  '<td valign="bottom"><input type="checkbox" name="HWFILE'.$jspart.'_'.$id.'_delete"'.
  780:                                  ' value="'.$portfile.'" id="HWFILE'.$jspart.'_'.$id.'_'.$num.'_delete" /></td>'."\n";
  781:                             $num ++;
  782:                         }
  783:                         my $pathid = 'HWFILE'.$jspart.'_'.$id.'_'.$num.'_path';
  784:                         my $pathidtext = $pathid.'text';
  785:                         my ($showname,$showpath);
  786:                         if ($legacy{$url}) {
  787:                             $showname = $name.' '.&mt('not in portfolio');
  788:                         } else {
  789:                             $showname = $name;
  790:                             $showpath = '<br />'. 
  791:                                         '<span id="'.$pathidtext.'" class="LC_cusr_subheading">'.
  792:                                         '<a href="javascript:showPortPath('."'$pathid','$pathidtext'".');" '.
  793:                                         'class="LC_menubuttons_link">'.
  794:                                         &mt('(Show path)').'</a></span>'.
  795:                                         '<div id="'.$pathid.'" class="LC_dccid">'.$rows{$url}{path}.$name.
  796: '</div>';
  797:                         }
  798:                         $result .= 
  799:                             '<td><a href="'.$link.'"><img src="'.$icon.
  800:                             '" border="0" alt="" />'.$showname.'</a>'.$showpath.'</td>'."\n".
  801:                             '<td align="right" valign="bottom">'.$rows{$url}{size}.'</td>'."\n".
  802:                             '<td align="right" valign="bottom">'.$rows{$url}{lastmodified}.'</td>'."\n".
  803:                             &Apache::loncommon::end_data_table_row();
  804:                     }
  805:                 }
  806:             }
  807:         }
  808:     }
  809:     if ($header_shown) {
  810:         $result .= &Apache::loncommon::end_data_table();
  811:         if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  812:             $result .= '<br /><span class="LC_warning">'.
  813:                        &mt('Exclude existing file(s) from grading by checking the "Delete?" checkbox(es) and clicking "Submit Answer"').'</span>';
  814:         }
  815:     }
  816:     if (@bad_file_list) {
  817:         my $bad_files = '<span class="LC_filename">'.
  818:             join('</span>, <span class="LC_filename">',@bad_file_list).
  819:             '</span>';
  820:         $result.='<p class="LC_error">'.
  821:                  &mt("These file(s) don't exist: [_1]",$bad_files).
  822:                  '</p>';
  823:     }
  824:     return $result;
  825: }
  826: 
  827: sub current_file_info {
  828:     my ($url,$uploadedfile,$name,$path) = @_;
  829:     my ($status,$error,%info);
  830:     my @stat = &Apache::lonnet::stat_file($url);
  831:     if ((@stat) && ($stat[0] ne 'no_such_dir')) {
  832:         my ($lastmod,$size);
  833:         if ($stat[9] =~ /^\d+$/) {
  834:             $lastmod = &Apache::lonlocal::locallocaltime($stat[9]);
  835:         }
  836:         $size = $stat[7]/(1024*1024);
  837:         $size = sprintf("%.3f",$size);
  838:         %info = (
  839:                     link         => $uploadedfile,
  840:                     name         => $name,
  841:                     path         => $path,
  842:                     size         => $size,
  843:                     lastmodified => $lastmod,
  844:                 );
  845:         $status = 'ok';
  846:     } else {
  847:         &Apache::lonnet::logthis("bad file is $url");
  848:         my $icon=&Apache::loncommon::icon($url);
  849:         $error = '<a href="'.$url.'"><img src="'.$icon.
  850:                  '" border="0" />'.$uploadedfile.'</a>';
  851:     }
  852:     return ($status,\%info,$error);
  853: }
  854: 
  855: sub portpath_popup_js {
  856:     my %lt = &Apache::lonlocal::texthash(
  857:                                           show => '(Show path)',
  858:                                           hide => '(Hide)',
  859:                                         );
  860:     return <<"END";
  861: <script type="text/javascript"> 
  862: // <![CDATA[
  863: 
  864: function showPortPath(id,idtext) {
  865:     document.getElementById(id).style.display='block';
  866:     document.getElementById(id).style.textAlign='left';
  867:     document.getElementById(id).style.textFace='normal';
  868:     if (document.getElementById(idtext)) {
  869:         document.getElementById(idtext).innerHTML ='<a href="javascript:hidePortPath(\\''+id+'\\',\\''+idtext+'\\'); '+
  870:                                                    '"class="LC_menubuttons_link">$lt{'hide'}</a>&nbsp;';
  871:     }
  872:     return;
  873: }
  874: 
  875: function hidePortPath(id,idtext) {
  876:     if (document.getElementById(id)) {
  877:         document.getElementById(id).style.display='none';
  878:     }
  879:     if (document.getElementById(idtext)) {
  880:         document.getElementById(idtext).innerHTML ='<a href="javascript:showPortPath(\\''+id+'\\',\\''+idtext+'\\');" '+
  881:                                                    'class="LC_menubuttons_link">$lt{'show'}</a>';
  882:     }
  883:     return;
  884: }
  885: 
  886: // ]]>
  887: </script>
  888: 
  889: END
  890: }
  891: 
  892: sub valid_award {
  893:     my ($award) =@_;
  894:     foreach my $possibleaward ('EXTRA_ANSWER','MISSING_ANSWER', 'ERROR',
  895: 			       'NO_RESPONSE','WRONG_NUMBOXESCHECKED',
  896: 			       'TOO_LONG', 'UNIT_INVALID_INSTRUCTOR',
  897: 			       'UNIT_INVALID_STUDENT', 'UNIT_IRRECONCIBLE',
  898: 			       'UNIT_FAIL', 'NO_UNIT',
  899: 			       'UNIT_NOTNEEDED', 'WANTED_NUMERIC',
  900: 			       'BAD_FORMULA', 'NOT_FUNCTION', 'WRONG_FORMAT', 
  901:                                'INTERNAL_ERROR', 'SIG_FAIL', 'INCORRECT', 
  902: 			       'MISORDERED_RANK', 'INVALID_FILETYPE',
  903:                                'EXCESS_FILESIZE', 'FILENAME_INUSE', 
  904: 			       'DRAFT', 'SUBMITTED', 'SUBMITTED_CREDIT', 
  905:                                'ANONYMOUS', 'ANONYMOUS_CREDIT',
  906:                                'ASSIGNED_SCORE', 'APPROX_ANS',
  907: 			       'EXACT_ANS','COMMA_FAIL') {
  908: 	if ($award eq $possibleaward) { return 1; }
  909:     }
  910:     return 0;
  911: }
  912: 
  913: {
  914:     my @awards = ('EXTRA_ANSWER', 'MISSING_ANSWER', 'ERROR', 'NO_RESPONSE',
  915: 		  'WRONG_NUMBOXESCHECKED','TOO_LONG',
  916: 		  'UNIT_INVALID_INSTRUCTOR', 'UNIT_INVALID_STUDENT',
  917: 		  'UNIT_IRRECONCIBLE', 'UNIT_FAIL', 'NO_UNIT',
  918: 		  'UNIT_NOTNEEDED', 'WANTED_NUMERIC', 'BAD_FORMULA',  'NOT_FUNCTION', 
  919:                   'WRONG_FORMAT', 'INTERNAL_ERROR',
  920: 		  'COMMA_FAIL', 'SIG_FAIL', 'INCORRECT', 'MISORDERED_RANK',
  921: 		  'INVALID_FILETYPE', 'EXCESS_FILESIZE', 'FILENAME_INUSE', 
  922:                   'DRAFT', 'SUBMITTED',
  923:                   'SUBMITTED_CREDIT', 'ANONYMOUS', 'ANONYMOUS_CREDIT',
  924:                   'ASSIGNED_SCORE', 'APPROX_ANS', 'EXACT_ANS');
  925:     my $i=0;
  926:     my %fwd_awards = map { ($_,$i++) } @awards;
  927:     my $max=scalar(@awards);
  928:     @awards=reverse(@awards);
  929:     $i=0;
  930:     my %rev_awards = map { ($_,$i++) } @awards;
  931: 
  932: sub awarddetail_to_awarded {
  933:     my ($awarddetail) = @_;
  934:     if ($awarddetail eq 'EXACT_ANS'
  935: 	|| $awarddetail eq 'APPROX_ANS') {
  936: 	return 1;
  937:     }
  938:     return 0;
  939: }
  940: 
  941: sub hide_award {
  942:     my ($award) = @_;
  943:     if (&Apache::lonhomework::show_no_problem_status()) {
  944: 	return 1;
  945:     }
  946:     if ($award =~
  947: 	/^(?:EXACT_ANS|APPROX_ANS|SUBMITTED|SUBMITTED_CREDIT|ANONYMOUS|ANONYMOUS_CREDIT|ASSIGNED_SCORE|INCORRECT)/) {
  948: 	return 1;
  949:     }
  950:     return 0;
  951: }
  952: 
  953: sub finalizeawards {
  954:     my ($awardref,$msgref,$nameref,$reverse,$final_scantron)=@_;
  955:     my $result;
  956:     if ($#$awardref == -1) { $result = "NO_RESPONSE"; }
  957:     if ($result eq '' ) {
  958: 	my $blankcount;
  959: 	foreach my $award (@$awardref) {
  960: 	    if ($award eq '') {
  961: 		$result='MISSING_ANSWER';
  962: 		$blankcount++;
  963: 	    }
  964: 	}
  965: 	if ($blankcount == ($#$awardref + 1)) {
  966: 	    return ('NO_RESPONSE');
  967: 	}
  968:     }
  969: 
  970:     if ($Apache::lonxml::internal_error) { $result='INTERNAL_ERROR'; }
  971: 
  972:     if (!$final_scantron && defined($result)) { return ($result); }
  973: 
  974:     # if in scantron mode, if the award for any response is 
  975:     # assigned score, then the part gets an assigned score
  976:     if ($final_scantron 
  977: 	&& grep {$_ eq 'ASSIGNED_SCORE'} (@$awardref)) {
  978: 	return ('ASSIGNED_SCORE');
  979:     }
  980: 
  981:     # if in scantron mode, if the award for any response is 
  982:     # correct and there are non-correct responses,
  983:     # then the part gets an assigned score
  984:     if ($final_scantron 
  985: 	&& (grep { $_ eq 'EXACT_ANS' ||
  986: 		   $_ eq 'APPROX_ANS'  } (@$awardref))
  987: 	&& (grep { $_ ne 'EXACT_ANS' &&
  988: 		   $_ ne 'APPROX_ANS'  } (@$awardref))) {
  989: 	return ('ASSIGNED_SCORE');
  990:     }
  991:     # these awards are ordered from most important error through best correct
  992:     my $awards = (!$reverse) ? \%fwd_awards : \%rev_awards ;
  993: 
  994:     my $best = $max;
  995:     my $j=0;
  996:     my $which;
  997:     foreach my $award (@$awardref) {
  998: 	if ($awards->{$award} < $best) {
  999: 	    $best  = $awards->{$award};
 1000: 	    $which = $j;
 1001: 	}
 1002: 	$j++;
 1003:     }
 1004: 
 1005:     # if at least one response item is set to include lenient grading
 1006:     # and that item is partially correct then overall award reflects
 1007:     # that, unless an award for one of the other response items does
 1008:     # not fall within the basic awards for correct or incorrect.
 1009:     if ($Apache::inputtags::leniency) {
 1010:         if (($$awardref[$which] eq 'INCORRECT')
 1011:             && (grep { $_ eq 'EXACT_ANS' ||
 1012:                        $_ eq 'APPROX_ANS' ||
 1013:                        $_ eq 'ASSIGNED_SCORE' } (@$awardref))
 1014:             && !((grep { $_ ne 'INCORRECT' &&
 1015:                          $_ ne 'EXACT_ANS' &&
 1016:                          $_ ne 'APPROX_ANS' &&
 1017:                          $_ ne 'ASSIGNED_SCORE' } (@$awardref)))) {
 1018:             return ('ASSIGNED_SCORE');
 1019:         }
 1020:     }
 1021: 
 1022:     if (defined($which)) {
 1023: 	if (ref($nameref)) {
 1024: 	    return ($$awardref[$which],$$msgref[$which],$$nameref[$which]);
 1025: 	} else {
 1026: 	    return ($$awardref[$which],$$msgref[$which]);
 1027: 	}
 1028:     }
 1029:     return ('ERROR',undef);
 1030: }
 1031: }
 1032: 
 1033: sub decideoutput {
 1034:     my ($award,$awarded,$awardmsg,$solved,$previous,$target,$nocorrect,$tdclass)=@_;
 1035: 
 1036:     my $message='';
 1037:     my $button=0;
 1038:     my $previousmsg;
 1039:     my $css_class='orange';
 1040:     my $added_computer_text=0;
 1041:     my %possible_class =
 1042: 	( 'correct'         => 'LC_answer_correct',
 1043: 	  'charged_try'     => 'LC_answer_charged_try',
 1044: 	  'not_charged_try' => 'LC_answer_not_charged_try',
 1045: 	  'no_grade'        => 'LC_answer_no_grade',
 1046: 	  'no_message'      => 'LC_no_message',
 1047:           'no_charge_warn'  => 'LC_answer_warning',
 1048: 	  );
 1049: 
 1050:     my $part = $Apache::inputtags::part;
 1051:     my $tohandgrade = &Apache::lonnet::EXT("resource.$part.handgrade");
 1052:     my $handgrade = ('yes' eq lc($tohandgrade)); 
 1053: #
 1054: # Should "Computer's Answer" be displayed?
 1055: # Should not be displayed if still answerable,
 1056: # if the problem is handgraded,
 1057: # or if the problem does not give a correct answer
 1058: #
 1059:     
 1060:     my $computer = ($handgrade || $nocorrect)? ''
 1061: 	                       : &mt("Computer's answer now shown above.");
 1062:     &Apache::lonxml::debug("handgrade has :$handgrade:");
 1063: 
 1064:     if ($previous) { $previousmsg=&mt('You have entered that answer before'); }
 1065:     
 1066:     if ($solved =~ /^correct/) {
 1067:         $css_class=$possible_class{'correct'};
 1068: 	$message=&mt('You are correct.');
 1069: 	if ($awarded < 1 && $awarded > 0) {
 1070: 	    $message=&mt('You are partially correct.');
 1071: 	    $css_class=$possible_class{'not_charged_try'};
 1072: 	} elsif ($awarded < 1) {
 1073: 	    $message=&mt('Incorrect.');
 1074: 	    $css_class=$possible_class{'charged_try'};
 1075: 	}
 1076: 	if ($handgrade || 
 1077:             ($env{'request.filename'}=~/\/res\/lib\/templates\/(examupload|DropBox).problem$/)) {
 1078: 	    $message = &mt("A score has been assigned.");
 1079: 	    $added_computer_text=1;
 1080: 	} else {
 1081: 	    if ($target eq 'tex') {
 1082: 		$message = '\textbf{'.$message.'}';
 1083: 	    } else {
 1084: 		$message = "<b>".$message."</b>";
 1085:                 if ($computer) {
 1086:                     $message = "$computer $message";
 1087:                 }
 1088: 	    }
 1089: 	    $added_computer_text=1;
 1090: 	    if ($awarded > 0) {
 1091: 		my ($symb) = &Apache::lonnet::whichuser();
 1092: 		if (($symb ne '') 
 1093: 		    &&
 1094: 		    ($env{'course.'.$env{'request.course.id'}.
 1095: 			      '.disable_receipt_display'} ne 'yes') &&
 1096:                     ($Apache::lonhomework::type ne 'practice')) { 
 1097: 		    $message.=(($target eq 'web')?'<br />':' ').
 1098: 			&mt('Your receipt no. is [_1]',
 1099: 			    (&Apache::lonnet::receipt($Apache::inputtags::part).
 1100: 			     (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'')));
 1101: 		}
 1102: 	    }
 1103: 	}
 1104:         if ($awarded >= 1) {
 1105:             $button=0;
 1106:         } elsif (&Apache::lonnet::EXT("resource.$part.retrypartial") !~/^1|on|yes$/i) {
 1107:             $button=0;
 1108:         } else {
 1109:             $button=1;
 1110:         }
 1111: 	$previousmsg='';
 1112:     } elsif ($solved =~ /^excused/) {
 1113: 	if ($target eq 'tex') {
 1114: 	    $message = ' \textbf{'.&mt('You are excused from the problem.').'} ';
 1115: 	} else {
 1116: 	    $message = "<b>".&mt('You are excused from the problem.')."</b>";
 1117: 	}
 1118: 	$css_class=$possible_class{'charged_try'};
 1119: 	$button=0;
 1120: 	$previousmsg='';
 1121:     } elsif ($award eq 'EXACT_ANS' || $award eq 'APPROX_ANS' ) {
 1122: 	if ($solved =~ /^incorrect/ || $solved eq '') {
 1123: 	    $message = &mt("Incorrect").".";
 1124: 	    $css_class=$possible_class{'charged_try'};
 1125: 	    $button=1;
 1126: 	} else {
 1127: 	    if ($target eq 'tex') {
 1128: 		$message = '\textbf{'.&mt('You are correct.').'}';
 1129: 	    } else {
 1130: 		$message = "<b>".&mt('You are correct.')."</b>";
 1131:                 if ($computer) {
 1132:                     $message = "$computer $message";
 1133:                 }
 1134: 	    }
 1135: 	    $added_computer_text=1;
 1136: 	    if  ($awarded > 0 
 1137: 		 && $env{'course.'.
 1138: 			     $env{'request.course.id'}.
 1139: 			     '.disable_receipt_display'} ne 'yes') { 
 1140: 		$message.=(($target eq 'web')?'<br />':' ').
 1141: 		    &mt('Your receipt is [_1]',
 1142: 			(&Apache::lonnet::receipt($Apache::inputtags::part).
 1143: 			 (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'')));
 1144: 	    }
 1145: 	    $css_class=$possible_class{'correct'};
 1146: 	    $button=0;
 1147: 	    $previousmsg='';
 1148: 	}
 1149:     } elsif ($award eq 'NO_RESPONSE') {
 1150: 	$message = '';
 1151: 	$css_class=$possible_class{'no_feedback'};
 1152: 	$button=1;
 1153:     } elsif ($award eq 'EXTRA_ANSWER') {
 1154: 	$message = &mt('Some extra items were submitted.');
 1155: 	$css_class=$possible_class{'not_charged_try'};
 1156: 	$button = 1;
 1157:     } elsif ($award eq 'MISSING_ANSWER') {
 1158: 	$message = &mt('Some items were not submitted.');
 1159:         if ($target ne 'tex') {
 1160:            $message .= &Apache::loncommon::help_open_topic('Some_Items_Were_Not_Submitted');
 1161:         }
 1162:         if (&Apache::lonhomework::show_some_problem_status()) {
 1163:             $css_class=$possible_class{'no_charge_warn'};
 1164:         } else {
 1165:             $css_class=$possible_class{'not_charged_try'};
 1166:         }
 1167: 	$button = 1;
 1168:     } elsif ($award eq 'WRONG_NUMBOXESCHECKED') {
 1169:         $message = &mt('Number of boxes checked outside permissible range (either too few or too many).');
 1170:         if ($target ne 'tex') {
 1171:            $message .= &Apache::loncommon::help_open_topic('Wrong_Num_Boxes_Checked');
 1172:         }
 1173:         $css_class=$possible_class{'not_charged_try'};
 1174:         $button = 1;
 1175:     } elsif ($award eq 'ERROR') {
 1176: 	$message = &mt('An error occurred while grading your answer.');
 1177: 	$css_class=$possible_class{'not_charged_try'};
 1178: 	$button = 1;
 1179:     } elsif ($award eq 'TOO_LONG') {
 1180: 	$message = &mt("The submitted answer was too long.");
 1181: 	$css_class=$possible_class{'not_charged_try'};
 1182: 	$button=1;
 1183:     } elsif ($award eq 'WANTED_NUMERIC') {
 1184: 	$message = &mt("This question expects a numeric answer.");
 1185: 	$css_class=$possible_class{'not_charged_try'};
 1186: 	$button=1;
 1187:     } elsif ($award eq 'MISORDERED_RANK') {
 1188:         $message = &mt('You have provided an invalid ranking.');
 1189:         if ($target ne 'tex') {
 1190:             $message.=' '.&mt('Please refer to [_1]',&Apache::loncommon::help_open_topic('Ranking_Problems',&mt('help on ranking problems')));
 1191:         }
 1192: 	$css_class=$possible_class{'not_charged_try'};
 1193: 	$button=1;
 1194:     } elsif ($award eq 'EXCESS_FILESIZE') {
 1195:         $message = &mt("Submission won't be graded. The combined size of submitted files exceeded the amount allowed.");
 1196:         $css_class=$possible_class{'not_charged_try'};
 1197:         $button=1;
 1198:     } elsif ($award eq 'FILENAME_INUSE') {
 1199:         $message = &mt('You have already uploaded a file with that filename.');
 1200:         if ($target eq 'tex') {
 1201:             $message.= "\\\\\n";
 1202:         } else {
 1203:             $message .= '<br />';
 1204:         }
 1205:         $message .= &mt('Please use a different filename.');
 1206:         $css_class=$possible_class{'not_charged_try'};
 1207:         $button=1;
 1208:     } elsif ($award eq 'INVALID_FILETYPE') {
 1209: 	$message = &mt("Submission won't be graded. The type of file submitted is not allowed.");
 1210: 	$css_class=$possible_class{'not_charged_try'};
 1211: 	$button=1;
 1212:     } elsif ($award eq 'SIG_FAIL') {
 1213: 	my ($used,$min,$max)=split(':',$awardmsg);
 1214: 	my $word = ($used < $min) ? 'more' : 'fewer';
 1215: 	$message = &mt("Submission not graded. Use $word significant figures.");
 1216:         if (&Apache::lonhomework::show_some_problem_status()) {
 1217:             $css_class=$possible_class{'no_charge_warn'};
 1218:         } else {
 1219:             $css_class=$possible_class{'not_charged_try'};
 1220:         }
 1221: 	$button=1;
 1222:     } elsif ($award eq 'UNIT_INVALID_INSTRUCTOR') {
 1223: 	$message = &mt('Error in instructor specifed unit. This error has been reported to the instructor.', $awardmsg);
 1224: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
 1225: 	$css_class=$possible_class{'not_charged_try'};
 1226: 	$button=1;
 1227:     } elsif ($award eq 'UNIT_INVALID_STUDENT') {
 1228: 	$message = &mt('Unable to interpret units. Computer reads units as "[_1]".',&markup_unit($awardmsg,$target));
 1229: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
 1230:         if (&Apache::lonhomework::show_some_problem_status()) {
 1231:             $css_class=$possible_class{'no_charge_warn'};
 1232:         } else {
 1233:             $css_class=$possible_class{'not_charged_try'};
 1234:         }
 1235: 	$button=1;
 1236:     } elsif ($award eq 'UNIT_FAIL' || $award eq 'UNIT_IRRECONCIBLE') {
 1237: 	$message = &mt('Incompatible units. No conversion found between "[_1]" and the required units.',&markup_unit($awardmsg,$target));
 1238: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
 1239:         if (&Apache::lonhomework::show_some_problem_status()) {
 1240:             $css_class=$possible_class{'no_charge_warn'};
 1241:         } else {
 1242:             $css_class=$possible_class{'not_charged_try'};
 1243:         }
 1244: 	$button=1;
 1245:     } elsif ($award eq 'UNIT_NOTNEEDED') {
 1246: 	$message = &mt('Only a number required. Computer reads units of "[_1]".',&markup_unit($awardmsg,$target));
 1247:         if (&Apache::lonhomework::show_some_problem_status()) {
 1248:             $css_class=$possible_class{'no_charge_warn'};
 1249:         } else {
 1250:             $css_class=$possible_class{'not_charged_try'};
 1251:         }
 1252: 	$button=1;
 1253:     } elsif ($award eq 'NO_UNIT') {
 1254: 	$message = &mt("Units required").'.';
 1255: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units')};
 1256:         if (&Apache::lonhomework::show_some_problem_status()) {
 1257:             $css_class=$possible_class{'no_charge_warn'};
 1258:         } else {
 1259:             $css_class=$possible_class{'not_charged_try'};
 1260:         }
 1261: 	$button=1;
 1262:     } elsif ($award eq 'COMMA_FAIL') {
 1263: 	$message = &mt("Proper comma separation is required").'.';
 1264: 	$css_class=$possible_class{'not_charged_try'};
 1265: 	$button=1;
 1266:     } elsif ($award eq 'BAD_FORMULA') {
 1267: 	$message = &mt("Unable to understand formula").'.';
 1268:         if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Formula_Answers')};
 1269: 	$css_class=$possible_class{'not_charged_try'};
 1270: 	$button=1;
 1271:     } elsif ($award eq 'NOT_FUNCTION') {
 1272:         $message = &mt("Not a function").'.';
 1273:         $css_class=$possible_class{'not_charged_try'};
 1274:         $button=1;
 1275:     } elsif ($award eq 'WRONG_FORMAT') {
 1276:         $message = &mt("Wrong format").'.';
 1277:         $css_class=$possible_class{'not_charged_try'};
 1278:         $button=1;
 1279:      } elsif ($award eq 'INTERNAL_ERROR') {
 1280:         $message = &mt("An internal error occurred while processing your answer. Please try again later.");
 1281:         $css_class=$possible_class{'not_charged_try'};
 1282:         $button=1;
 1283:     } elsif ($award eq 'INCORRECT') {
 1284: 	$message = &mt("Incorrect").'.';
 1285: 	$css_class=$possible_class{'charged_try'};
 1286: 	$button=1;
 1287:     } elsif ($award eq 'SUBMITTED') {
 1288: 	$message = &mt("Your submission has been recorded.");
 1289: 	$css_class=$possible_class{'no_grade'};
 1290: 	$button=1;
 1291:     } elsif ($award eq 'SUBMITTED_CREDIT') {
 1292:         $message = &mt("Your submission has been recorded, and credit awarded.");
 1293:         $css_class=$possible_class{'correct'};
 1294:         $button=1;
 1295:     } elsif ($award eq 'ANONYMOUS') {
 1296:         $message = &mt("Your anonymous submission has been recorded.");
 1297:         $css_class=$possible_class{'no_grade'};
 1298:         $button=1;
 1299:     } elsif ($award eq 'ANONYMOUS_CREDIT') {
 1300:         $message = &mt("Your anonymous submission has been recorded, and credit awarded.");
 1301:         $css_class=$possible_class{'correct'};
 1302:         $button=1;
 1303:     } elsif ($award eq 'DRAFT') {
 1304: 	$message = &mt("Copy saved but not submitted.");
 1305: 	$css_class=$possible_class{'not_charged_try'};
 1306: 	$button=1;
 1307:     } elsif ($award eq 'ASSIGNED_SCORE') {
 1308: 	$message = &mt("A score has been assigned.");
 1309: 	$css_class=$possible_class{'correct'};
 1310: 	$button=0;
 1311:     } elsif ($award eq '') {
 1312: 	if ($handgrade && $Apache::inputtags::status[-1] eq 'SHOW_ANSWER') {
 1313: 	    $message = &mt("Nothing submitted.");
 1314: 	    $css_class=$possible_class{'charged_try'};
 1315: 	} else {
 1316: 	    $css_class=$possible_class{'not_charged_try'};
 1317: 	}
 1318: 	$button=1;
 1319:     } else {
 1320: 	$message = &mt("Unknown message").": $award";
 1321: 	$button=1;
 1322:     }
 1323:     my (undef,undef,$domain,$user)=&Apache::lonnet::whichuser();
 1324:     foreach my $resid(@Apache::inputtags::response){
 1325:         if ($Apache::lonhomework::history{"resource.$part.$resid.handback"}) {
 1326:             if ($target eq 'tex') {
 1327:                 $message.= "\\\\\n";
 1328:             } else {
 1329:                 $message.='<br />';
 1330:             }
 1331: 	    my @files = split(/\s*,\s*/,
 1332: 			      $Apache::lonhomework::history{"resource.$part.$resid.handback"});
 1333: 	    my $file_msg;
 1334: 	    foreach my $file (@files) {
 1335:                 if ($target eq 'tex') {
 1336:                     $file_msg.= "\\\\\n".$file;
 1337:                 } else {
 1338:                     $file_msg.= '<br /><a href="/uploaded/'."$domain/$user".'/'.$file.'">'.$file.'</a>';
 1339:                 }
 1340: 	    }
 1341: 	    $message .= &mt('Returned file(s): [_1]',$file_msg);
 1342:             if ($target eq 'tex') {
 1343:                 $message.= "\\\\\n";
 1344:             } else {
 1345:                 $message.='<br />';
 1346:             }
 1347: 	}
 1348:     }
 1349: 
 1350:     if (&Apache::lonhomework::hide_problem_status()
 1351: 	&& $Apache::inputtags::status[-1] ne 'SHOW_ANSWER'
 1352: 	&& &hide_award($award)) {
 1353:         $message = &mt("Answer Submitted: Your final submission will be graded after the due date.");
 1354:         my @interval= &Apache::lonnet::EXT("resource.$part.interval");
 1355:         if ($interval[0] =~ /\d+/) {
 1356:             my $first_access=&Apache::lonnet::get_first_access($interval[1]);
 1357:             if (defined($first_access)) {
 1358:                 my $due_date= &Apache::lonnet::EXT("resource.$part.duedate");
 1359:                 my ($timelimit) = ($interval[0] =~ /^(\d+)/);
 1360:                 unless (($due_date) && ($due_date < $first_access + $timelimit)) {
 1361:                     $message = &mt("Answer Submitted: Your final submission will be graded when the time limit is reached.");
 1362:                 }
 1363:             }
 1364:         }
 1365: 	$css_class=$possible_class{'no_grade'};
 1366: 	$button=1;
 1367:     }
 1368:     if ($Apache::inputtags::status[-1] eq 'SHOW_ANSWER' && 
 1369: 	!$added_computer_text && $target ne 'tex') {
 1370:         if ($computer) {
 1371:             $message = "$computer $message";
 1372:         }
 1373: 	$added_computer_text=1;
 1374:     }
 1375:     if ($Apache::lonhomework::type eq 'practice') {
 1376:        if ($target eq 'web') {
 1377:            $message .= '<br />';
 1378:        } else {
 1379:            $message .= ' ';      
 1380:        }
 1381:        $message.=&mt('Submissions to practice problems are not permanently recorded.');
 1382:     }
 1383:     return ($button,$css_class,$message,$previousmsg);
 1384: }
 1385: 
 1386: sub markup_unit {
 1387:     my ($unit,$target)=@_;
 1388:     if ($target eq 'tex') {
 1389: 	return '\texttt{'.&Apache::lonxml::latex_special_symbols($unit).'}'; 
 1390:     } else {
 1391: 	return "<tt>".$unit."</tt>";
 1392:     }
 1393: }
 1394: 
 1395: sub removealldata {
 1396:     my ($id)=@_;
 1397:     foreach my $key (keys(%Apache::lonhomework::results)) {
 1398: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
 1399: 	    &Apache::lonxml::debug("Removing $key");
 1400: 	    delete($Apache::lonhomework::results{$key});
 1401: 	}
 1402:     }
 1403: }
 1404: 
 1405: sub hidealldata {
 1406:     my ($id)=@_;
 1407:     foreach my $key (keys(%Apache::lonhomework::results)) {
 1408: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
 1409: 	    &Apache::lonxml::debug("Hidding $key");
 1410: 	    my $newkey=$key;
 1411: 	    $newkey=~s/^(resource\.\Q$id\E\.[^\.]+\.)(.*)$/${1}hidden${2}/;
 1412: 	    $Apache::lonhomework::results{$newkey}=
 1413: 		$Apache::lonhomework::results{$key};
 1414: 	    delete($Apache::lonhomework::results{$key});
 1415: 	}
 1416:     }
 1417: }
 1418: 
 1419: sub setgradedata {
 1420:     my ($award,$msg,$id,$previously_used) = @_;
 1421:     if ($Apache::lonhomework::scantronmode && 
 1422: 	&Apache::lonnet::validCODE($env{'form.CODE'})) {
 1423: 	$Apache::lonhomework::results{"resource.CODE"}=$env{'form.CODE'};
 1424:     } elsif ($Apache::lonhomework::scantronmode && 
 1425: 	     $env{'form.CODE'} eq '' &&
 1426: 	     $Apache::lonhomework::history{"resource.CODE"} ne '') {
 1427: 	$Apache::lonhomework::results{"resource.CODE"}='';
 1428:     }
 1429: 
 1430:     if (!$Apache::lonhomework::scantronmode &&
 1431: 	$Apache::inputtags::status['-1'] ne 'CAN_ANSWER' &&
 1432: 	$Apache::inputtags::status['-1'] ne 'CANNOT_ANSWER') {
 1433: 	$Apache::lonhomework::results{"resource.$id.afterduedate"}=$award;
 1434: 	return '';
 1435:     } elsif ( $Apache::lonhomework::history{"resource.$id.awarded"} < 1
 1436: 	      || $Apache::lonhomework::scantronmode 
 1437: 	      || &Apache::lonhomework::hide_problem_status()  ) {
 1438:         # the student doesn't already have it correct,
 1439: 	# or we are in a mode (scantron orno problem status) where a correct 
 1440:         # can become incorrect
 1441: 	# handle assignment of tries and solved status
 1442: 	my $solvemsg;
 1443: 	if ($Apache::lonhomework::scantronmode) {
 1444: 	    $solvemsg='correct_by_scantron';
 1445: 	} else {
 1446: 	    $solvemsg='correct_by_student';
 1447: 	}
 1448: 	if ($Apache::lonhomework::history{"resource.$id.afterduedate"}) {
 1449: 	    $Apache::lonhomework::results{"resource.$id.afterduedate"}='';
 1450: 	}
 1451: 	if ( $award eq 'ASSIGNED_SCORE') {
 1452: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1453: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1454: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1455: 		$solvemsg;
 1456: 	    my $numawards=scalar(@Apache::inputtags::response);
 1457: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1458: 	    foreach my $res (@Apache::inputtags::response) {
 1459: 		if (defined($Apache::lonhomework::results{"resource.$id.$res.awarded"})) {
 1460: 		    $Apache::lonhomework::results{"resource.$id.awarded"}+=
 1461: 			$Apache::lonhomework::results{"resource.$id.$res.awarded"};
 1462: 		} else {
 1463: 		    $Apache::lonhomework::results{"resource.$id.awarded"}+=
 1464: 			&awarddetail_to_awarded($Apache::lonhomework::results{"resource.$id.$res.awarddetail"});
 1465: 		}
 1466: 	    }
 1467: 	    if ($numawards > 0) {
 1468: 		$Apache::lonhomework::results{"resource.$id.awarded"}/=
 1469: 		    $numawards;
 1470: 	    }
 1471: 	} elsif ( $award eq 'APPROX_ANS' || $award eq 'EXACT_ANS' ) {
 1472: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1473: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1474: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1475: 		$solvemsg;
 1476: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
 1477:         } elsif ( $award eq 'SUBMITTED_CREDIT' ) {
 1478:             $Apache::lonhomework::results{"resource.$id.tries"} =
 1479:                 $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1480:             $Apache::lonhomework::results{"resource.$id.solved"} =
 1481:                 'credit_attempted';
 1482:             $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
 1483:         }  elsif ( $award eq 'ANONYMOUS_CREDIT' ) {
 1484:             $Apache::lonhomework::results{"resource.$id.tries"} =
 1485:                 $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1486:             $Apache::lonhomework::results{"resource.$id.solved"} =
 1487:                 'credit_attempted';
 1488:             $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
 1489: 	} elsif ( $award eq 'INCORRECT' ) {
 1490: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1491: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1492: 	    if (&Apache::lonhomework::hide_problem_status()
 1493: 		|| $Apache::lonhomework::scantronmode) {
 1494: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1495: 	    }
 1496: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1497: 		'incorrect_attempted';
 1498: 	} elsif ( $award eq 'SUBMITTED' ) {
 1499: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1500: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1501: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1502: 		'ungraded_attempted';
 1503:         }  elsif ( $award eq 'ANONYMOUS' ) {
 1504:             $Apache::lonhomework::results{"resource.$id.tries"} =
 1505:                 $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1506:             $Apache::lonhomework::results{"resource.$id.solved"} =
 1507:                 'ungraded_attempted';
 1508: 	} elsif ( $award eq 'DRAFT' ) {
 1509: 	    $Apache::lonhomework::results{"resource.$id.solved"} = '';
 1510: 	} elsif ( $award eq 'NO_RESPONSE' ) {
 1511: 	    #no real response so delete any data that got stored
 1512: 	    &removealldata($id);
 1513: 	    return '';
 1514: 	} else {
 1515: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1516: 		'incorrect_attempted';
 1517: 	    if (&Apache::lonhomework::show_no_problem_status()
 1518: 		|| $Apache::lonhomework::scantronmode) {
 1519: 		$Apache::lonhomework::results{"resource.$id.tries"} =
 1520: 		    $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1521: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1522: 	    }
 1523: 
 1524: 	    if (&Apache::lonhomework::show_some_problem_status()) {
 1525: 		# clear out the awarded if they had gotten it wrong/right
 1526: 		# and are now in an error mode	
 1527: 		$Apache::lonhomework::results{"resource.$id.awarded"} = '';
 1528: 	    }
 1529: 	}
 1530: 	if (defined($msg)) {
 1531: 	    $Apache::lonhomework::results{"resource.$id.awardmsg"} = $msg;
 1532: 	}
 1533: 	# did either of the overall awards chage? If so ignore the 
 1534: 	# previous check
 1535: 	if (($Apache::lonhomework::results{"resource.$id.awarded"} eq
 1536: 	     $Apache::lonhomework::history{"resource.$id.awarded"}) &&
 1537: 	    ($Apache::lonhomework::results{"resource.$id.solved"} eq
 1538: 	     $Apache::lonhomework::history{"resource.$id.solved"})) {
 1539: 	    # check if this was a previous submission if it was delete the
 1540: 	    # unneeded data and update the previously_used attribute
 1541: 	    if ( $previously_used eq 'PREVIOUSLY_USED') {
 1542: 		if (&Apache::lonhomework::show_problem_status()) {
 1543: 		    delete($Apache::lonhomework::results{"resource.$id.tries"});
 1544: 		    $Apache::lonhomework::results{"resource.$id.previous"} = '1';
 1545: 		}
 1546: 	    } elsif ( $previously_used eq 'PREVIOUSLY_LAST') {
 1547: 		#delete all data as they student didn't do anything, but save
 1548: 		#the list of collaborators.
 1549: 		&removealldata($id);
 1550: 		#and since they didn't do anything we were never here
 1551: 		return '';
 1552: 	    } else {
 1553: 		$Apache::lonhomework::results{"resource.$id.previous"} = '0';
 1554: 	    }
 1555: 	}
 1556:     } elsif ( $Apache::lonhomework::history{"resource.$id.awarded"} == 1 ) {
 1557: 	#delete all data as they student already has it correct
 1558: 	&removealldata($id);
 1559: 	#and since they didn't do anything we were never here
 1560: 	return '';
 1561:     }
 1562:     $Apache::lonhomework::results{"resource.$id.award"} = $award;
 1563:     if ($award eq 'SUBMITTED') {
 1564: 	&Apache::response::add_to_gradingqueue();
 1565:     }
 1566:     $Apache::lonhomework::results{"resource.$id.type"} = $Apache::lonhomework::type;
 1567:     $Apache::lonhomework::results{"resource.$id.duedate"} = &Apache::lonnet::EXT("resource.$id.duedate");
 1568:     $Apache::lonhomework::results{"resource.$id.hinttries"} = &Apache::lonnet::EXT("resource.$id.hinttries");
 1569:     $Apache::lonhomework::results{"resource.$id.version"} = &Apache::lonnet::usedversion();
 1570:     $Apache::lonhomework::results{"resource.$id.maxtries"} = &Apache::lonnet::EXT("resource.$id.maxtries");
 1571: }
 1572: 
 1573: sub find_which_previous {
 1574:     my ($version) = @_;
 1575:     my $part = $Apache::inputtags::part;
 1576:     my (@previous_version);
 1577:     foreach my $resp (@Apache::inputtags::response) {
 1578: 	my $key = "$version:resource.$part.$resp.submission";
 1579: 	my $submission = $Apache::lonhomework::history{$key};
 1580: 	my %previous = &Apache::response::check_for_previous($submission,
 1581: 							     $part,$resp,
 1582: 							     $version);
 1583: 	push(@previous_version,$previous{'version'});
 1584:     }
 1585:     return &previous_match(\@previous_version,
 1586: 			   scalar(@Apache::inputtags::response));
 1587: }
 1588: 
 1589: sub previous_match {
 1590:     my ($previous_array,$count) = @_;
 1591:     my $match = 0;
 1592:     my @matches;
 1593:     foreach my $versionar (@$previous_array) {
 1594: 	foreach my $version (@$versionar) {
 1595: 	    $matches[$version]++;
 1596: 	}
 1597:     }
 1598:     my $which=0;
 1599:     foreach my $elem (@matches) {
 1600: 	if ($elem eq $count) {
 1601: 	    $match=1;
 1602: 	    last;
 1603: 	}
 1604: 	$which++;
 1605:     }
 1606:     return ($match,$which);
 1607: }
 1608: 
 1609: sub grade {
 1610:     my ($target) = @_;
 1611:     my $id = $Apache::inputtags::part;
 1612:     my $response='';
 1613:     if ( defined $env{'form.submitted'}) {
 1614: 	my (@awards,@msgs);
 1615: 	foreach $response (@Apache::inputtags::response) {
 1616: 	    &Apache::lonxml::debug("looking for response.$id.$response.awarddetail");
 1617: 	    my $value=$Apache::lonhomework::results{"resource.$id.$response.awarddetail"};
 1618: 	    &Apache::lonxml::debug("keeping $value from $response for $id");
 1619: 	    push (@awards,$value);
 1620: 	    $value=$Apache::lonhomework::results{"resource.$id.$response.awardmsg"};
 1621: 	    &Apache::lonxml::debug("got message $value from $response for $id");
 1622: 	    push (@msgs,$value);
 1623: 	}
 1624: 	my ($finalaward,$msg) = 
 1625: 	    &finalizeawards(\@awards,\@msgs,undef,undef,
 1626: 			    $Apache::lonhomework::scantronmode);
 1627: 	my $previously_used;
 1628: 	if ( $#Apache::inputtags::previous eq $#awards ) {
 1629: 	    my ($match) =
 1630: 		&previous_match(\@Apache::inputtags::previous_version,
 1631: 				scalar(@Apache::inputtags::response));
 1632: 
 1633: 	    if ($match) {
 1634: 		$previously_used = 'PREVIOUSLY_LAST';
 1635: 		foreach my $value (@Apache::inputtags::previous) {
 1636: 		    if ($value eq 'PREVIOUSLY_USED' ) {
 1637: 			$previously_used = $value;
 1638: 			last;
 1639: 		    }
 1640: 		}
 1641: 	    }
 1642: 	}
 1643: 	&Apache::lonxml::debug("final award $finalaward, $previously_used, message $msg");
 1644: 	&setgradedata($finalaward,$msg,$id,$previously_used);
 1645:     }
 1646:     return '';
 1647: }
 1648: 
 1649: sub get_grade_messages {
 1650:     my ($id,$prefix,$target,$status,$nocorrect,$tdclass) = @_;
 1651: # nocorrect suppresses "Computer's answer now shown above"
 1652:     my ($message,$latemessage,$trystr,$previousmsg);
 1653:     my $showbutton = 1;
 1654: 
 1655:     my $award = $Apache::lonhomework::history{"$prefix.award"};
 1656:     my $awarded = $Apache::lonhomework::history{"$prefix.awarded"};
 1657:     my $solved = $Apache::lonhomework::history{"$prefix.solved"};
 1658:     my $previous = $Apache::lonhomework::history{"$prefix.previous"};
 1659:     my $awardmsg = $Apache::lonhomework::history{"$prefix.awardmsg"};
 1660:     &Apache::lonxml::debug("Found Award |$award|$solved|$awardmsg");
 1661:     if ( $award ne '' || $solved ne '' || $status eq 'SHOW_ANSWER') {
 1662: 	&Apache::lonxml::debug('Getting message');
 1663: 	($showbutton,my $css_class,$message,$previousmsg) =
 1664: 	    &decideoutput($award,$awarded,$awardmsg,$solved,$previous,
 1665: 			  $target,(($status eq 'CAN_ANSWER') || $nocorrect),$tdclass);
 1666: 	if ($target eq 'tex') {
 1667: 	    $message='\vskip 2 mm '.$message.' ';
 1668: 	} else {
 1669: 	    $message="<td class=\"$tdclass $css_class\">$message</td>";
 1670: 	    if ($previousmsg) {
 1671: 		$previousmsg="<td class=\"$tdclass LC_answer_previous\">$previousmsg</td>";
 1672: 	    }
 1673: 	}
 1674:     }
 1675:     my $tries = $Apache::lonhomework::history{"$prefix.tries"};
 1676:     my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
 1677:     &Apache::lonxml::debug("got maxtries of :$maxtries:");
 1678:     #if tries are set to negative turn off the Tries/Button and messages
 1679:     if (defined($maxtries) && $maxtries < 0) { return ''; }
 1680:     if ( $tries eq '' ) { $tries = '0'; }
 1681:     if ( $maxtries eq '' ) { $maxtries = '2'; } 
 1682:     if ( $maxtries eq 'con_lost' ) { $maxtries = '0'; } 
 1683:     my $tries_text= &get_tries_text();
 1684:     if ($showbutton) {
 1685: 	if ($target eq 'tex') {
 1686: 	    if ($env{'request.state'} ne "construct"
 1687: 		&& $Apache::lonhomework::type ne 'exam'
 1688: 		&& $env{'form.suppress_tries'} ne 'yes') {
 1689: 		$trystr ='{\vskip 1 mm \small '
 1690:                         .&mt('[_1]'.$tries_text.'[_2] [_3]'
 1691: 				,'\textit{','}',$tries.'/'.$maxtries ) 
 1692:                         .'} \vskip 2 mm';
 1693: 	    } else {
 1694: 		$trystr = '\vskip 0 mm ';
 1695: 	    }
 1696: 	} else {
 1697: 	    my $trial =$tries;
 1698: 	    if ($Apache::lonhomework::parsing_a_task) {
 1699: 	    } elsif($env{'request.state'} ne 'construct') {
 1700: 		$trial.="/".&Apache::lonhtmlcommon::direct_parm_link($maxtries,$env{'request.symb'},'maxtries',$id,$target);
 1701: 	    } else {
 1702: 		if (defined($Apache::inputtags::params{'maxtries'})) {
 1703: 		    $trial.="/".$Apache::inputtags::params{'maxtries'};
 1704: 		}
 1705: 	    }
 1706: 	    $trystr = '<td class="'.$tdclass.'"><span class="LC_nobreak">'.&mt($tries_text.' [_1]',$trial).'</span></td>';
 1707: 	}
 1708:     }
 1709: 
 1710:     if ($Apache::lonhomework::history{"$prefix.afterduedate"}) {
 1711: 	#last submissions was after due date
 1712: 	$latemessage=&mt(' The last submission was after the Due Date ');;
 1713: 	if ($target eq 'web') {
 1714: 	    $latemessage='<td class="'.$tdclass.' LC_answer_late">'.$latemessage.'</td>';
 1715: 	}
 1716:     }
 1717:     return ($previousmsg,$latemessage,$message,$trystr,$showbutton);
 1718: }
 1719: 
 1720: sub gradestatus {
 1721:     my ($id,$target,$no_previous) = @_;
 1722:     my $showbutton = 1;
 1723:     my $message = '';
 1724:     my $latemessage = '';
 1725:     my $trystr='';
 1726:     my $button='';
 1727:     my $previousmsg='';
 1728:     my $tdclass='';
 1729: 
 1730:     my $status = $Apache::inputtags::status['-1'];
 1731:     &Apache::lonxml::debug("gradestatus has :$status:");
 1732:     if ( $status ne 'CLOSED' 
 1733: 	 && $status ne 'UNAVAILABLE' 
 1734: 	 && $status ne 'INVALID_ACCESS' 
 1735: 	 && $status ne 'NEEDS_CHECKIN' 
 1736: 	 && $status ne 'NOT_IN_A_SLOT'
 1737:          && $status ne 'RESERVABLE'
 1738:          && $status ne 'RESERVABLE_LATER'
 1739:          && $status ne 'NOTRESERVABLE') {
 1740: 
 1741: 	if ($status eq 'SHOW_ANSWER') {
 1742:             $showbutton = 0;
 1743:         }
 1744: 
 1745:         unless (($status eq 'SHOW_ANSWER') || ($status eq 'CANNOT_ANSWER')) {
 1746:             if ($target ne 'tex') {
 1747:                 $tdclass = 'LC_status_submit_'.$id;
 1748:             }
 1749:         }
 1750: 
 1751: 	($previousmsg,$latemessage,$message,$trystr) =
 1752: 	    &get_grade_messages($id,"resource.$id",$target,$status,
 1753: 				$showbutton,$tdclass);
 1754: 	if ($status eq 'CANNOT_ANSWER') {
 1755: 	    $showbutton = 0;
 1756: 	}
 1757: 	if ( $status eq 'SHOW_ANSWER') {
 1758: 	    undef($previousmsg);
 1759: 	}
 1760: 	if ( $showbutton ) {
 1761: 	    if ($target ne 'tex') {
 1762:                 if ($env{'form.disable_submit'}) {
 1763:                     $button = '<input type="submit" name="submit_'.$id.'" id="submit_'.$id.'" class="LC_hwk_submit" value="'.&mt('Submit Answer').'" disabled="disabled" />&nbsp;'.
 1764:                                '<div id="msg_submit_'.$id.'" style="display:none"></div>';
 1765:                 } else {
 1766: 		    $button = 
 1767:             '<input onmouseup="javascript:setSubmittedPart(\''.$id.'\');this.form.action+=\'#'.&escape($id).'\';"
 1768:                     type="submit" name="submit_'.$id.'" id="submit_'.$id.'" class="LC_hwk_submit"
 1769:                     value="'.&mt('Submit Answer').'" />&nbsp;'.
 1770:                     '<div id="msg_submit_'.$id.'" style="display:none">'.
 1771:                     &mt('Processing your submission ...').'</div>';
 1772:                 }
 1773: 	    }
 1774: 	}
 1775: 
 1776:     }
 1777:     my $output= $previousmsg.$latemessage.$message.$trystr;
 1778:     if ($output =~ /^\s*$/) {
 1779: 	return $button;
 1780:     } else {
 1781: 	if ($target eq 'tex') {
 1782: 	    return $button.' \vskip 0 mm '.$output.' ';
 1783: 	} else {
 1784: 	    $output =
 1785: 		'<table><tr><td>'.$button.'</td>'.$output;
 1786: 	    if (!$no_previous) {
 1787: 		$output.='<td class="'.$tdclass.'">'.&previous_tries($id,$target).'</td>';
 1788: 	    }
 1789: 	    $output.= '</tr></table>';
 1790: 	    return $output;
 1791: 	}
 1792:     }
 1793: }
 1794: 
 1795: sub previous_tries {
 1796:     my ($id,$target) = @_;
 1797:     my $output;
 1798:     my $status = $Apache::inputtags::status['-1'];
 1799: 
 1800:     my $count;
 1801:     my %count_lookup;
 1802:     my ($lastrndseed,$lasttype);
 1803:     my $numstamps = 0;
 1804: 
 1805:     foreach my $i (1..$Apache::lonhomework::history{'version'}) {
 1806: 	my $prefix = $i.":resource.$id";
 1807:         my $is_anon;
 1808:         my $curr_type = $Apache::lonhomework::history{"$prefix.type"};    
 1809:         if (defined($env{'form.grade_symb'})) {
 1810:             if (($curr_type eq 'anonsurvey') || ($curr_type eq 'anonsurveycred')) {
 1811:                 $is_anon = 1;
 1812:             }
 1813:         }
 1814: 	next if (!exists($Apache::lonhomework::history{"$prefix.award"}));
 1815: 	$count++;
 1816: 	$count_lookup{$i} = $count;
 1817:         my $curr_rndseed = $Apache::lonhomework::history{"$prefix.rndseed"};
 1818: 	my ($previousmsg,$latemessage,$message,$trystr);
 1819: 
 1820: 	($previousmsg,$latemessage,$message,$trystr) =
 1821: 	    &get_grade_messages($id,"$prefix",$target,$status);
 1822: 
 1823: 	if ($previousmsg ne '') {
 1824: 	    my ($match,$which) = &find_which_previous($i);
 1825: 	    $message=$previousmsg;
 1826: 	    my $previous = $count_lookup{$which};
 1827: 	    $message =~ s{(</td>)}{ as submission \# $previous $1};
 1828: 	} elsif ($Apache::lonhomework::history{"$prefix.tries"}) {
 1829: 	    if (!(&Apache::lonhomework::hide_problem_status()
 1830: 		  && $Apache::inputtags::status[-1] ne 'SHOW_ANSWER')
 1831: 		&& $Apache::lonhomework::history{"$prefix.solved"} =~/^correct/
 1832: 		) {
 1833: 		
 1834:                 my $txt_correct = &mt('Correct');
 1835:                 my $awarded = $Apache::lonhomework::history{"$prefix.awarded"};
 1836:                 if ($awarded < 1 && $awarded > 0) {
 1837:                     $txt_correct=&mt('Partially Correct');
 1838:                 } elsif ($awarded < 1) {
 1839:                     if ($awarded eq '') {
 1840:                         $txt_correct='';
 1841:                     } else {
 1842:                         $txt_correct=&mt('Incorrect');
 1843:                     }
 1844:                 }
 1845: 		$message =~ s{(<td.*?>)(.*?)(</td>)}
 1846:                              {$1 <strong>$txt_correct</strong>. $3}s;
 1847: 	    }
 1848:             my $trystr = "(".&mt('Try [_1]',$Apache::lonhomework::history{"$prefix.tries"}).")";
 1849:             if (($curr_rndseed ne '') &&  ($lastrndseed ne '')) {
 1850:                 if (($curr_rndseed ne $lastrndseed) && 
 1851:                     (($curr_type eq 'randomizetry') || ($lasttype eq 'randomizetry'))) {
 1852:                     $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>';
 1853:                 }
 1854:             } 
 1855: 	    $message =~ s{(</td>)}{ $trystr $1};
 1856: 	}
 1857: 	my ($class) = ($message =~ m{<td.*class="([^"]*)"}); #"
 1858: 	$message =~ s{(<td.*?>)}{<td>};
 1859: 	
 1860: 
 1861: 	$output .= '<tr class="'.$class.'">'.
 1862: 	           '<td align="center">'.$count.'</td>'.$message;
 1863:         if ((!$is_anon) && ($Apache::lonhomework::history{"$prefix.tries"}) &&
 1864:             ($Apache::lonhomework::history{"$prefix.award"} ne 'ASSIGNED_SCORE') &&
 1865:             ($Apache::lonhomework::history{$i.':timestamp'})) {
 1866:             $output .= '<td>'.&Apache::lonlocal::locallocaltime(
 1867:                              $Apache::lonhomework::history{$i.':timestamp'}).'</td>';
 1868:             $numstamps ++;
 1869:         } else {
 1870:             $output .= '<td></td>';
 1871:         }
 1872: 	foreach my $resid (@Apache::inputtags::response) {
 1873: 	    my $prefix = $prefix.".$resid";
 1874: 	    if (exists($Apache::lonhomework::history{"$prefix.submission"})) {
 1875: 		my $submission =
 1876: 		    $Apache::inputtags::submission_display{"$prefix.submission"};
 1877: 		if (!defined($submission)) {
 1878: 		    $submission = 
 1879: 			$Apache::lonhomework::history{"$prefix.submission"};
 1880: 		}
 1881:                 if ($is_anon) {
 1882:                     $output.='<td>'.&mt('(only shown to submitter)').'</td>';
 1883:                 } else {
 1884: 		    $output.='<td>'.$submission.'</td>';
 1885:                 }
 1886: 	    } else {
 1887: 		$output.='<td></td>';
 1888: 	    }
 1889: 	}
 1890: 	$output.=&Apache::loncommon::end_data_table_row()."\n";
 1891:         $lastrndseed = $curr_rndseed;
 1892:         $lasttype = $curr_type;
 1893:     }
 1894:     return if ($output eq '');
 1895:     my $headers = '<tr>'.
 1896:                   '<th>'.&mt('Submission #').'</th>'.
 1897:                   '<th>'.&mt('Try').'</th><th>';
 1898:     if ($numstamps) {
 1899:         $headers .= &mt('When');
 1900:     }
 1901:     $headers .= '</th>';
 1902:     my $colspan = scalar(@Apache::inputtags::response);
 1903:     if ($colspan > 1) {
 1904:         $headers .= '<th colspan="'.$colspan.'">';
 1905:     } else {
 1906:         $headers .= '<th>';
 1907:     }
 1908:     $headers .= &mt('Submitted Answer').'</th></tr>';
 1909:     $output ='<table class="LC_prior_tries">'.$headers.$output.'</table>';
 1910: 
 1911:     my $tries_text = &get_tries_text('link');
 1912:     my $prefix = $env{'form.request.prefix'};
 1913:     $prefix =~ tr{.}{_};
 1914:     my $function_name = 'LONCAPA_previous_tries_'.$prefix;
 1915:     if (($env{'request.state'} eq 'construct') || ($id =~ /\W/)) {
 1916:         $function_name .= $Apache::lonxml::curdepth;
 1917:     } else {
 1918:         $function_name .= $id;
 1919:     }
 1920:     $function_name .= '_'.$Apache::lonxml::counter;
 1921:     my $possmathjax = 1;
 1922:     my $result = &Apache::loncommon::modal_adhoc_window($function_name,420,410,$output,
 1923:                                                         &mt($tries_text),$possmathjax)."<br />";
 1924:     return $result;
 1925: }
 1926: 
 1927: sub get_tries_text {
 1928:     my ($context) = @_;
 1929:     my $tries_text;
 1930:     if ($context eq 'link') {
 1931:         $tries_text = 'Previous Tries';
 1932:     } else {
 1933:         $tries_text = 'Tries';
 1934:     }
 1935:     if ( $Apache::lonhomework::type eq 'survey' ||
 1936:          $Apache::lonhomework::type eq 'surveycred' ||
 1937:          $Apache::lonhomework::type eq 'anonsurvey' ||
 1938:          $Apache::lonhomework::type eq 'anonsurveycred' ||
 1939:          $Apache::lonhomework::parsing_a_task) {
 1940:         if ($context eq 'link') {
 1941:             $tries_text = 'Previous Submissions';
 1942:         } else {
 1943:             $tries_text = 'Submissions';
 1944:         }
 1945:     }
 1946:     return $tries_text;
 1947: }
 1948: 
 1949: sub spelling_languages {
 1950:     my %langchoices;
 1951:     foreach my $id (&Apache::loncommon::languageids()) {
 1952:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 1953:         if ($code ne '') {
 1954:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 1955:         }
 1956:     }
 1957:     my @spelllangs = ('none');
 1958:     foreach my $code ('en','de','he','es','fr','pt','tr') {
 1959:         push(@spelllangs,[$code,$langchoices{$code}]);
 1960:     }
 1961:     return \@spelllangs;
 1962: }
 1963: 
 1964: sub edit_mathresponse_button {
 1965:     my ($field) = @_;
 1966:     my $eqneditor = 'lcmath';
 1967:     if ($env{'browser.type'} eq 'safari') {
 1968:         if ($env{'browser.os'} eq 'mac') {
 1969:             my ($prefix,$version) = ($env{'browser.version'} =~ /^(\d*)(\d{3})\./);
 1970:             if ($env{'browser.mobile'}) {
 1971:                 if (($version < 531) || (($prefix eq '') && ($version < 533))) {
 1972:                     $eqneditor = '';
 1973:                 }
 1974:             } elsif ($version < 533) {
 1975:                 $eqneditor = 'dragmath';
 1976:             }
 1977:         } elsif ($env{'browser.os'} eq 'win') {
 1978:             if ($env{'browser.version'} < 533) {
 1979:                 $eqneditor = 'dragmath';
 1980:             }
 1981:         }
 1982:     } elsif ($env{'browser.type'} eq 'explorer') {
 1983:         if ($env{'browser.version'} < 9) {
 1984:             $eqneditor = 'dragmath';
 1985:         }
 1986:     } elsif ($env{'browser.type'} eq 'mozilla') {
 1987:         if ($env{'browser.version'} < 5) {
 1988:             $eqneditor = 'dragmath';
 1989:         } else {
 1990:             if ($env{'browser.info'} =~ /^firefox\-([\d\.]+)/) {
 1991:                 my $firefox = $1;
 1992:                 if ($firefox < 4) {
 1993:                     $eqneditor = 'dragmath';
 1994:                 }
 1995:             }
 1996:         }
 1997:     } elsif ($env{'browser.type'} eq 'chrome') {
 1998:         if ($env{'browser.version'} < 5) {
 1999:             $eqneditor = 'dragmath';
 2000:         }
 2001:     } elsif ($env{'browser.type'} eq 'opera') {
 2002:         if ($env{'browser.version'} < 12) {
 2003:             $eqneditor = 'dragmath';
 2004:         }
 2005:     }
 2006:     if ($eqneditor eq 'lcmath') {
 2007:         if (($env{'request.course.id'}) && ($env{'request.state'} ne 'construct')) {
 2008:             if (exists($env{'course.'.$env{'request.course.id'}.'.uselcmath'})) {
 2009:                 if ($env{'course.'.$env{'request.course.id'}.'.uselcmath'} eq '0') {
 2010:                     $eqneditor = 'dragmath';
 2011:                 }
 2012:             } else {
 2013:                 my %domdefs = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
 2014:                 if ($domdefs{'uselcmath'} eq '0') {
 2015:                     $eqneditor = 'dragmath';
 2016:                 }
 2017:             }
 2018:         } else {
 2019:             my %domdefs = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
 2020:             if ($domdefs{'uselcmath'} eq '0') {
 2021:                 $eqneditor = 'dragmath';
 2022:             }
 2023:         }
 2024:     }
 2025:     if ($eqneditor eq 'dragmath') {
 2026:         # DragMath applet
 2027:         my $button=&mt('Edit Answer');
 2028: #       my $helplink=&Apache::loncommon::help_open_topic('Formula_Editor');
 2029:         my $iconpath=$Apache::lonnet::perlvar{'lonIconsURL'};
 2030:         return(<<ENDFORMULABUTTON);
 2031: <script type="text/javascript" language="JavaScript">
 2032: function LC_mathedit_${field} (LCtextline) {
 2033:     thenumber = LCtextline;
 2034:     var thedata = '';
 2035:     if (document.getElementById(LCtextline)) {
 2036:         thedata = document.getElementById(LCtextline).value;
 2037:     }
 2038:     newwin = window.open("/adm/dragmath/MaximaPopup.html","","width=565,height=400,resizable");
 2039: }
 2040: </script>
 2041: <a href="javascript:LC_mathedit_${field}('${field}');void(0);"><img class="stift" src="$iconpath/stift.gif" alt="$button" title="$button" /></a>
 2042: ENDFORMULABUTTON
 2043:     } elsif ($eqneditor eq 'lcmath') {
 2044:         # LON-CAPA math equation editor
 2045:         my $mathjaxjs;
 2046:         unless (lc(&Apache::lontexconvert::tex_engine()) eq 'mathjax') {
 2047:             $mathjaxjs = <<"MATHJAX_SCRIPT";
 2048: var mathjaxscript = document.createElement("script");
 2049:     mathjaxscript.type = "text/javascript";
 2050:     mathjaxscript.src = "/adm/MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
 2051:     document.body.appendChild(mathjaxscript);
 2052: MATHJAX_SCRIPT
 2053:         }
 2054:         return(<<EQ_EDITOR_SCRIPT);
 2055: <script type="text/javascript">
 2056:   var LCmathField = document.getElementById('${field}');
 2057:   LCmathField.className += ' math'; // note the space
 2058:   LCmathField.setAttribute('data-implicit_operators', 'true');
 2059:   var LCMATH_started;
 2060:   if (typeof LCMATH_started === 'undefined') {
 2061:     $mathjaxjs
 2062:     LCMATH_started = true;
 2063:     var script = document.createElement("script");
 2064:     script.type = "text/javascript";
 2065:     script.src = "/adm/LC_math_editor/LC_math_editor.min.js";
 2066:     document.body.appendChild(script);
 2067:     window.addEventListener('load', function(e) {
 2068:         LCMATH.initEditors();
 2069:     }, false);
 2070:   }
 2071: </script>
 2072: EQ_EDITOR_SCRIPT
 2073:     }
 2074: }
 2075: 
 2076: 1;
 2077: __END__
 2078: 
 2079: =pod
 2080: 
 2081: =back
 2082: 
 2083: =cut
 2084:  

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