File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.271.2.10: download - view: text, annotated - select for diffs
Tue Apr 30 21:45:47 2013 UTC (11 years, 1 month ago) by raeburn
Branches: version_2_10_X
- For 2.10.
  - Backport 1.317.

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

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