File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.333.2.12.2.2: download - view: text, annotated - select for diffs
Sun Feb 5 01:52:21 2023 UTC (15 months, 1 week 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.356

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

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