File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.309: download - view: text, annotated - select for diffs
Fri Sep 14 11:23:58 2012 UTC (11 years, 8 months ago) by goltermann
Branches: MAIN
CVS tags: HEAD
added essay response to pdf form functionality.
students can now print and upload a pdf with essay problems with form fields in it. after uploading they will get a notice that their essay is saved as a draft but not yet submitted.
fixed a missing <span> tag.
special thanks to jeconia kapitako who helped with inplementing textareas into lon capa pdf forms.

    1: # The LearningOnline Network with CAPA
    2: # input  definitons
    3: #
    4: # $Id: inputtags.pm,v 1.309 2012/09/14 11:23:58 goltermann 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: sub check_for_duplicate_ids {
  129:     my %check;
  130:     foreach my $id (@Apache::inputtags::partlist,
  131: 		    @Apache::inputtags::responselist,
  132: 		    @Apache::inputtags::hintlist,
  133: 		    @Apache::inputtags::importlist) {
  134: 	$check{$id}++;
  135:     }
  136:     my @duplicates;
  137:     foreach my $id (sort(keys(%check))) {
  138: 	if ($check{$id} > 1) {
  139: 	    push(@duplicates,$id);
  140: 	}
  141:     }
  142:     if (@duplicates) {
  143: 	&Apache::lonxml::error("Duplicated ids found, problem will operate incorrectly. Duplicated ids seen: ",join(', ',@duplicates));
  144:     }
  145: }
  146: 
  147: sub start_input {
  148:     my ($parstack,$safeeval)=@_;
  149:     my $id = &Apache::lonxml::get_id($parstack,$safeeval);
  150:     push (@Apache::inputtags::input,$id);
  151:     push (@Apache::inputtags::inputlist,$id);
  152:     return $id;
  153: }
  154: 
  155: sub end_input {
  156:     pop @Apache::inputtags::input;
  157:     return '';
  158: }
  159: 
  160: sub addchars {
  161:     my ($fieldid,$addchars)=@_;
  162:     my $output='';
  163:     foreach (split(/\,/,$addchars)) {
  164: 	$output.='<a href="javascript:void(document.forms.lonhomework.'.
  165: 	    $fieldid.'.value+=\''.$_.'\')">'.$_.'</a> ';
  166:     }
  167:     return $output;
  168: }
  169: 
  170: sub start_textfield {
  171:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  172:     my $result = "";
  173:     my $id = &start_input($parstack,$safeeval);
  174:     my $resid=$Apache::inputtags::response[-1];
  175:     if ($target eq 'web') {
  176: 	$Apache::lonxml::evaluate--;
  177: 	my $partid=$Apache::inputtags::part;
  178:         my ($oldresponse,$newvariation);
  179:         if ((($Apache::lonhomework::history{"resource.$partid.type"} eq 'randomizetry') ||
  180:              ($Apache::lonhomework::type eq 'randomizetry')) &&
  181:              ($Apache::inputtags::status[-1] eq 'CAN_ANSWER')) {
  182:             if ($env{'form.'.$partid.'.rndseed'} ne
  183:                 $Apache::lonhomework::history{"resource.$partid.rndseed"}) {
  184:                 $newvariation = 1;
  185:             }
  186:         }
  187:         unless ($newvariation) {
  188: 	    $oldresponse = $Apache::lonhomework::history{"resource.$partid.$resid.submission"};
  189:         }
  190: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  191: 	    my $cols = &Apache::lonxml::get_param('cols',$parstack,$safeeval);
  192: 	    if ( $cols eq '') { $cols = 80; }
  193: 	    my $rows = &Apache::lonxml::get_param('rows',$parstack,$safeeval);
  194: 	    if ( $rows eq '') { $rows = 16; }
  195: 	    my $addchars=&Apache::lonxml::get_param('addchars',$parstack,$safeeval);
  196: 	    $result='';
  197: 	    if ($addchars) {
  198: 		$result.=&addchars('HWVAL_'.$resid,$addchars);
  199: 	    }
  200:             my $textareaclass = 'class="LC_richDetectHtml spellchecked"';
  201: 	    $result.= '<textarea wrap="hard" name="HWVAL_'.$resid.'" id="HWVAL_'.$resid.'" ' .
  202: 		      'rows="'.$rows.'" cols="'.$cols.'" '.$textareaclass
  203: 		      . "onblur='\$(this).spellchecker(\"check\")'"
  204: 		      .'>'.
  205:                       &HTML::Entities::encode($oldresponse,'<>&"');
  206: 	    if ($oldresponse ne '') {
  207: 
  208: 		#get rid of any startup text if the user has already responded
  209: 		&Apache::lonxml::get_all_text("/textfield",$parser,$style);
  210: 	    }
  211: 	} else {
  212: 	    #show past answer in the essayresponse case
  213: 	    if ($oldresponse =~ /\S/
  214: 		&& &Apache::londefdef::is_inside_of($tagstack,
  215: 						    'essayresponse') ) {
  216: 		$result='<table class="LC_pastsubmission"><tr><td>'.
  217: 		    $oldresponse.'</td></tr></table>';
  218: 	    }
  219: 	    #get rid of any startup text
  220: 	    &Apache::lonxml::get_all_text("/textfield",$parser,$style);
  221: 	}
  222:     } elsif ($target eq 'grade') {
  223: 	my $seedtext=&Apache::lonxml::get_all_text("/textfield",$parser,
  224: 						   $style);
  225: 	if ($seedtext eq $env{'form.HWVAL_'.$resid}) {
  226: 	    # if the seed text is still there it wasn't a real submission
  227: 	    $env{'form.HWVAL_'.$resid}='';
  228: 	}
  229:     } elsif ($target eq 'edit') {
  230: 	$result.=&Apache::edit::tag_start($target,$token);
  231: 	$result.=&Apache::edit::text_arg('Rows:','rows',$token,4);
  232: 	$result.=&Apache::edit::text_arg('Columns:','cols',$token,4);
  233: 	$result.=&Apache::edit::text_arg
  234: 	    ('Click-On Texts (comma sep):','addchars',$token,10);
  235: 	my $bodytext=&Apache::lonxml::get_all_text("/textfield",$parser,
  236: 						   $style);
  237: 	$result.=&Apache::edit::editfield($token->[1],$bodytext,'Text you want to appear by default:',80,2);
  238:     } elsif ($target eq 'modified') {
  239: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  240: 						     $safeeval,'rows','cols',
  241: 						     'addchars');
  242: 	if ($constructtag) {
  243: 	    $result = &Apache::edit::rebuild_tag($token);
  244: 	} else {
  245: 	    $result=$token->[4];
  246: 	}
  247: 	$result.=&Apache::edit::modifiedfield("/textfield",$parser);
  248:     } elsif ($target eq 'tex') {
  249: 	my $number_of_lines = &Apache::lonxml::get_param('rows',$parstack,$safeeval);
  250: 	my $width_of_box = &Apache::lonxml::get_param('cols',$parstack,$safeeval);
  251: 	if ($$tagstack[-2] eq 'essayresponse' and $Apache::lonhomework::type eq 'exam') {
  252: 	    $result = '\fbox{\fbox{\parbox{\textwidth-5mm}{';
  253: 	    for (my $i=0;$i<int $number_of_lines*2;$i++) {$result.='\strut \\\\ ';}
  254: 	    $result.='\strut \\\\\strut \\\\\strut \\\\\strut \\\\}}}';
  255: 	} else {
  256: 	    my $fieldname = $env{'request.symb'}.
  257:                     '&part_'. $Apache::inputtags::part.
  258:                     '&textresponse'.
  259:                     '&HWVAL_' . $Apache::inputtags::response['-1'];
  260:             $result.='\TextField[name='.$fieldname.',multiline=true,height=6\baselineskip,width=270,borderwidth=0,backgroundcolor={.85
  261:                 .85 .85}]\\';
  262: 	}
  263:     }
  264:     return $result;
  265: }
  266: 
  267: sub end_textfield {
  268:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  269:     my $result;
  270:     if ($target eq 'web') {
  271: 	$Apache::lonxml::evaluate++;
  272: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  273: 	    return "</textarea>";
  274: 	}
  275:     } elsif ($target eq 'edit') {
  276: 	$result=&Apache::edit::end_table();
  277:     }
  278:     &end_input;
  279:     return $result;
  280: }
  281: 
  282: sub exam_score_line {
  283:     my ($target) = @_;
  284: 
  285:     my $result;
  286:     if ($target eq 'tex') {
  287: 	my $repetition = &Apache::response::repetition();
  288: 	$result.='\begin{enumerate}';
  289: 	if ($env{'request.state'} eq "construct" ) {$result.='\item[\strut]';}
  290: 	foreach my $i (0..$repetition-1) {
  291: 	    $result.='\item[\textbf{'.
  292: 		($Apache::lonxml::counter+$i).
  293: 		'}.]\textit{Leave blank on scoring form}\vskip 0 mm';
  294: 	}
  295: 	$result.= '\end{enumerate}';
  296:     }
  297: 
  298:     return $result;
  299: }
  300: 
  301: sub exam_box {
  302:     my ($target) = @_;
  303:     my $result;
  304: 
  305:     if ($target eq 'tex') {
  306: 	$result .= '\fbox{\fbox{\parbox{\textwidth-5mm}{\strut\\\\\strut\\\\\strut\\\\\strut\\\\}}}';
  307: 	$result .= &exam_score_line($target);
  308:     } elsif ($target eq 'web') {
  309: 	my $id=$Apache::inputtags::response[-1];
  310: 	$result.= '<br /><br />
  311:                    <textarea name="HWVAL_'.$id.'" rows="4" cols="50">
  312:                    </textarea> <br /><br />';
  313:     }
  314:     return $result;
  315: }
  316: 
  317: sub needs_exam_box {
  318:     my ($tagstack) = @_;
  319:     my @tags = ('formularesponse',
  320: 		'stringresponse',
  321: 		'reactionresponse',
  322: 		'organicresponse',
  323: 		);
  324: 
  325:     foreach my $tag (@tags) {
  326: 	if (grep(/\Q$tag\E/,@$tagstack)) {
  327: 	    return 1;
  328: 	}
  329:     }
  330:     return 0;
  331: }
  332: 
  333: sub start_textline {
  334:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  335:     my $result = "";
  336:     my $input_id = &start_input($parstack,$safeeval);
  337:     if ($target eq 'web') {
  338: 	$Apache::lonxml::evaluate--;
  339: 	my $partid=$Apache::inputtags::part;
  340: 	my $id=$Apache::inputtags::response[-1];
  341: 	if (!&Apache::response::show_answer()) {
  342: 	    my $size = &Apache::lonxml::get_param('size',$parstack,$safeeval);
  343: 	    my $maxlength;
  344: 	    if ($size eq '') { $size=20; } else {
  345: 		if ($size < 20) {
  346: 		    $maxlength = ' maxlength="'.$size.'"';
  347: 		}
  348: 	    }
  349:             my ($oldresponse,$newvariation);
  350:             if ((($Apache::lonhomework::history{"resource.$partid.type"} eq 'randomizetry') ||
  351:                  ($Apache::lonhomework::type eq 'randomizetry')) &&
  352:                  ($Apache::inputtags::status[-1] eq 'CAN_ANSWER')) {
  353:                 if ($env{'form.'.$partid.'.rndseed'} ne
  354:                     $Apache::lonhomework::history{"resource.$partid.rndseed"}) {
  355:                     $newvariation = 1;
  356:                 }
  357:             }
  358:             unless ($newvariation) {
  359: 	        $oldresponse = $Apache::lonhomework::history{"resource.$partid.$id.submission"};
  360: 	        &Apache::lonxml::debug("oldresponse $oldresponse is ".ref($oldresponse));
  361: 	        if (ref($oldresponse) eq 'ARRAY') {
  362: 		    $oldresponse = $oldresponse->[$#Apache::inputtags::inputlist];
  363: 	        }
  364: 	        $oldresponse = &HTML::Entities::encode($oldresponse,'<>&"');
  365:                 $oldresponse =~ s/^\s+//;
  366:                 $oldresponse =~ s/\s+$//;
  367:                 $oldresponse =~ s/\s+/ /g;
  368:             }
  369: 	    if ($Apache::lonhomework::type ne 'exam') {
  370: 		my $addchars=&Apache::lonxml::get_param('addchars',$parstack,$safeeval);
  371: 		$result='';
  372: 		if ($addchars) {
  373: 		    $result.=&addchars('HWVAL_'.$id,$addchars);
  374: 		}
  375: 		my $readonly=&Apache::lonxml::get_param('readonly',$parstack,
  376: 							$safeeval);
  377: 		if (lc($readonly) eq 'yes' 
  378: 		    || $Apache::inputtags::status[-1] eq 'CANNOT_ANSWER') {
  379: 		    $readonly=' readonly="readonly" ';
  380: 		} else {
  381: 		    $readonly='';
  382: 		}
  383: 		my $name = 'HWVAL_'.$id;
  384: 		if ($Apache::inputtags::status[-1] eq 'CANNOT_ANSWER') {
  385: 		    $name = "none";
  386: 		}
  387: 		$result.= '<input onkeydown="javascript:setSubmittedPart(\''.$partid.'\');" type="text" '.$readonly.' name="'.$name.'" value="'.
  388: 		    $oldresponse.'" class="spellchecked"  size="'.$size.'"'.$maxlength.'
  389:                     onblur=' . "'\$(this).spellchecker(\"check\")'"  . '/>';
  390: 	    }
  391: 	    if ($Apache::lonhomework::type eq 'exam'
  392: 		&& &needs_exam_box($tagstack)) {
  393: 		$result.=&exam_box($target);
  394: 	    }
  395: 	} else {
  396: 	    #right or wrong don't show what was last typed in.
  397: 	    my $count = scalar(@Apache::inputtags::inputlist)-1;
  398: 	    $result='<b>'.$Apache::inputtags::answertxt{$id}[$count].'</b>';
  399: 	    #$result='';
  400: 	}
  401:     } elsif ($target eq 'edit') {
  402: 	$result=&Apache::edit::tag_start($target,$token);
  403: 	$result.=&Apache::edit::text_arg('Size:','size',$token,'5').
  404: 	    &Apache::edit::text_arg('Click-On Texts (comma sep):',
  405: 				    'addchars',$token,10);
  406:         $result.=&Apache::edit::select_arg('Readonly:','readonly',
  407: 					   ['no','yes'],$token);
  408: 	$result.=&Apache::edit::end_row();
  409: 	$result.=&Apache::edit::end_table();
  410:     } elsif ($target eq 'modified') {
  411: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  412: 						     $safeeval,'size',
  413: 						     'addchars','readonly');
  414: 	if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
  415:     } elsif ($target eq 'tex' 
  416: 	     && $Apache::lonhomework::type ne 'exam') {
  417: 	my $size = &Apache::lonxml::get_param('size',$parstack,$safeeval);
  418: 	if ($size != 0) {$size=$size*2; $size.=' mm';} else {$size='40 mm';}
  419: 	if ($env{'form.pdfFormFields'} eq 'yes'
  420:             && $Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  421:             my $fieldname = $env{'request.symb'}.
  422:                                  '&part_'. $Apache::inputtags::part.
  423:                                  '&textresponse'.
  424:                                  '&HWVAL_' . $Apache::inputtags::response['-1'];
  425:             $result='\textField{'.$fieldname.'}{'.$size.'}{12 bp}';
  426:         } else {
  427:             $result='\framebox['.$size.'][s]{\tiny\strut}';
  428:         }
  429:     } elsif ($target eq 'tex' 
  430: 	     && $Apache::lonhomework::type eq 'exam'
  431: 	     && &needs_exam_box($tagstack)) {
  432: 	$result.=&exam_box($target);
  433:     }
  434:     return $result;
  435: }
  436: 
  437: sub end_textline {
  438:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  439:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  440:     elsif ($target eq 'edit') { return ('','no'); }
  441:     &end_input();
  442:     return "";
  443: }
  444: 
  445: sub start_hiddenline {
  446:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  447:     my $result = "";
  448:     my $input_id = &start_input($parstack,$safeeval);
  449:     if ($target eq 'web') {
  450: 	$Apache::lonxml::evaluate--;
  451: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  452: 	    my $partid=$Apache::inputtags::part;
  453: 	    my $id=$Apache::inputtags::response[-1];
  454: 	    my $oldresponse = $Apache::lonhomework::history{"resource.$partid.$id.submission"};
  455: 	    if (ref($oldresponse) eq 'ARRAY') {
  456: 		$oldresponse = $oldresponse->[$#Apache::inputtags::inputlist];
  457: 	    }
  458: 	    $oldresponse = &HTML::Entities::encode($oldresponse,'<>&"');
  459: 
  460: 	    if ($Apache::lonhomework::type ne 'exam') {
  461: 		$result= '<input type="hidden" name="HWVAL_'.$id.'" value="'.
  462: 		    $oldresponse.'" />';
  463: 	    }
  464: 	}
  465:     } elsif ($target eq 'edit') {
  466: 	$result=&Apache::edit::tag_start($target,$token);
  467: 	$result.=&Apache::edit::end_table;
  468:     }
  469: 
  470:     if ( ($target eq 'web' || $target eq 'tex')
  471: 	 && $Apache::lonhomework::type eq 'exam'
  472: 	 && &needs_exam_box($tagstack)) {
  473: 	$result.=&exam_box($target);
  474:     }
  475:     return $result;
  476: }
  477: 
  478: sub end_hiddenline {
  479:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  480:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  481:     elsif ($target eq 'edit') { return ('','no'); }
  482:     &end_input();
  483:     return "";
  484: }
  485: 
  486: 
  487: sub start_hiddensubmission {
  488:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  489:     my $result = "";
  490:     my $input_id = &start_input($parstack,$safeeval);
  491:     if ($target eq 'web') {
  492:         $Apache::lonxml::evaluate--;
  493:         if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  494:             my $partid=$Apache::inputtags::part;
  495:             my $id=$Apache::inputtags::response[-1];
  496:             if ($Apache::lonhomework::type ne 'exam') {
  497:                 my $value = &Apache::lonxml::get_param('value',$parstack,$safeeval);
  498:                 $value = &HTML::Entities::encode($value,'<>&"');
  499:                 $result= '<input type="hidden" name="HWVAL_'.$id.'" value="'.$value.'" />';
  500:             }
  501:         }
  502:     } elsif ($target eq 'edit') {
  503:         $result=&Apache::edit::tag_start($target,$token);
  504:         $result.=&Apache::edit::text_arg('Value:','value',$token,'15');
  505:         $result.=&Apache::edit::end_row();
  506:         $result.=&Apache::edit::end_table();
  507:     } elsif ($target eq 'modified') {
  508:         my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  509:                                                      $safeeval,'value');
  510:         if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
  511:     }
  512: 
  513:     if ( ($target eq 'web' || $target eq 'tex')
  514:          && $Apache::lonhomework::type eq 'exam'
  515:          && &needs_exam_box($tagstack)) {
  516:         $result.=&exam_box($target);
  517:     }
  518:     return $result;
  519: }
  520: 
  521: sub end_hiddensubmission {
  522:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  523:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  524:     elsif ($target eq 'edit') { return ('','no'); }
  525:     &end_input();
  526:     return "";
  527: }
  528: 
  529: =pod
  530: 
  531: =item file_selector()
  532: 
  533: $part -> partid
  534: $id -> responseid
  535: $uploadefiletypes -> comma seperated list of extensions allowed or * for any
  536: $which -> 'uploadonly'  -> only newly uploaded files
  537:           'portfolioonly' -> only allow files from portfolio
  538:           'both' -> allow files from either location
  539: $extratext -> additional text to go between the link and the input box
  540: $maxfilesize -> maximum cumulative filesize for submitted files (in MB).
  541: returns a table row <tr> 
  542: 
  543: =cut
  544: 
  545: sub file_selector {
  546:     my ($part,$id,$uploadedfiletypes,$which,$extratext,$maxfilesize)=@_;
  547:     if (!$uploadedfiletypes) { return ''; }
  548: 
  549:     my $jspart=$part;
  550:     $jspart=~s/\./_/g;
  551: 
  552:     my $result;
  553:     my $current_files_display = &current_file_submissions($part,$id);
  554:     my $addfiles;
  555:     if ($current_files_display) {
  556:         $result .= &Apache::lonhtmlcommon::row_title(&mt('Currently submitted files')).
  557:                    $current_files_display.
  558:                    &Apache::lonhtmlcommon::row_closure();
  559:         $addfiles = &mt('Submit other file(s)');
  560:     } else {
  561:         $addfiles = &mt('Choose file(s) to submit');
  562:     }
  563:     $result .= &Apache::lonhtmlcommon::row_title($addfiles);
  564:     my $constraints;
  565:     if ($uploadedfiletypes ne '*') {
  566: 	$constraints =
  567: 	    &mt('Allowed filetypes: [_1]','<b>'.$uploadedfiletypes.'</b>').'<br />';
  568:     }
  569:     if ($maxfilesize) {
  570:         $constraints .= &mt('Combined size of all files not to exceed: [_1] MB[_2].',
  571:                         '<b>'.$maxfilesize.'</b>').'<br />';
  572:     }
  573:     if ($constraints) {
  574:         $result .= $constraints.'<br />';
  575:     }
  576:     if ($which eq 'uploadonly' || $which eq 'both') { 
  577: 	$result.=&mt('Submit a file: (only one file per submission)').
  578: 	    ' <br /><input type="file" size="50" name="HWFILE'.
  579: 	    $jspart.'_'.$id.'" id="HWFILE'.$jspart.'_'.$id.'" /><br />';
  580:     }
  581:     if ( $which eq 'both') {
  582: 	$result.='<br />'.'<strong>'.&mt('OR:').'</strong><br />';
  583:     }
  584:     if ($which eq 'portfolioonly' || $which eq 'both') {
  585:         my $symb = $env{'request.symb'};
  586:         (undef,undef,my $res)=&Apache::lonnet::decode_symb($symb);
  587:         my $showsymb;
  588:         # If resource is a .task and URL is unencrypted, include symb in query string
  589:         # for url opened in portfolio file selection window. Can be used to override
  590:         # blocking of portfolio access resulting from an exam event in a different course. 
  591:         if ($res =~ /\.task$/i) {
  592:             my $encsymb = &Apache::lonenc::check_encrypt($symb);
  593:             if ($symb eq $encsymb) {
  594:                 $showsymb = $symb;
  595:             }
  596:         }
  597: 	$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"))'."'".'>'.
  598: 	    &mt('Select Portfolio Files: (one or more files per submission)').'</a><br />'.
  599: 	    '<input type="text" size="50" name="HWPORT'.$jspart.'_'.$id.'" value="" />'.
  600: 	    '<br />';
  601: 
  602:     }
  603:     $result.=&Apache::lonhtmlcommon::row_closure(1);
  604:     return $result;
  605: }
  606: 
  607: sub current_file_submissions {
  608:     my ($part,$id) = @_;
  609:     my $jspart=$part;
  610:     $jspart=~s/\./_/g;
  611:     my $uploadedfile=$Apache::lonhomework::history{"resource.$part.$id.uploadedfile"};
  612:     my $portfiles=$Apache::lonhomework::history{"resource.$part.$id.portfiles"};
  613:     return if (($uploadedfile eq '') && ($portfiles !~/[^\s]/));
  614:     my $header = &Apache::loncommon::start_data_table().
  615:                  &Apache::loncommon::start_data_table_header_row();
  616:     if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  617:         $header .= '<th>'.&mt('Delete?').'</th>';
  618:     }
  619:     $header .=   '<th>'.&mt('File').'</th>'.
  620:                  '<th>'.&mt('Size (MB)').'</th>'.
  621:                  '<th>'.&mt('Last Modified').'</th>'.
  622:                  &Apache::loncommon::end_data_table_header_row();
  623:     my (undef,$crsid,$udom,$uname)=&Apache::lonnet::whichuser();
  624:     my ($cdom,$cnum) = ($crsid =~ /^($LONCAPA::match_domain)_($LONCAPA::match_courseid)$/);
  625:     my ($result,$header_shown,%okfiles,%rows,%legacy,@bad_file_list);
  626:     if ($uploadedfile) {
  627:         my $url=$Apache::lonhomework::history{"resource.$part.$id.uploadedurl"};
  628:         my $link = &HTML::Entities::encode($url,'<>&"');
  629:         my ($path,$name) = ($url =~ m{^(/uploaded/\Q$udom\E/\Q$uname\E/essayresponse.*/)([^/]+)$});
  630:         my ($status,$hashref,$error) =
  631:             &current_file_info($url,$link,$name,$path);
  632:         if ($status eq 'ok') {
  633:             push(@{$okfiles{$name}},$url);
  634:             $rows{$url} = $hashref;
  635:             $legacy{$url} = 1;
  636:             &Apache::lonxml::extlink($url);
  637:             &Apache::lonnet::allowuploaded('/adm/essayresponse',$url);
  638:         } else {
  639:             push(@bad_file_list,$error);
  640:         }
  641:     }
  642:     if ($portfiles =~ /[^\s]/) {
  643:         my $prefix = "/uploaded/$udom/$uname/portfolio";
  644:         foreach my $file (split(/\s*,\s*/,&unescape($portfiles))) {
  645:             my ($path,$name) = ($file =~ m{^(.*/)([^/]+)$});
  646:             my $url = $prefix.$path.$name;
  647:             my $uploadedfile = &HTML::Entities::encode($url,'<>&"');
  648:             my ($status,$hashref,$error) =
  649:                 &current_file_info($url,$uploadedfile,$name,$path);
  650:             if ($status eq 'ok') {
  651:                 push(@{$okfiles{$name}},$url);
  652:                 $rows{$url} = $hashref;
  653:             } else {
  654:                 push(@bad_file_list,$error);
  655:             }
  656:         }
  657:     }
  658:     my $num = 0;
  659:     foreach my $name (sort(keys(%okfiles))) {
  660:         if (ref($okfiles{$name}) eq 'ARRAY') {
  661:             foreach my $url (@{$okfiles{$name}}) {
  662:                 if (ref($rows{$url}) eq 'HASH') {
  663:                     my $link = $rows{$url}{link};
  664:                     my $portfile = $rows{$url}{path}.$rows{$url}{name};
  665:                     $portfile = &HTML::Entities::encode($portfile,'<>&"');
  666:                     if ($link) {
  667:                         my $icon=&Apache::loncommon::icon($url);
  668:                         unless ($header_shown) {
  669:                             $result .= $header;
  670:                             $header_shown = 1;
  671:                         }
  672:                         $result.=
  673:                             &Apache::loncommon::start_data_table_row()."\n";
  674:                         if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  675:                             $result .=
  676:                                  '<td valign="bottom"><input type="checkbox" name="HWFILE'.$jspart.'_'.$id.'_delete"'.
  677:                                  ' value="'.$portfile.'" id="HWFILE'.$jspart.'_'.$id.'_'.$num.'_delete" /></td>'."\n";
  678:                             $num ++;
  679:                         }
  680:                         my $showname = $rows{$url}{path}.$name;
  681:                         if ($legacy{$url}) {
  682:                             $showname = $name.' '.&mt('not in portfolio');
  683:                         }
  684:                         $result .= 
  685:                             '<td><a href="'.$link.'"><img src="'.$icon.
  686:                             '" border="0" alt="" />'.$showname.'</a></td>'."\n".
  687:                             '<td align="right" valign="bottom">'.$rows{$url}{size}.'</td>'."\n".
  688:                             '<td align="right" valign="bottom">'.$rows{$url}{lastmodified}.'</td>'."\n".
  689:                             &Apache::loncommon::end_data_table_row();
  690:                     }
  691:                 }
  692:             }
  693:         }
  694:     }
  695:     if ($header_shown) {
  696:         $result .= &Apache::loncommon::end_data_table();
  697:         if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  698:             $result .= '<br /><span class="LC_warning">'.
  699:                        &mt('Exclude existing file(s) from grading by checking the "Delete?" checkbox(es) and clicking "Submit Answer"').'</span>';
  700:         }
  701:     }
  702:     if (@bad_file_list) {
  703:         my $bad_files = '<span class="LC_filename">'.
  704:             join('</span>, <span class="LC_filename">',@bad_file_list).
  705:             '</span>';
  706:         $result.='<p class="LC_error">'.
  707:                  &mt("These file(s) don't exist: [_1]",$bad_files).
  708:                  '</p>';
  709:     }
  710:     return $result;
  711: }
  712: 
  713: sub current_file_info {
  714:     my ($url,$uploadedfile,$name,$path) = @_;
  715:     my ($status,$error,%info);
  716:     my @stat = &Apache::lonnet::stat_file($url);
  717:     if ((@stat) && ($stat[0] ne 'no_such_dir')) {
  718:         my ($lastmod,$size);
  719:         if ($stat[9] =~ /^\d+$/) {
  720:             $lastmod = &Apache::lonlocal::locallocaltime($stat[9]);
  721:         }
  722:         $size = $stat[7]/(1024*1024);
  723:         $size = sprintf("%.3f",$size);
  724:         %info = (
  725:                     link         => $uploadedfile,
  726:                     name         => $name,
  727:                     path         => $path,
  728:                     size         => $size,
  729:                     lastmodified => $lastmod,
  730:                 );
  731:         $status = 'ok';
  732:     } else {
  733:         &Apache::lonnet::logthis("bad file is $url");
  734:         my $icon=&Apache::loncommon::icon($url);
  735:         $error = '<a href="'.$url.'"><img src="'.$icon.
  736:                  '" border="0" />'.$uploadedfile.'</a>';
  737:     }
  738:     return ($status,\%info,$error);
  739: }
  740: 
  741: sub valid_award {
  742:     my ($award) =@_;
  743:     foreach my $possibleaward ('EXTRA_ANSWER','MISSING_ANSWER', 'ERROR',
  744: 			       'NO_RESPONSE',
  745: 			       'TOO_LONG', 'UNIT_INVALID_INSTRUCTOR',
  746: 			       'UNIT_INVALID_STUDENT', 'UNIT_IRRECONCIBLE',
  747: 			       'UNIT_FAIL', 'NO_UNIT',
  748: 			       'UNIT_NOTNEEDED', 'WANTED_NUMERIC',
  749: 			       'BAD_FORMULA', 'NOT_FUNCTION', 'WRONG_FORMAT', 
  750:                                'INTERNAL_ERROR', 'SIG_FAIL', 'INCORRECT', 
  751: 			       'MISORDERED_RANK', 'INVALID_FILETYPE',
  752:                                'EXCESS_FILESIZE', 'FILENAME_INUSE', 
  753: 			       'DRAFT', 'SUBMITTED', 'SUBMITTED_CREDIT', 
  754:                                'ANONYMOUS', 'ANONYMOUS_CREDIT',
  755:                                'ASSIGNED_SCORE', 'APPROX_ANS',
  756: 			       'EXACT_ANS','COMMA_FAIL') {
  757: 	if ($award eq $possibleaward) { return 1; }
  758:     }
  759:     return 0;
  760: }
  761: 
  762: {
  763:     my @awards = ('EXTRA_ANSWER', 'MISSING_ANSWER', 'ERROR', 'NO_RESPONSE',
  764: 		  'TOO_LONG',
  765: 		  'UNIT_INVALID_INSTRUCTOR', 'UNIT_INVALID_STUDENT',
  766: 		  'UNIT_IRRECONCIBLE', 'UNIT_FAIL', 'NO_UNIT',
  767: 		  'UNIT_NOTNEEDED', 'WANTED_NUMERIC', 'BAD_FORMULA',  'NOT_FUNCTION', 
  768:                   'WRONG_FORMAT', 'INTERNAL_ERROR',
  769: 		  'COMMA_FAIL', 'SIG_FAIL', 'INCORRECT', 'MISORDERED_RANK',
  770: 		  'INVALID_FILETYPE', 'EXCESS_FILESIZE', 'FILENAME_INUSE', 
  771:                   'DRAFT', 'SUBMITTED',
  772:                   'SUBMITTED_CREDIT', 'ANONYMOUS', 'ANONYMOUS_CREDIT',
  773:                   'ASSIGNED_SCORE', 'APPROX_ANS', 'EXACT_ANS');
  774:     my $i=0;
  775:     my %fwd_awards = map { ($_,$i++) } @awards;
  776:     my $max=scalar(@awards);
  777:     @awards=reverse(@awards);
  778:     $i=0;
  779:     my %rev_awards = map { ($_,$i++) } @awards;
  780: 
  781: sub awarddetail_to_awarded {
  782:     my ($awarddetail) = @_;
  783:     if ($awarddetail eq 'EXACT_ANS'
  784: 	|| $awarddetail eq 'APPROX_ANS') {
  785: 	return 1;
  786:     }
  787:     return 0;
  788: }
  789: 
  790: sub hide_award {
  791:     my ($award) = @_;
  792:     if (&Apache::lonhomework::show_no_problem_status()) {
  793: 	return 1;
  794:     }
  795:     if ($award =~
  796: 	/^(?:EXACT_ANS|APPROX_ANS|SUBMITTED|SUBMITTED_CREDIT|ANONYMOUS|ANONYMOUS_CREDIT|ASSIGNED_SCORE|INCORRECT)/) {
  797: 	return 1;
  798:     }
  799:     return 0;
  800: }
  801: 
  802: sub finalizeawards {
  803:     my ($awardref,$msgref,$nameref,$reverse,$final_scantron)=@_;
  804:     my $result;
  805:     if ($#$awardref == -1) { $result = "NO_RESPONSE"; }
  806:     if ($result eq '' ) {
  807: 	my $blankcount;
  808: 	foreach my $award (@$awardref) {
  809: 	    if ($award eq '') {
  810: 		$result='MISSING_ANSWER';
  811: 		$blankcount++;
  812: 	    }
  813: 	}
  814: 	if ($blankcount == ($#$awardref + 1)) {
  815: 	    return ('NO_RESPONSE');
  816: 	}
  817:     }
  818: 
  819:     if ($Apache::lonxml::internal_error) { $result='INTERNAL_ERROR'; }
  820: 
  821:     if (!$final_scantron && defined($result)) { return ($result); }
  822: 
  823:     # if in scantron mode, if the award for any response is 
  824:     # assigned score, then the part gets an assigned score
  825:     if ($final_scantron 
  826: 	&& grep {$_ eq 'ASSIGNED_SCORE'} (@$awardref)) {
  827: 	return ('ASSIGNED_SCORE');
  828:     }
  829: 
  830:     # if in scantron mode, if the award for any response is 
  831:     # correct and there are non-correct responses,
  832:     # then the part gets an assigned score
  833:     if ($final_scantron 
  834: 	&& (grep { $_ eq 'EXACT_ANS' ||
  835: 		   $_ eq 'APPROX_ANS'  } (@$awardref))
  836: 	&& (grep { $_ ne 'EXACT_ANS' &&
  837: 		   $_ ne 'APPROX_ANS'  } (@$awardref))) {
  838: 	return ('ASSIGNED_SCORE');
  839:     }
  840:     # these awards are ordered from most important error through best correct
  841:     my $awards = (!$reverse) ? \%fwd_awards : \%rev_awards ;
  842: 
  843:     my $best = $max;
  844:     my $j=0;
  845:     my $which;
  846:     foreach my $award (@$awardref) {
  847: 	if ($awards->{$award} < $best) {
  848: 	    $best  = $awards->{$award};
  849: 	    $which = $j;
  850: 	}
  851: 	$j++;
  852:     }
  853: 
  854:     if (defined($which)) {
  855: 	if (ref($nameref)) {
  856: 	    return ($$awardref[$which],$$msgref[$which],$$nameref[$which]);
  857: 	} else {
  858: 	    return ($$awardref[$which],$$msgref[$which]);
  859: 	}
  860:     }
  861:     return ('ERROR',undef);
  862: }
  863: }
  864: 
  865: sub decideoutput {
  866:     my ($award,$awarded,$awardmsg,$solved,$previous,$target,$nocorrect)=@_;
  867: 
  868:     my $message='';
  869:     my $button=0;
  870:     my $previousmsg;
  871:     my $css_class='orange';
  872:     my $added_computer_text=0;
  873:     my %possible_class =
  874: 	( 'correct'         => 'LC_answer_correct',
  875: 	  'charged_try'     => 'LC_answer_charged_try',
  876: 	  'not_charged_try' => 'LC_answer_not_charged_try',
  877: 	  'no_grade'        => 'LC_answer_no_grade',
  878: 	  'no_message'      => 'LC_no_message',
  879: 	  );
  880: 
  881:     my $part = $Apache::inputtags::part;
  882:     my $tohandgrade = &Apache::lonnet::EXT("resource.$part.handgrade");
  883:     my $handgrade = ('yes' eq lc($tohandgrade)); 
  884: #
  885: # Should "Computer's Answer" be displayed?
  886: # Should not be displayed if still answerable,
  887: # if the problem is handgraded,
  888: # or if the problem does not give a correct answer
  889: #
  890:     
  891:     my $computer = ($handgrade || $nocorrect)? ''
  892: 	                       : " ".&mt("Computer's answer now shown above.");
  893:     &Apache::lonxml::debug("handgrade has :$handgrade:");
  894: 
  895:     if ($previous) { $previousmsg=&mt('You have entered that answer before'); }
  896:     
  897:     if ($solved =~ /^correct/) {
  898:         $css_class=$possible_class{'correct'};
  899: 	$message=&mt('You are correct.');
  900: 	if ($awarded < 1 && $awarded > 0) {
  901: 	    $message=&mt('You are partially correct.');
  902: 	    $css_class=$possible_class{'not_charged_try'};
  903: 	} elsif ($awarded < 1) {
  904: 	    $message=&mt('Incorrect.');
  905: 	    $css_class=$possible_class{'charged_try'};
  906: 	}
  907: 	if ($handgrade || 
  908:             ($env{'request.filename'}=~/\/res\/lib\/templates\/(examupload|DropBox).problem$/)) {
  909: 	    $message = &mt("A score has been assigned.");
  910: 	    $added_computer_text=1;
  911: 	} else {
  912: 	    if ($target eq 'tex') {
  913: 		$message = '\textbf{'.$message.'}';
  914: 	    } else {
  915: 		$message = "<b>".$message."</b>";
  916: 		$message.= $computer;
  917: 	    }
  918: 	    $added_computer_text=1;
  919: 	    if ($awarded > 0) {
  920: 		my ($symb) = &Apache::lonnet::whichuser();
  921: 		if (($symb ne '') 
  922: 		    &&
  923: 		    ($env{'course.'.$env{'request.course.id'}.
  924: 			      '.disable_receipt_display'} ne 'yes') &&
  925:                     ($Apache::lonhomework::type ne 'practice')) { 
  926: 		    $message.=(($target eq 'web')?'<br />':' ').
  927: 			&mt('Your receipt no. is [_1]',
  928: 			    (&Apache::lonnet::receipt($Apache::inputtags::part).
  929: 			     (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'')));
  930: 		}
  931: 	    }
  932: 	}
  933:         if ($awarded >= 1) {
  934:             $button=0;
  935:         } elsif (&Apache::lonnet::EXT("resource.$part.retrypartial") !~/^1|on|yes$/i) {
  936:             $button=0;
  937:         } else {
  938:             $button=1;
  939:         }
  940: 	$previousmsg='';
  941:     } elsif ($solved =~ /^excused/) {
  942: 	if ($target eq 'tex') {
  943: 	    $message = ' \textbf{'.&mt('You are excused from the problem.').'} ';
  944: 	} else {
  945: 	    $message = "<b>".&mt('You are excused from the problem.')."</b>";
  946: 	}
  947: 	$css_class=$possible_class{'charged_try'};
  948: 	$button=0;
  949: 	$previousmsg='';
  950:     } elsif ($award eq 'EXACT_ANS' || $award eq 'APPROX_ANS' ) {
  951: 	if ($solved =~ /^incorrect/ || $solved eq '') {
  952: 	    $message = &mt("Incorrect").".";
  953: 	    $css_class=$possible_class{'charged_try'};
  954: 	    $button=1;
  955: 	} else {
  956: 	    if ($target eq 'tex') {
  957: 		$message = '\textbf{'.&mt('You are correct.').'}';
  958: 	    } else {
  959: 		$message = "<b>".&mt('You are correct.')."</b>";
  960: 		$message.= $computer;
  961: 	    }
  962: 	    $added_computer_text=1;
  963: 	    if  ($awarded > 0 
  964: 		 && $env{'course.'.
  965: 			     $env{'request.course.id'}.
  966: 			     '.disable_receipt_display'} ne 'yes') { 
  967: 		$message.=(($target eq 'web')?'<br />':' ').
  968: 		    &mt('Your receipt is [_1]',
  969: 			(&Apache::lonnet::receipt($Apache::inputtags::part).
  970: 			 (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'')));
  971: 	    }
  972: 	    $css_class=$possible_class{'correct'};
  973: 	    $button=0;
  974: 	    $previousmsg='';
  975: 	}
  976:     } elsif ($award eq 'NO_RESPONSE') {
  977: 	$message = '';
  978: 	$css_class=$possible_class{'no_feedback'};
  979: 	$button=1;
  980:     } elsif ($award eq 'EXTRA_ANSWER') {
  981: 	$message = &mt('Some extra items were submitted.');
  982: 	$css_class=$possible_class{'not_charged_try'};
  983: 	$button = 1;
  984:     } elsif ($award eq 'MISSING_ANSWER') {
  985: 	$message = &mt('Some items were not submitted.');
  986:         if ($target ne 'tex') {
  987:            $message .= &Apache::loncommon::help_open_topic('Some_Items_Were_Not_Submitted');
  988:         }
  989: 	$css_class=$possible_class{'not_charged_try'};
  990: 	$button = 1;
  991:     } elsif ($award eq 'ERROR') {
  992: 	$message = &mt('An error occurred while grading your answer.');
  993: 	$css_class=$possible_class{'not_charged_try'};
  994: 	$button = 1;
  995:     } elsif ($award eq 'TOO_LONG') {
  996: 	$message = &mt("The submitted answer was too long.");
  997: 	$css_class=$possible_class{'not_charged_try'};
  998: 	$button=1;
  999:     } elsif ($award eq 'WANTED_NUMERIC') {
 1000: 	$message = &mt("This question expects a numeric answer.");
 1001: 	$css_class=$possible_class{'not_charged_try'};
 1002: 	$button=1;
 1003:     } elsif ($award eq 'MISORDERED_RANK') {
 1004:         $message = &mt('You have provided an invalid ranking.');
 1005:         if ($target ne 'tex') {
 1006:             $message.=' '.&mt('Please refer to [_1]',&Apache::loncommon::help_open_topic('Ranking_Problems',&mt('help on ranking problems')));
 1007:         }
 1008: 	$css_class=$possible_class{'not_charged_try'};
 1009: 	$button=1;
 1010:     } elsif ($award eq 'EXCESS_FILESIZE') {
 1011:         $message = &mt('Submission won\'t be graded. The combined size of submitted files exceeded the amount allowed.');
 1012:         $css_class=$possible_class{'not_charged_try'};
 1013:         $button=1;
 1014:     } elsif ($award eq 'FILENAME_INUSE') {
 1015:         $message = &mt('You have already uploaded a file with that filename.');
 1016:         if ($target eq 'tex') {
 1017:             $message.= "\\\\\n";
 1018:         } else {
 1019:             $message .= '<br />';
 1020:         }
 1021:         $message .= &mt('Please use a different file name.');
 1022:         $css_class=$possible_class{'not_charged_try'};
 1023:         $button=1;
 1024:     } elsif ($award eq 'INVALID_FILETYPE') {
 1025: 	$message = &mt("Submission won't be graded. The type of file submitted is not allowed.");
 1026: 	$css_class=$possible_class{'not_charged_try'};
 1027: 	$button=1;
 1028:     } elsif ($award eq 'SIG_FAIL') {
 1029: 	my ($used,$min,$max)=split(':',$awardmsg);
 1030: 	my $word = ($used < $min) ? 'more' : 'fewer';
 1031: 	$message = &mt("Submission not graded. Use $word digits.",$used);
 1032: 	$css_class=$possible_class{'not_charged_try'};
 1033: 	$button=1;
 1034:     } elsif ($award eq 'UNIT_INVALID_INSTRUCTOR') {
 1035: 	$message = &mt('Error in instructor specifed unit. This error has been reported to the instructor.', $awardmsg);
 1036: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
 1037: 	$css_class=$possible_class{'not_charged_try'};
 1038: 	$button=1;
 1039:     } elsif ($award eq 'UNIT_INVALID_STUDENT') {
 1040: 	$message = &mt('Unable to interpret units. Computer reads units as "[_1]".',&markup_unit($awardmsg,$target));
 1041: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
 1042: 	$css_class=$possible_class{'not_charged_try'};
 1043: 	$button=1;
 1044:     } elsif ($award eq 'UNIT_FAIL' || $award eq 'UNIT_IRRECONCIBLE') {
 1045: 	$message = &mt('Incompatible units. No conversion found between "[_1]" and the required units.',&markup_unit($awardmsg,$target));
 1046: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
 1047: 	$css_class=$possible_class{'not_charged_try'};
 1048: 	$button=1;
 1049:     } elsif ($award eq 'UNIT_NOTNEEDED') {
 1050: 	$message = &mt('Only a number required. Computer reads units of "[_1]".',&markup_unit($awardmsg,$target));
 1051: 	$css_class=$possible_class{'not_charged_try'};
 1052: 	$button=1;
 1053:     } elsif ($award eq 'NO_UNIT') {
 1054: 	$message = &mt("Units required").'.';
 1055: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units')};
 1056: 	$css_class=$possible_class{'not_charged_try'};
 1057: 	$button=1;
 1058:     } elsif ($award eq 'COMMA_FAIL') {
 1059: 	$message = &mt("Proper comma separation is required").'.';
 1060: 	$css_class=$possible_class{'not_charged_try'};
 1061: 	$button=1;
 1062:     } elsif ($award eq 'BAD_FORMULA') {
 1063: 	$message = &mt("Unable to understand formula").'.';
 1064:         if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Formula_Answers')};
 1065: 	$css_class=$possible_class{'not_charged_try'};
 1066: 	$button=1;
 1067:     } elsif ($award eq 'NOT_FUNCTION') {
 1068:         $message = &mt("Not a function").'.';
 1069:         $css_class=$possible_class{'not_charged_try'};
 1070:         $button=1;
 1071:     } elsif ($award eq 'WRONG_FORMAT') {
 1072:         $message = &mt("Wrong format").'.';
 1073:         $css_class=$possible_class{'not_charged_try'};
 1074:         $button=1;
 1075:      } elsif ($award eq 'INTERNAL_ERROR') {
 1076:         $message = &mt("An internal error occurred while processing your answer. Please try again later.");
 1077:         $css_class=$possible_class{'not_charged_try'};
 1078:         $button=1;
 1079:     } elsif ($award eq 'INCORRECT') {
 1080: 	$message = &mt("Incorrect").'.';
 1081: 	$css_class=$possible_class{'charged_try'};
 1082: 	$button=1;
 1083:     } elsif ($award eq 'SUBMITTED') {
 1084: 	$message = &mt("Your submission has been recorded.");
 1085: 	$css_class=$possible_class{'no_grade'};
 1086: 	$button=1;
 1087:     } elsif ($award eq 'SUBMITTED_CREDIT') {
 1088:         $message = &mt("Your submission has been recorded, and credit awarded.");
 1089:         $css_class=$possible_class{'correct'};
 1090:         $button=1;
 1091:     } elsif ($award eq 'ANONYMOUS') {
 1092:         $message = &mt("Your anonymous submission has been recorded.");
 1093:         $css_class=$possible_class{'no_grade'};
 1094:         $button=1;
 1095:     } elsif ($award eq 'ANONYMOUS_CREDIT') {
 1096:         $message = &mt("Your anonymous submission has been recorded, and credit awarded.");
 1097:         $css_class=$possible_class{'correct'};
 1098:         $button=1;
 1099:     } elsif ($award eq 'DRAFT') {
 1100: 	$message = &mt("Copy saved but not submitted.");
 1101: 	$css_class=$possible_class{'not_charged_try'};
 1102: 	$button=1;
 1103:     } elsif ($award eq 'ASSIGNED_SCORE') {
 1104: 	$message = &mt("A score has been assigned.");
 1105: 	$css_class=$possible_class{'correct'};
 1106: 	$button=0;
 1107:     } elsif ($award eq '') {
 1108: 	if ($handgrade && $Apache::inputtags::status[-1] eq 'SHOW_ANSWER') {
 1109: 	    $message = &mt("Nothing submitted.");
 1110: 	    $css_class=$possible_class{'charged_try'};
 1111: 	} else {
 1112: 	    $css_class=$possible_class{'not_charged_try'};
 1113: 	}
 1114: 	$button=1;
 1115:     } else {
 1116: 	$message = &mt("Unknown message").": $award";
 1117: 	$button=1;
 1118:     }
 1119:     my (undef,undef,$domain,$user)=&Apache::lonnet::whichuser();
 1120:     foreach my $resid(@Apache::inputtags::response){
 1121:         if ($Apache::lonhomework::history{"resource.$part.$resid.handback"}) {
 1122:             if ($target eq 'tex') {
 1123:                 $message.= "\\\\\n";
 1124:             } else {
 1125:                 $message.='<br />';
 1126:             }
 1127: 	    my @files = split(/\s*,\s*/,
 1128: 			      $Apache::lonhomework::history{"resource.$part.$resid.handback"});
 1129: 	    my $file_msg;
 1130: 	    foreach my $file (@files) {
 1131:                 if ($target eq 'tex') {
 1132:                     $file_msg.= "\\\\\n".$file;
 1133:                 } else {
 1134:                     $file_msg.= '<br /><a href="/uploaded/'."$domain/$user".'/'.$file.'">'.$file.'</a>';
 1135:                 }
 1136: 	    }
 1137: 	    $message .= &mt('Returned file(s): [_1]',$file_msg);
 1138:             if ($target eq 'tex') {
 1139:                 $message.= "\\\\\n";
 1140:             } else {
 1141:                 $message.='<br />';
 1142:             }
 1143: 	}
 1144:     }
 1145: 
 1146:     if (&Apache::lonhomework::hide_problem_status()
 1147: 	&& $Apache::inputtags::status[-1] ne 'SHOW_ANSWER'
 1148: 	&& &hide_award($award)) {
 1149:         $message = &mt("Answer Submitted: Your final submission will be graded after the due date.");
 1150:         my @interval= &Apache::lonnet::EXT("resource.$part.interval");
 1151:         if ($interval[0] =~ /\d+/) {
 1152:             my $first_access=&Apache::lonnet::get_first_access($interval[1]);
 1153:             if (defined($first_access)) {
 1154:                 my $due_date= &Apache::lonnet::EXT("resource.$part.duedate");
 1155:                 unless (($due_date) && ($due_date < $first_access + $interval[0])) { 
 1156:                     $message = &mt("Answer Submitted: Your final submission will be graded when the time limit is reached.");
 1157:                 }
 1158:             }
 1159:         }
 1160: 	$css_class=$possible_class{'no_grade'};
 1161: 	$button=1;
 1162:     }
 1163:     if ($Apache::inputtags::status[-1] eq 'SHOW_ANSWER' && 
 1164: 	!$added_computer_text && $target ne 'tex') {
 1165: 	$message.= $computer;
 1166: 	$added_computer_text=1;
 1167:     }
 1168:     if ($Apache::lonhomework::type eq 'practice') {
 1169:        if ($target eq 'web') {
 1170:            $message .= '<br />';
 1171:        } else {
 1172:            $message .= ' ';      
 1173:        }
 1174:        $message.=&mt('Submissions to practice problems are not permanently recorded.');
 1175:     }
 1176:     return ($button,$css_class,$message,$previousmsg);
 1177: }
 1178: 
 1179: sub markup_unit {
 1180:     my ($unit,$target)=@_;
 1181:     if ($target eq 'tex') {
 1182: 	return '\texttt{'.&Apache::lonxml::latex_special_symbols($unit).'}'; 
 1183:     } else {
 1184: 	return "<tt>".$unit."</tt>";
 1185:     }
 1186: }
 1187: 
 1188: sub removealldata {
 1189:     my ($id)=@_;
 1190:     foreach my $key (keys(%Apache::lonhomework::results)) {
 1191: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
 1192: 	    &Apache::lonxml::debug("Removing $key");
 1193: 	    delete($Apache::lonhomework::results{$key});
 1194: 	}
 1195:     }
 1196: }
 1197: 
 1198: sub hidealldata {
 1199:     my ($id)=@_;
 1200:     foreach my $key (keys(%Apache::lonhomework::results)) {
 1201: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
 1202: 	    &Apache::lonxml::debug("Hidding $key");
 1203: 	    my $newkey=$key;
 1204: 	    $newkey=~s/^(resource\.\Q$id\E\.[^\.]+\.)(.*)$/${1}hidden${2}/;
 1205: 	    $Apache::lonhomework::results{$newkey}=
 1206: 		$Apache::lonhomework::results{$key};
 1207: 	    delete($Apache::lonhomework::results{$key});
 1208: 	}
 1209:     }
 1210: }
 1211: 
 1212: sub setgradedata {
 1213:     my ($award,$msg,$id,$previously_used) = @_;
 1214:     if ($Apache::lonhomework::scantronmode && 
 1215: 	&Apache::lonnet::validCODE($env{'form.CODE'})) {
 1216: 	$Apache::lonhomework::results{"resource.CODE"}=$env{'form.CODE'};
 1217:     } elsif ($Apache::lonhomework::scantronmode && 
 1218: 	     $env{'form.CODE'} eq '' &&
 1219: 	     $Apache::lonhomework::history{"resource.CODE"} ne '') {
 1220: 	$Apache::lonhomework::results{"resource.CODE"}='';
 1221:     }
 1222: 
 1223:     if (!$Apache::lonhomework::scantronmode &&
 1224: 	$Apache::inputtags::status['-1'] ne 'CAN_ANSWER' &&
 1225: 	$Apache::inputtags::status['-1'] ne 'CANNOT_ANSWER') {
 1226: 	$Apache::lonhomework::results{"resource.$id.afterduedate"}=$award;
 1227: 	return '';
 1228:     } elsif ( $Apache::lonhomework::history{"resource.$id.awarded"} < 1
 1229: 	      || $Apache::lonhomework::scantronmode 
 1230: 	      || &Apache::lonhomework::hide_problem_status()  ) {
 1231:         # the student doesn't already have it correct,
 1232: 	# or we are in a mode (scantron orno problem status) where a correct 
 1233:         # can become incorrect
 1234: 	# handle assignment of tries and solved status
 1235: 	my $solvemsg;
 1236: 	if ($Apache::lonhomework::scantronmode) {
 1237: 	    $solvemsg='correct_by_scantron';
 1238: 	} else {
 1239: 	    $solvemsg='correct_by_student';
 1240: 	}
 1241: 	if ($Apache::lonhomework::history{"resource.$id.afterduedate"}) {
 1242: 	    $Apache::lonhomework::results{"resource.$id.afterduedate"}='';
 1243: 	}
 1244: 	if ( $award eq 'ASSIGNED_SCORE') {
 1245: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1246: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1247: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1248: 		$solvemsg;
 1249: 	    my $numawards=scalar(@Apache::inputtags::response);
 1250: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1251: 	    foreach my $res (@Apache::inputtags::response) {
 1252: 		if (defined($Apache::lonhomework::results{"resource.$id.$res.awarded"})) {
 1253: 		    $Apache::lonhomework::results{"resource.$id.awarded"}+=
 1254: 			$Apache::lonhomework::results{"resource.$id.$res.awarded"};
 1255: 		} else {
 1256: 		    $Apache::lonhomework::results{"resource.$id.awarded"}+=
 1257: 			&awarddetail_to_awarded($Apache::lonhomework::results{"resource.$id.$res.awarddetail"});
 1258: 		}
 1259: 	    }
 1260: 	    if ($numawards > 0) {
 1261: 		$Apache::lonhomework::results{"resource.$id.awarded"}/=
 1262: 		    $numawards;
 1263: 	    }
 1264: 	} elsif ( $award eq 'APPROX_ANS' || $award eq 'EXACT_ANS' ) {
 1265: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1266: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1267: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1268: 		$solvemsg;
 1269: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
 1270:         } elsif ( $award eq 'SUBMITTED_CREDIT' ) {
 1271:             $Apache::lonhomework::results{"resource.$id.tries"} =
 1272:                 $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1273:             $Apache::lonhomework::results{"resource.$id.solved"} =
 1274:                 'credit_attempted';
 1275:             $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
 1276:         }  elsif ( $award eq 'ANONYMOUS_CREDIT' ) {
 1277:             $Apache::lonhomework::results{"resource.$id.tries"} =
 1278:                 $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1279:             $Apache::lonhomework::results{"resource.$id.solved"} =
 1280:                 'credit_attempted';
 1281:             $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
 1282: 	} elsif ( $award eq 'INCORRECT' ) {
 1283: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1284: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1285: 	    if (&Apache::lonhomework::hide_problem_status()
 1286: 		|| $Apache::lonhomework::scantronmode) {
 1287: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1288: 	    }
 1289: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1290: 		'incorrect_attempted';
 1291: 	} elsif ( $award eq 'SUBMITTED' ) {
 1292: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1293: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1294: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1295: 		'ungraded_attempted';
 1296:         }  elsif ( $award eq 'ANONYMOUS' ) {
 1297:             $Apache::lonhomework::results{"resource.$id.tries"} =
 1298:                 $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1299:             $Apache::lonhomework::results{"resource.$id.solved"} =
 1300:                 'ungraded_attempted';
 1301: 	} elsif ( $award eq 'DRAFT' ) {
 1302: 	    $Apache::lonhomework::results{"resource.$id.solved"} = '';
 1303: 	} elsif ( $award eq 'NO_RESPONSE' ) {
 1304: 	    #no real response so delete any data that got stored
 1305: 	    &removealldata($id);
 1306: 	    return '';
 1307: 	} else {
 1308: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1309: 		'incorrect_attempted';
 1310: 	    if (&Apache::lonhomework::show_no_problem_status()
 1311: 		|| $Apache::lonhomework::scantronmode) {
 1312: 		$Apache::lonhomework::results{"resource.$id.tries"} =
 1313: 		    $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1314: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1315: 	    }
 1316: 
 1317: 	    if (&Apache::lonhomework::show_some_problem_status()) {
 1318: 		# clear out the awarded if they had gotten it wrong/right
 1319: 		# and are now in an error mode	
 1320: 		$Apache::lonhomework::results{"resource.$id.awarded"} = '';
 1321: 	    }
 1322: 	}
 1323: 	if (defined($msg)) {
 1324: 	    $Apache::lonhomework::results{"resource.$id.awardmsg"} = $msg;
 1325: 	}
 1326: 	# did either of the overall awards chage? If so ignore the 
 1327: 	# previous check
 1328: 	if (($Apache::lonhomework::results{"resource.$id.awarded"} eq
 1329: 	     $Apache::lonhomework::history{"resource.$id.awarded"}) &&
 1330: 	    ($Apache::lonhomework::results{"resource.$id.solved"} eq
 1331: 	     $Apache::lonhomework::history{"resource.$id.solved"})) {
 1332: 	    # check if this was a previous submission if it was delete the
 1333: 	    # unneeded data and update the previously_used attribute
 1334: 	    if ( $previously_used eq 'PREVIOUSLY_USED') {
 1335: 		if (&Apache::lonhomework::show_problem_status()) {
 1336: 		    delete($Apache::lonhomework::results{"resource.$id.tries"});
 1337: 		    $Apache::lonhomework::results{"resource.$id.previous"} = '1';
 1338: 		}
 1339: 	    } elsif ( $previously_used eq 'PREVIOUSLY_LAST') {
 1340: 		#delete all data as they student didn't do anything, but save
 1341: 		#the list of collaborators.
 1342: 		&removealldata($id);
 1343: 		#and since they didn't do anything we were never here
 1344: 		return '';
 1345: 	    } else {
 1346: 		$Apache::lonhomework::results{"resource.$id.previous"} = '0';
 1347: 	    }
 1348: 	}
 1349:     } elsif ( $Apache::lonhomework::history{"resource.$id.awarded"} == 1 ) {
 1350: 	#delete all data as they student already has it correct
 1351: 	&removealldata($id);
 1352: 	#and since they didn't do anything we were never here
 1353: 	return '';
 1354:     }
 1355:     $Apache::lonhomework::results{"resource.$id.award"} = $award;
 1356:     if ($award eq 'SUBMITTED') {
 1357: 	&Apache::response::add_to_gradingqueue();
 1358:     }
 1359:     $Apache::lonhomework::results{"resource.$id.type"} = $Apache::lonhomework::type;
 1360:     $Apache::lonhomework::results{"resource.$id.duedate"} = &Apache::lonnet::EXT("resource.$id.duedate");
 1361:     $Apache::lonhomework::results{"resource.$id.hinttries"} = &Apache::lonnet::EXT("resource.$id.hinttries");
 1362:     $Apache::lonhomework::results{"resourse.$id.version"} = &Apache::lonnet::usedversion(); 
 1363: }
 1364: 
 1365: sub find_which_previous {
 1366:     my ($version) = @_;
 1367:     my $part = $Apache::inputtags::part;
 1368:     my (@previous_version);
 1369:     foreach my $resp (@Apache::inputtags::response) {
 1370: 	my $key = "$version:resource.$part.$resp.submission";
 1371: 	my $submission = $Apache::lonhomework::history{$key};
 1372: 	my %previous = &Apache::response::check_for_previous($submission,
 1373: 							     $part,$resp,
 1374: 							     $version);
 1375: 	push(@previous_version,$previous{'version'});
 1376:     }
 1377:     return &previous_match(\@previous_version,
 1378: 			   scalar(@Apache::inputtags::response));
 1379: }
 1380: 
 1381: sub previous_match {
 1382:     my ($previous_array,$count) = @_;
 1383:     my $match = 0;
 1384:     my @matches;
 1385:     foreach my $versionar (@$previous_array) {
 1386: 	foreach my $version (@$versionar) {
 1387: 	    $matches[$version]++;
 1388: 	}
 1389:     }
 1390:     my $which=0;
 1391:     foreach my $elem (@matches) {
 1392: 	if ($elem eq $count) {
 1393: 	    $match=1;
 1394: 	    last;
 1395: 	}
 1396: 	$which++;
 1397:     }
 1398:     return ($match,$which);
 1399: }
 1400: 
 1401: sub grade {
 1402:     my ($target) = @_;
 1403:     my $id = $Apache::inputtags::part;
 1404:     my $response='';
 1405:     if ( defined $env{'form.submitted'}) {
 1406: 	my (@awards,@msgs);
 1407: 	foreach $response (@Apache::inputtags::response) {
 1408: 	    &Apache::lonxml::debug("looking for response.$id.$response.awarddetail");
 1409: 	    my $value=$Apache::lonhomework::results{"resource.$id.$response.awarddetail"};
 1410: 	    &Apache::lonxml::debug("keeping $value from $response for $id");
 1411: 	    push (@awards,$value);
 1412: 	    $value=$Apache::lonhomework::results{"resource.$id.$response.awardmsg"};
 1413: 	    &Apache::lonxml::debug("got message $value from $response for $id");
 1414: 	    push (@msgs,$value);
 1415: 	}
 1416: 	my ($finalaward,$msg) = 
 1417: 	    &finalizeawards(\@awards,\@msgs,undef,undef,
 1418: 			    $Apache::lonhomework::scantronmode);
 1419: 	my $previously_used;
 1420: 	if ( $#Apache::inputtags::previous eq $#awards ) {
 1421: 	    my ($match) =
 1422: 		&previous_match(\@Apache::inputtags::previous_version,
 1423: 				scalar(@Apache::inputtags::response));
 1424: 
 1425: 	    if ($match) {
 1426: 		$previously_used = 'PREVIOUSLY_LAST';
 1427: 		foreach my $value (@Apache::inputtags::previous) {
 1428: 		    if ($value eq 'PREVIOUSLY_USED' ) {
 1429: 			$previously_used = $value;
 1430: 			last;
 1431: 		    }
 1432: 		}
 1433: 	    }
 1434: 	}
 1435: 	&Apache::lonxml::debug("final award $finalaward, $previously_used, message $msg");
 1436: 	&setgradedata($finalaward,$msg,$id,$previously_used);
 1437:     }
 1438:     return '';
 1439: }
 1440: 
 1441: sub get_grade_messages {
 1442:     my ($id,$prefix,$target,$status,$nocorrect) = @_;
 1443: # nocorrect suppresses "Computer's answer now shown above"
 1444:     my ($message,$latemessage,$trystr,$previousmsg);
 1445:     my $showbutton = 1;
 1446: 
 1447:     my $award = $Apache::lonhomework::history{"$prefix.award"};
 1448:     my $awarded = $Apache::lonhomework::history{"$prefix.awarded"};
 1449:     my $solved = $Apache::lonhomework::history{"$prefix.solved"};
 1450:     my $previous = $Apache::lonhomework::history{"$prefix.previous"};
 1451:     my $awardmsg = $Apache::lonhomework::history{"$prefix.awardmsg"};
 1452:     &Apache::lonxml::debug("Found Award |$award|$solved|$awardmsg");
 1453:     if ( $award ne '' || $solved ne '' || $status eq 'SHOW_ANSWER') {
 1454: 	&Apache::lonxml::debug('Getting message');
 1455: 	($showbutton,my $css_class,$message,$previousmsg) =
 1456: 	    &decideoutput($award,$awarded,$awardmsg,$solved,$previous,
 1457: 			  $target,(($status eq 'CAN_ANSWER') || $nocorrect));
 1458: 	if ($target eq 'tex') {
 1459: 	    $message='\vskip 2 mm '.$message.' ';
 1460: 	} else {
 1461: 	    $message="<td class=\"$css_class\">$message</td>";
 1462: 	    if ($previousmsg) {
 1463: 		$previousmsg="<td class=\"LC_answer_previous\">$previousmsg</td>";
 1464: 	    }
 1465: 	}
 1466:     }
 1467:     my $tries = $Apache::lonhomework::history{"$prefix.tries"};
 1468:     my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
 1469:     &Apache::lonxml::debug("got maxtries of :$maxtries:");
 1470:     #if tries are set to negative turn off the Tries/Button and messages
 1471:     if (defined($maxtries) && $maxtries < 0) { return ''; }
 1472:     if ( $tries eq '' ) { $tries = '0'; }
 1473:     if ( $maxtries eq '' ) { $maxtries = '2'; } 
 1474:     if ( $maxtries eq 'con_lost' ) { $maxtries = '0'; } 
 1475:     my $tries_text= &get_tries_text();
 1476:     if ($showbutton) {
 1477: 	if ($target eq 'tex') {
 1478: 	    if ($env{'request.state'} ne "construct"
 1479: 		&& $Apache::lonhomework::type ne 'exam'
 1480: 		&& $env{'form.suppress_tries'} ne 'yes') {
 1481: 		$trystr ='{\vskip 1 mm \small '
 1482:                         .&mt('[_1]'.$tries_text.'[_2] [_3]'
 1483: 				,'\textit{','}',$tries.'/'.$maxtries ) 
 1484:                         .'} \vskip 2 mm';
 1485: 	    } else {
 1486: 		$trystr = '\vskip 0 mm ';
 1487: 	    }
 1488: 	} else {
 1489: 	    my $trial =$tries;
 1490: 	    if ($Apache::lonhomework::parsing_a_task) {
 1491: 	    } elsif($env{'request.state'} ne 'construct') {
 1492: 		$trial.="/".&Apache::lonhtmlcommon::direct_parm_link($maxtries,$env{'request.symb'},'maxtries',$id,$target);
 1493: 	    } else {
 1494: 		if (defined($Apache::inputtags::params{'maxtries'})) {
 1495: 		    $trial.="/".$Apache::inputtags::params{'maxtries'};
 1496: 		}
 1497: 	    }
 1498: 	    $trystr = '<td><span class="LC_nobreak">'.&mt($tries_text.' [_1]',$trial).'</span></td>';
 1499: 	}
 1500:     }
 1501: 
 1502:     if ($Apache::lonhomework::history{"$prefix.afterduedate"}) {
 1503: 	#last submissions was after due date
 1504: 	$latemessage=&mt(' The last submission was after the Due Date ');;
 1505: 	if ($target eq 'web') {
 1506: 	    $latemessage='<td class="LC_answer_late">'.$latemessage.'</td>';
 1507: 	}
 1508:     }
 1509:     return ($previousmsg,$latemessage,$message,$trystr,$showbutton);
 1510: }
 1511: 
 1512: sub gradestatus {
 1513:     my ($id,$target,$no_previous) = @_;
 1514:     my $showbutton = 1;
 1515:     my $message = '';
 1516:     my $latemessage = '';
 1517:     my $trystr='';
 1518:     my $button='';
 1519:     my $previousmsg='';
 1520: 
 1521:     my $status = $Apache::inputtags::status['-1'];
 1522:     &Apache::lonxml::debug("gradestatus has :$status:");
 1523:     if ( $status ne 'CLOSED' 
 1524: 	 && $status ne 'UNAVAILABLE' 
 1525: 	 && $status ne 'INVALID_ACCESS' 
 1526: 	 && $status ne 'NEEDS_CHECKIN' 
 1527: 	 && $status ne 'NOT_IN_A_SLOT'
 1528:          && $status ne 'RESERVABLE'
 1529:          && $status ne 'RESERVABLE_LATER'
 1530:          && $status ne 'NOTRESERVABLE') {
 1531: 
 1532: 	if ($status eq 'SHOW_ANSWER') {
 1533:             $showbutton = 0;
 1534:         }
 1535: 
 1536: 	($previousmsg,$latemessage,$message,$trystr) =
 1537: 	    &get_grade_messages($id,"resource.$id",$target,$status,
 1538: 				$showbutton);
 1539: 	if ($status eq 'CANNOT_ANSWER') {
 1540: 	    $showbutton = 0;
 1541: 	}
 1542: 	if ( $status eq 'SHOW_ANSWER') {
 1543: 	    undef($previousmsg);
 1544: 	}
 1545: 	if ( $showbutton ) { 
 1546: 	    if ($target ne 'tex') {
 1547: 		$button = 
 1548:             '<input onmouseup="javascript:setSubmittedPart(\''.$id.'\');this.form.action+=\'#'.&escape($id).'\';"
 1549:                     type="submit" name="submit_'.$id.'"
 1550:                     value="'.&mt('Submit Answer').'" />';
 1551: 	    }
 1552: 	}
 1553: 
 1554:     }
 1555:     my $output= $previousmsg.$latemessage.$message.$trystr;
 1556:     if ($output =~ /^\s*$/) {
 1557: 	return $button;
 1558:     } else {
 1559: 	if ($target eq 'tex') {
 1560: 	    return $button.' \vskip 0 mm '.$output.' ';
 1561: 	} else {
 1562: 	    $output =
 1563: 		'<table><tr><td>'.$button.'</td>'.$output;
 1564: 	    if (!$no_previous) {
 1565: 		$output.='<td>'.&previous_tries($id,$target).'</td>';
 1566: 	    }
 1567: 	    $output.= '</tr></table>';
 1568: 	    return $output;
 1569: 	}
 1570:     }
 1571: }
 1572: 
 1573: sub previous_tries {
 1574:     my ($id,$target) = @_;
 1575:     my $output;
 1576:     my $status = $Apache::inputtags::status['-1'];
 1577: 
 1578:     my $count;
 1579:     my %count_lookup;
 1580:     my $lastrndseed;
 1581: 
 1582:     foreach my $i (1..$Apache::lonhomework::history{'version'}) {
 1583: 	my $prefix = $i.":resource.$id";
 1584:         my $is_anon; 
 1585:         if (defined($env{'form.grade_symb'})) {
 1586:             if (($Apache::lonhomework::history{"$prefix.type"} eq 'anonsurvey') || 
 1587:                 ($Apache::lonhomework::history{"$prefix.type"} eq 'anonsurveycred')) {
 1588:                 $is_anon = 1;
 1589:             }
 1590:         }
 1591: 	next if (!exists($Apache::lonhomework::history{"$prefix.award"}));
 1592: 	$count++;
 1593: 	$count_lookup{$i} = $count;
 1594:         my $curr_rndseed = $Apache::lonhomework::history{"$prefix.rndseed"};
 1595: 	my ($previousmsg,$latemessage,$message,$trystr);
 1596: 
 1597: 	($previousmsg,$latemessage,$message,$trystr) =
 1598: 	    &get_grade_messages($id,"$prefix",$target,$status);
 1599: 
 1600: 	if ($previousmsg ne '') {
 1601: 	    my ($match,$which) = &find_which_previous($i);
 1602: 	    $message=$previousmsg;
 1603: 	    my $previous = $count_lookup{$which};
 1604: 	    $message =~ s{(</td>)}{ as submission \# $previous $1};
 1605: 	} elsif ($Apache::lonhomework::history{"$prefix.tries"}) {
 1606: 	    if (!(&Apache::lonhomework::hide_problem_status()
 1607: 		  && $Apache::inputtags::status[-1] ne 'SHOW_ANSWER')
 1608: 		&& $Apache::lonhomework::history{"$prefix.solved"} =~/^correct/
 1609: 		) {
 1610: 		
 1611:                 my $txt_correct = &mt('Correct');
 1612:                 my $awarded = $Apache::lonhomework::history{"$prefix.awarded"};
 1613:                 if ($awarded < 1 && $awarded > 0) {
 1614:                     $txt_correct=&mt('Partially Correct');
 1615:                 } elsif ($awarded < 1) {
 1616:                     if ($awarded eq '') {
 1617:                         $txt_correct='';
 1618:                     } else {
 1619:                         $txt_correct=&mt('Incorrect');
 1620:                     }
 1621:                 }
 1622: 		$message =~ s{(<td.*?>)(.*?)(</td>)}
 1623:                              {$1 <strong>$txt_correct</strong>. $3}s;
 1624: 	    }
 1625:             my $trystr = "(".&mt('Try [_1]',$Apache::lonhomework::history{"$prefix.tries"}).")";
 1626:             if (($curr_rndseed || $lastrndseed) && ($i > 1)) {
 1627:                 if ($curr_rndseed ne $lastrndseed) {
 1628:                     $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>';
 1629:                 }
 1630:             } 
 1631: 	    $message =~ s{(</td>)}{ $trystr $1};
 1632: 	}
 1633: 	my ($class) = ($message =~ m{<td.*class="([^"]*)"}); #"
 1634: 	$message =~ s{(<td.*?>)}{<td>};
 1635: 	
 1636: 
 1637: 	$output.='<tr class="'.$class.'">';
 1638: 	$output.='<td align="center">'.$count.'</td>';
 1639: 	$output.=$message;
 1640: 
 1641: 	foreach my $resid (@Apache::inputtags::response) {
 1642: 	    my $prefix = $prefix.".$resid";
 1643: 	    if (exists($Apache::lonhomework::history{"$prefix.submission"})) {
 1644: 		my $submission =
 1645: 		    $Apache::inputtags::submission_display{"$prefix.submission"};
 1646: 		if (!defined($submission)) {
 1647: 		    $submission = 
 1648: 			$Apache::lonhomework::history{"$prefix.submission"};
 1649: 		}
 1650:                 if ($is_anon) {
 1651:                     $output.='<td>'.&mt('(only shown to submitter)').'</td>';
 1652:                 } else {
 1653: 		    $output.='<td>'.$submission.'</td>';
 1654:                 }
 1655: 	    } else {
 1656: 		$output.='<td></td>';
 1657: 	    }
 1658: 	}
 1659: 	$output.=&Apache::loncommon::end_data_table_row()."\n";
 1660:         $lastrndseed = $curr_rndseed;
 1661:     }
 1662:     return if ($output eq '');
 1663:     my $headers = 
 1664: 	'<tr>'.'<th>'.&mt('Submission #').'</th><th>'.&mt('Try').
 1665: 	'</th><th colspan="'.scalar(@Apache::inputtags::response).'">'.
 1666: 	&mt('Submitted Answer').'</th>';
 1667:     $output ='<table class="LC_prior_tries">'.$headers.$output.'</table>';
 1668: 
 1669:     my $tries_text = &get_tries_text('link');
 1670:     my $prefix = $env{'form.request.prefix'};
 1671:     $prefix =~ tr{.}{_};
 1672:     my $function_name = "LONCAPA_previous_tries_".$prefix.
 1673: 	$Apache::lonxml::curdepth.'_'.$env{'form.counter'};
 1674:     my $result = &Apache::loncommon::modal_adhoc_window($function_name,420,410,$output,&mt($tries_text))."<br />";
 1675:     return $result;
 1676: }
 1677: 
 1678: sub get_tries_text {
 1679:     my ($context) = @_;
 1680:     my $tries_text;
 1681:     if ($context eq 'link') {
 1682:         $tries_text = 'Previous Tries';
 1683:     } else {
 1684:         $tries_text = 'Tries';
 1685:     }
 1686:     if ( $Apache::lonhomework::type eq 'survey' ||
 1687:          $Apache::lonhomework::type eq 'surveycred' ||
 1688:          $Apache::lonhomework::type eq 'anonsurvey' ||
 1689:          $Apache::lonhomework::type eq 'anonsurveycred' ||
 1690:          $Apache::lonhomework::parsing_a_task) {
 1691:         if ($context eq 'link') {
 1692:             $tries_text = 'Previous Submissions';
 1693:         } else {
 1694:             $tries_text = 'Submissions';
 1695:         }
 1696:     }
 1697:     return $tries_text;
 1698: }
 1699: 
 1700: 1;
 1701: __END__
 1702: 
 1703: =pod
 1704: 
 1705: =back
 1706: 
 1707: =cut
 1708:  

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