File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.356: download - view: text, annotated - select for diffs
Sat Feb 4 22:38:31 2023 UTC (15 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6978
  "turnoffeditor" parameter previously available for formularesponse and
  mathresponse is now also available for customreponse, but default for
  formula and math is "no", whereas default for custom is "yes".

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

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