File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.271.2.3: download - view: text, annotated - select for diffs
Tue Dec 21 14:56:03 2010 UTC (13 years, 5 months ago) by raeburn
Branches: version_2_10_X
- Line in rev 1.274 missed in 1.271.2.2 backport.

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

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