File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.274: download - view: text, annotated - select for diffs
Sun Dec 19 02:58:16 2010 UTC (13 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- New Question Type - randomizetry
  - Only display submission from last try in textbox or textarea for new
    try, if rndseed for last try is the same as for current try.
  - Include item in "Try" column in previous tries display to show when a
    new problem variation was used.
  - Store questiontype in resource.$partid.type in Apache::lonhomework::results.

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

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