File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.342: download - view: text, annotated - select for diffs
Wed Apr 6 00:34:12 2016 UTC (8 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6770. "Computer's answer now shown above" message moved to left of
  award-related message.

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

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