File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.333.2.4.4.1: download - view: text, annotated - select for diffs
Wed Jun 21 19:55:00 2017 UTC (6 years, 10 months ago) by raeburn
Branches: version_2_11_2_msu
Diff to branchpoint 1.333.2.4: preferred, unified
- For 2.11.2 (modified).
    Use 2.12 feature ("done" button for timed exms) pre-release, in modified
    2.11.2. Domain's configuration must be set to prohibit hosting of sessions
    for domain's users outside own domain, and modification must be in place
    on all nodes in domain.

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

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