File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.251: download - view: text, annotated - select for diffs
Sun Dec 7 23:40:57 2008 UTC (15 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
Detect if there were timeouts or other internal errors during grading.

Do not charge a try, allow student to enter same answer again.

    1: # The LearningOnline Network with CAPA
    2: # input  definitons
    3: #
    4: # $Id: inputtags.pm,v 1.251 2008/12/07 23:40:57 www 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::lonlocal;
   57: use Apache::lonnet;
   58: use LONCAPA;
   59:  
   60: 
   61: BEGIN {
   62:     &Apache::lonxml::register('Apache::inputtags',('hiddenline','textfield','textline'));
   63: }
   64: 
   65: =pod
   66: 
   67: =item initialize_inputtags()
   68: 
   69: Initializes a set of global variables used during the parse of the problem.
   70: 
   71: @Apache::inputtags::input        - List of current input ids.
   72: @Apache::inputtags::inputlist    - List of all input ids seen this problem.
   73: @Apache::inputtags::response     - List of all current resopnse ids.
   74: @Apache::inputtags::responselist - List of all response ids seen this 
   75:                                      problem.
   76: @Apache::inputtags::hint         - List of all hint ids.
   77: @Apache::inputtags::hintlist     - List of all hint ids seen this problem.
   78: @Apache::inputtags::previous     - List describing if specific responseds
   79:                                      have been used
   80: @Apache::inputtags::previous_version - Submission responses were used in.
   81: $Apache::inputtags::part         - Current part id (valid only in 
   82:                                      <problem>)
   83:                                    0 if not in a part.
   84: @Apache::inputtags::partlist     - List of part ids seen in the current
   85:                                      <problem>
   86: @Apache::inputtags::status       - List of problem  statuses. First 
   87:                                    element is the status of the <problem>
   88:                                    the remainder are for individual <part>s.
   89: %Apache::inputtags::params       - Hash of defined parameters for the
   90:                                    current response.
   91: @Apache::inputtags::import       - List of all ids for <import> thes get
   92:                                    join()ed and prepended.
   93: @Apache::inputtags::importlist   - List of all import ids seen.
   94: $Apache::inputtags::response_with_no_part
   95:                                  - Flag set true if we have seen a response
   96:                                    that is not inside a <part>
   97: %Apache::inputtags::answertxt    - <*response> tags store correct
   98:                                    answer strings for display by <textline/>
   99:                                    in this hash.
  100: %Apache::inputtags::submission_display
  101:                                  - <*response> tags store improved display
  102:                                    of submission strings for display by part
  103:                                    end.
  104: 
  105: =cut
  106: 
  107: sub initialize_inputtags {
  108:     @Apache::inputtags::input=();
  109:     @Apache::inputtags::inputlist=();
  110:     @Apache::inputtags::response=();
  111:     @Apache::inputtags::responselist=();
  112:     @Apache::inputtags::hint=();
  113:     @Apache::inputtags::hintlist=();
  114:     @Apache::inputtags::previous=();
  115:     @Apache::inputtags::previous_version=();
  116:     $Apache::inputtags::part='';
  117:     @Apache::inputtags::partlist=();
  118:     @Apache::inputtags::status=();
  119:     %Apache::inputtags::params=();
  120:     @Apache::inputtags::import=();
  121:     @Apache::inputtags::importlist=();
  122:     $Apache::inputtags::response_with_no_part=0;
  123:     %Apache::inputtags::answertxt=();
  124:     %Apache::inputtags::submission_display=();
  125: }
  126: 
  127: sub check_for_duplicate_ids {
  128:     my %check;
  129:     foreach my $id (@Apache::inputtags::partlist,
  130: 		    @Apache::inputtags::responselist,
  131: 		    @Apache::inputtags::hintlist,
  132: 		    @Apache::inputtags::importlist) {
  133: 	$check{$id}++;
  134:     }
  135:     my @duplicates;
  136:     foreach my $id (sort(keys(%check))) {
  137: 	if ($check{$id} > 1) {
  138: 	    push(@duplicates,$id);
  139: 	}
  140:     }
  141:     if (@duplicates) {
  142: 	&Apache::lonxml::error("Duplicated ids found, problem will operate incorrectly. Duplicated ids seen: ",join(', ',@duplicates));
  143:     }
  144: }
  145: 
  146: sub start_input {
  147:     my ($parstack,$safeeval)=@_;
  148:     my $id = &Apache::lonxml::get_id($parstack,$safeeval);
  149:     push (@Apache::inputtags::input,$id);
  150:     push (@Apache::inputtags::inputlist,$id);
  151:     return $id;
  152: }
  153: 
  154: sub end_input {
  155:     pop @Apache::inputtags::input;
  156:     return '';
  157: }
  158: 
  159: sub addchars {
  160:     my ($fieldid,$addchars)=@_;
  161:     my $output='';
  162:     foreach (split(/\,/,$addchars)) {
  163: 	$output.='<a href="javascript:void(document.forms.lonhomework.'.
  164: 	    $fieldid.'.value+=\''.$_.'\')">'.$_.'</a> ';
  165:     }
  166:     return $output;
  167: }
  168: 
  169: sub start_textfield {
  170:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  171:     my $result = "";
  172:     my $id = &start_input($parstack,$safeeval);
  173:     my $resid=$Apache::inputtags::response[-1];
  174:     if ($target eq 'web') {
  175: 	$Apache::lonxml::evaluate--;
  176: 	my $partid=$Apache::inputtags::part;
  177: 	my $oldresponse = &HTML::Entities::encode($Apache::lonhomework::history{"resource.$partid.$resid.submission"},'<>&"');
  178: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  179: 	    my $cols = &Apache::lonxml::get_param('cols',$parstack,$safeeval);
  180: 	    if ( $cols eq '') { $cols = 80; }
  181: 	    my $rows = &Apache::lonxml::get_param('rows',$parstack,$safeeval);
  182: 	    if ( $rows eq '') { $rows = 16; }
  183: 	    my $addchars=&Apache::lonxml::get_param('addchars',$parstack,$safeeval);
  184: 	    $result='';
  185: 	    if ($addchars) {
  186: 		$result.=&addchars('HWVAL_'.$resid,$addchars);
  187: 	    }
  188: 	    &Apache::lonhtmlcommon::add_htmlareafields('HWVAL_'.$resid);
  189: 	    $result.= '<textarea wrap="hard" name="HWVAL_'.$resid.'" id="HWVAL_'.$resid.'" '.
  190: 		"rows=\"$rows\" cols=\"$cols\">".$oldresponse;
  191: 	    if ($oldresponse ne '') {
  192: 
  193: 		#get rid of any startup text if the user has already responded
  194: 		&Apache::lonxml::get_all_text("/textfield",$parser,$style);
  195: 	    }
  196: 	} else {
  197: 	    #show past answer in the essayresponse case
  198: 	    if ($oldresponse =~ /\S/
  199: 		&& &Apache::londefdef::is_inside_of($tagstack,
  200: 						    'essayresponse') ) {
  201: 		$result='<table class="LC_pastsubmission"><tr><td>'.
  202: 		    $oldresponse.'</td></tr></table>';
  203: 	    }
  204: 	    #get rid of any startup text
  205: 	    &Apache::lonxml::get_all_text("/textfield",$parser,$style);
  206: 	}
  207:     } elsif ($target eq 'grade') {
  208: 	my $seedtext=&Apache::lonxml::get_all_text("/textfield",$parser,
  209: 						   $style);
  210: 	if ($seedtext eq $env{'form.HWVAL_'.$resid}) {
  211: 	    # if the seed text is still there it wasn't a real submission
  212: 	    $env{'form.HWVAL_'.$resid}='';
  213: 	}
  214:     } elsif ($target eq 'edit') {
  215: 	$result.=&Apache::edit::tag_start($target,$token);
  216: 	$result.=&Apache::edit::text_arg('Rows:','rows',$token,4);
  217: 	$result.=&Apache::edit::text_arg('Columns:','cols',$token,4);
  218: 	$result.=&Apache::edit::text_arg
  219: 	    ('Click-On Texts (comma sep):','addchars',$token,10);
  220: 	my $bodytext=&Apache::lonxml::get_all_text("/textfield",$parser,
  221: 						   $style);
  222: 	$result.=&Apache::edit::editfield($token->[1],$bodytext,'Text you want to appear by default:',80,2);
  223:     } elsif ($target eq 'modified') {
  224: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  225: 						     $safeeval,'rows','cols',
  226: 						     'addchars');
  227: 	if ($constructtag) {
  228: 	    $result = &Apache::edit::rebuild_tag($token);
  229: 	} else {
  230: 	    $result=$token->[4];
  231: 	}
  232: 	$result.=&Apache::edit::modifiedfield("/textfield",$parser);
  233:     } elsif ($target eq 'tex') {
  234: 	my $number_of_lines = &Apache::lonxml::get_param('rows',$parstack,$safeeval);
  235: 	my $width_of_box = &Apache::lonxml::get_param('cols',$parstack,$safeeval);
  236: 	if ($$tagstack[-2] eq 'essayresponse' and $Apache::lonhomework::type eq 'exam') {
  237: 	    $result = '\fbox{\fbox{\parbox{\textwidth-5mm}{';
  238: 	    for (my $i=0;$i<int $number_of_lines*2;$i++) {$result.='\strut \\\\ ';}
  239: 	    $result.='\strut \\\\\strut \\\\\strut \\\\\strut \\\\}}}';
  240: 	} else {
  241: 	    my $TeXwidth=$width_of_box/80;
  242: 	    $result = '\vskip 1 mm \fbox{\fbox{\parbox{'.$TeXwidth.'\textwidth-5mm}{';
  243: 	    for (my $i=0;$i<int $number_of_lines*2;$i++) {$result.='\strut \\\\ ';}
  244: 	    $result.='}}}\vskip 2 mm ';
  245: 	}
  246:     }
  247:     return $result;
  248: }
  249: 
  250: sub end_textfield {
  251:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  252:     my $result;
  253:     if ($target eq 'web') {
  254: 	$Apache::lonxml::evaluate++;
  255: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  256: 	    return "</textarea>";
  257: 	}
  258:     } elsif ($target eq 'edit') {
  259: 	$result=&Apache::edit::end_table();
  260:     }
  261:     &end_input;
  262:     return $result;
  263: }
  264: 
  265: sub exam_score_line {
  266:     my ($target) = @_;
  267: 
  268:     my $result;
  269:     if ($target eq 'tex') {
  270: 	my $repetition = &Apache::response::repetition();
  271: 	$result.='\begin{enumerate}';
  272: 	if ($env{'request.state'} eq "construct" ) {$result.='\item[\strut]';}
  273: 	foreach my $i (0..$repetition-1) {
  274: 	    $result.='\item[\textbf{'.
  275: 		($Apache::lonxml::counter+$i).
  276: 		'}.]\textit{Leave blank on scoring form}\vskip 0 mm';
  277: 	}
  278: 	$result.= '\end{enumerate}';
  279:     }
  280: 
  281:     return $result;
  282: }
  283: 
  284: sub exam_box {
  285:     my ($target) = @_;
  286:     my $result;
  287: 
  288:     if ($target eq 'tex') {
  289: 	$result .= '\fbox{\fbox{\parbox{\textwidth-5mm}{\strut\\\\\strut\\\\\strut\\\\\strut\\\\}}}';
  290: 	$result .= &exam_score_line($target);
  291:     } elsif ($target eq 'web') {
  292: 	my $id=$Apache::inputtags::response[-1];
  293: 	$result.= '<br /><br />
  294:                    <textarea name="HWVAL_'.$id.'" rows="4" cols="50">
  295:                    </textarea> <br /><br />';
  296:     }
  297:     return $result;
  298: }
  299: 
  300: sub needs_exam_box {
  301:     my ($tagstack) = @_;
  302:     my @tags = ('formularesponse',
  303: 		'stringresponse',
  304: 		'reactionresponse',
  305: 		'organicresponse',
  306: 		);
  307: 
  308:     foreach my $tag (@tags) {
  309: 	if (grep(/\Q$tag\E/,@$tagstack)) {
  310: 	    return 1;
  311: 	}
  312:     }
  313:     return 0;
  314: }
  315: 
  316: sub start_textline {
  317:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  318:     my $result = "";
  319:     my $input_id = &start_input($parstack,$safeeval);
  320:     if ($target eq 'web') {
  321: 	$Apache::lonxml::evaluate--;
  322: 	my $partid=$Apache::inputtags::part;
  323: 	my $id=$Apache::inputtags::response[-1];
  324: 	if (!&Apache::response::show_answer()) {
  325: 	    my $size = &Apache::lonxml::get_param('size',$parstack,$safeeval);
  326: 	    my $maxlength;
  327: 	    if ($size eq '') { $size=20; } else {
  328: 		if ($size < 20) {
  329: 		    $maxlength = ' maxlength="'.$size.'"';
  330: 		}
  331: 	    }
  332: 	    my $oldresponse = $Apache::lonhomework::history{"resource.$partid.$id.submission"};
  333: 	    &Apache::lonxml::debug("oldresponse $oldresponse is ".ref($oldresponse));
  334: 
  335: 	    if (ref($oldresponse) eq 'ARRAY') {
  336: 		$oldresponse = $oldresponse->[$#Apache::inputtags::inputlist];
  337: 	    }
  338: 	    $oldresponse = &HTML::Entities::encode($oldresponse,'<>&"');
  339:             $oldresponse =~ s/^\s+//;
  340:             $oldresponse =~ s/\s+$//;
  341:             $oldresponse =~ s/\s+/ /g;
  342: 	    if ($Apache::lonhomework::type ne 'exam') {
  343: 		my $addchars=&Apache::lonxml::get_param('addchars',$parstack,$safeeval);
  344: 		$result='';
  345: 		if ($addchars) {
  346: 		    $result.=&addchars('HWVAL_'.$id,$addchars);
  347: 		}
  348: 		my $readonly=&Apache::lonxml::get_param('readonly',$parstack,
  349: 							$safeeval);
  350: 		if (lc($readonly) eq 'yes' 
  351: 		    || $Apache::inputtags::status[-1] eq 'CANNOT_ANSWER') {
  352: 		    $readonly=' readonly="readonly" ';
  353: 		} else {
  354: 		    $readonly='';
  355: 		}
  356: 		my $name = 'HWVAL_'.$id;
  357: 		if ($Apache::inputtags::status[-1] eq 'CANNOT_ANSWER') {
  358: 		    $name = "none";
  359: 		}
  360: 		$result.= '<input onkeydown="javascript:setSubmittedPart(\''.$partid.'\');" type="text" '.$readonly.' name="'.$name.'" value="'.
  361: 		    $oldresponse.'" size="'.$size.'"'.$maxlength.' />';
  362: 	    }
  363: 	    if ($Apache::lonhomework::type eq 'exam'
  364: 		&& &needs_exam_box($tagstack)) {
  365: 		$result.=&exam_box($target);
  366: 	    }
  367: 	} else {
  368: 	    #right or wrong don't show what was last typed in.
  369: 	    my $count = scalar(@Apache::inputtags::inputlist)-1;
  370: 	    $result='<b>'.$Apache::inputtags::answertxt{$id}[$count].'</b>';
  371: 	    #$result='';
  372: 	}
  373:     } elsif ($target eq 'edit') {
  374: 	$result=&Apache::edit::tag_start($target,$token);
  375: 	$result.=&Apache::edit::text_arg('Size:','size',$token,'5').
  376: 	    &Apache::edit::text_arg('Click-On Texts (comma sep):',
  377: 				    'addchars',$token,10);
  378:         $result.=&Apache::edit::select_arg('Readonly:','readonly',
  379: 					   ['no','yes'],$token);
  380: 	$result.=&Apache::edit::end_row();
  381: 	$result.=&Apache::edit::end_table();
  382:     } elsif ($target eq 'modified') {
  383: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  384: 						     $safeeval,'size',
  385: 						     'addchars','readonly');
  386: 	if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
  387:     } elsif ($target eq 'tex' 
  388: 	     && $Apache::lonhomework::type ne 'exam') {
  389: 	my $size = &Apache::lonxml::get_param('size',$parstack,$safeeval);
  390: 	if ($size != 0) {$size=$size*2; $size.=' mm';} else {$size='40 mm';}
  391: 	if ($env{'form.pdfFormFields'} eq 'yes') {
  392:             my $fieldname = $env{'request.symb'}.
  393:                                  '&part_'. $Apache::inputtags::part.
  394:                                  '&textresponse'.
  395:                                  '&HWVAL_' . $Apache::inputtags::response['-1'];
  396:             $result="\n\\\\\n".'\textField{'.$fieldname.'}{'.$size.'}{12 bp}';
  397:         } else {
  398:             $result='\framebox['.$size.'][s]{\tiny\strut}';
  399:         }
  400:     } elsif ($target eq 'tex' 
  401: 	     && $Apache::lonhomework::type eq 'exam'
  402: 	     && &needs_exam_box($tagstack)) {
  403: 	$result.=&exam_box($target);
  404:     }
  405:     return $result;
  406: }
  407: 
  408: sub end_textline {
  409:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  410:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  411:     elsif ($target eq 'edit') { return ('','no'); }
  412:     &end_input();
  413:     return "";
  414: }
  415: 
  416: sub start_hiddenline {
  417:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  418:     my $result = "";
  419:     my $input_id = &start_input($parstack,$safeeval);
  420:     if ($target eq 'web') {
  421: 	$Apache::lonxml::evaluate--;
  422: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  423: 	    my $partid=$Apache::inputtags::part;
  424: 	    my $id=$Apache::inputtags::response[-1];
  425: 	    my $oldresponse = $Apache::lonhomework::history{"resource.$partid.$id.submission"};
  426: 	    if (ref($oldresponse) eq 'ARRAY') {
  427: 		$oldresponse = $oldresponse->[$#Apache::inputtags::inputlist];
  428: 	    }
  429: 	    $oldresponse = &HTML::Entities::encode($oldresponse,'<>&"');
  430: 
  431: 	    if ($Apache::lonhomework::type ne 'exam') {
  432: 		$result= '<input type="hidden" name="HWVAL_'.$id.'" value="'.
  433: 		    $oldresponse.'" />';
  434: 	    }
  435: 	}
  436:     } elsif ($target eq 'edit') {
  437: 	$result=&Apache::edit::tag_start($target,$token);
  438: 	$result.=&Apache::edit::end_table;
  439:     }
  440: 
  441:     if ( ($target eq 'web' || $target eq 'tex')
  442: 	 && $Apache::lonhomework::type eq 'exam'
  443: 	 && &needs_exam_box($tagstack)) {
  444: 	$result.=&exam_box($target);
  445:     }
  446:     return $result;
  447: }
  448: 
  449: sub end_hiddenline {
  450:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  451:     if    ($target eq 'web') { $Apache::lonxml::evaluate++; }
  452:     elsif ($target eq 'edit') { return ('','no'); }
  453:     &end_input();
  454:     return "";
  455: }
  456: 
  457: =pod
  458: 
  459: =item file_selector()
  460: 
  461: $part -> partid
  462: $id -> responseid
  463: $uploadefiletypes -> comma seperated list of extensions allowed or * for any
  464: $which -> 'uploadedonly'  -> only newly uploaded files
  465:           'portfolioonly' -> only allow files from portfolio
  466:           'both' -> allow files from either location
  467: $extratext -> additional text to go between the link and the input box
  468: returns a table row <tr> 
  469: 
  470: =cut
  471: 
  472: sub file_selector {
  473:     my ($part,$id,$uploadedfiletypes,$which,$extratext)=@_;
  474:     if (!$uploadedfiletypes) { return ''; }
  475: 
  476:     my $jspart=$part;
  477:     $jspart=~s/\./_/g;
  478: 
  479:     my $result;
  480:     
  481:     $result.='<tr><td>';
  482:     if ($uploadedfiletypes ne '*') {
  483: 	$result.=
  484: 	    &mt('Allowed filetypes: [_1]','<b>'.$uploadedfiletypes.'</b>').'<br />';
  485:     }
  486:     if ($which eq 'uploadonly' || $which eq 'both') { 
  487: 	$result.=&mt('Submit a file: (only one file can be uploaded)').
  488: 	    ' <br /><input type="file" size="50" name="HWFILE'.
  489: 	    $jspart.'_'.$id.'" /><br />';
  490: 	$result .= &show_past_file_submission($part,$id);
  491:     }
  492:     if ( $which eq 'both') { 
  493: 	$result.='<br />'.'<strong>'.&mt('OR:').'</strong><br />';
  494:     }
  495:     if ($which eq 'portfolioonly' || $which eq 'both') { 
  496: 	$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"))'."'".'>'.
  497: 	    &mt('Select Portfolio Files').'</a><br />'.
  498: 	    '<input type="text" size="50" name="HWPORT'.$jspart.'_'.$id.'" value="" />'.
  499: 	    '<br />';
  500: 	$result .= &show_past_portfile_submission($part,$id);
  501: 
  502:     }
  503:     $result.='</td></tr>'; 
  504:     return $result;
  505: }
  506: 
  507: sub show_past_file_submission {
  508:     my ($part,$id) = @_;
  509:     my $uploadedfile= &HTML::Entities::encode($Apache::lonhomework::history{"resource.$part.$id.uploadedfile"},'<>&"');
  510: 
  511:     return if (!$uploadedfile);
  512: 
  513:     my $url=$Apache::lonhomework::history{"resource.$part.$id.uploadedurl"};
  514:     &Apache::lonxml::extlink($url);
  515:     &Apache::lonnet::allowuploaded('/adm/essayresponse',$url);
  516:     my $icon=&Apache::loncommon::icon($url);
  517:     my $curfile='<a href="'.$url.'"><img src="'.$icon.
  518: 	'" border="0" />'.$uploadedfile.'</a>';
  519:     return &mt('Currently submitted: [_1]','<tt>'.$curfile.'</tt>');
  520: 
  521: }
  522: 
  523: sub show_past_portfile_submission {
  524:     my ($part,$id) = @_;
  525:     if ($Apache::lonhomework::history{"resource.$part.$id.portfiles"}!~/[^\s]/){
  526: 	return;
  527:     }
  528:     my (@file_list,@bad_file_list);
  529:     foreach my $file (split(/\s*,\s*/,&unescape($Apache::lonhomework::history{"resource.$part.$id.portfiles"}))) {
  530: 	my (undef,undef,$domain,$user)=&Apache::lonnet::whichuser();
  531: 	my $url="/uploaded/$domain/$user/portfolio$file";
  532: 	my $icon=&Apache::loncommon::icon($url);
  533: 	push(@file_list,'<a href="'.$url.'"><img src="'.$icon.
  534: 	     '" border="0" />'.$file.'</a>');
  535: 	if (! &Apache::lonnet::stat_file($url)) {
  536: 	    &Apache::lonnet::logthis("bad file is $url");
  537: 	    push(@bad_file_list,'<a href="'.$url.'"><img src="'.$icon.
  538: 		 '" border="0" />'.$file.'</a>');
  539: 	}
  540:     }
  541:     my $files = '<span class="LC_filename">'.
  542: 	join('</span>, <span class="LC_filename">',@file_list).
  543: 	'</span>';
  544:     my $result = &mt("Portfolio files previously selected: [_1]",$files);
  545:     if (@bad_file_list) {
  546: 	my $bad_files = '<span class="LC_filename">'.
  547: 	    join('</span>, <span class="LC_filename">',@bad_file_list).
  548: 	    '</span>';
  549: 	$result.='<p><span class="LC_error">'
  550:                 .&mt("These file(s) don't exist: [_1]",$bad_files)
  551:                 .'</span></p>';
  552:     }
  553:     return $result;
  554: 
  555: }
  556: 
  557: sub valid_award {
  558:     my ($award) =@_;
  559:     foreach my $possibleaward ('EXTRA_ANSWER','MISSING_ANSWER', 'ERROR',
  560: 			       'NO_RESPONSE',
  561: 			       'TOO_LONG', 'UNIT_INVALID_INSTRUCTOR',
  562: 			       'UNIT_INVALID_STUDENT', 'UNIT_IRRECONCIBLE',
  563: 			       'UNIT_FAIL', 'NO_UNIT',
  564: 			       'UNIT_NOTNEEDED', 'WANTED_NUMERIC',
  565: 			       'BAD_FORMULA', 'INTERNAL_ERROR', 'SIG_FAIL', 'INCORRECT', 
  566: 			       'MISORDERED_RANK', 'INVALID_FILETYPE',
  567:                                'EXCESS_FILESIZE', 'DRAFT',
  568: 			       'SUBMITTED', 'ASSIGNED_SCORE',
  569: 			       'APPROX_ANS', 'EXACT_ANS','COMMA_FAIL') {
  570: 	if ($award eq $possibleaward) { return 1; }
  571:     }
  572:     return 0;
  573: }
  574: 
  575: {
  576:     my @awards = ('EXTRA_ANSWER', 'MISSING_ANSWER', 'ERROR', 'NO_RESPONSE',
  577: 		  'TOO_LONG',
  578: 		  'UNIT_INVALID_INSTRUCTOR', 'UNIT_INVALID_STUDENT',
  579: 		  'UNIT_IRRECONCIBLE', 'UNIT_FAIL', 'NO_UNIT',
  580: 		  'UNIT_NOTNEEDED', 'WANTED_NUMERIC', 'BAD_FORMULA', 'INTERNAL_ERROR',
  581: 		  'COMMA_FAIL', 'SIG_FAIL', 'INCORRECT', 'MISORDERED_RANK',
  582: 		  'INVALID_FILETYPE', 'EXCESS_FILESIZE', 'DRAFT', 'SUBMITTED',
  583:                   'ASSIGNED_SCORE', 'APPROX_ANS', 'EXACT_ANS');
  584:     my $i=0;
  585:     my %fwd_awards = map { ($_,$i++) } @awards;
  586:     my $max=scalar(@awards);
  587:     @awards=reverse(@awards);
  588:     $i=0;
  589:     my %rev_awards = map { ($_,$i++) } @awards;
  590: 
  591: sub awarddetail_to_awarded {
  592:     my ($awarddetail) = @_;
  593:     if ($awarddetail eq 'EXACT_ANS'
  594: 	|| $awarddetail eq 'APPROX_ANS') {
  595: 	return 1;
  596:     }
  597:     return 0;
  598: }
  599: 
  600: sub hide_award {
  601:     my ($award) = @_;
  602:     if (&Apache::lonhomework::show_no_problem_status()) {
  603: 	return 1;
  604:     }
  605:     if ($award =~
  606: 	/^(?:EXACT_ANS|APPROX_ANS|SUBMITTED|ASSIGNED_SCORE|INCORRECT)/) {
  607: 	return 1;
  608:     }
  609:     return 0;
  610: }
  611: 
  612: sub finalizeawards {
  613:     my ($awardref,$msgref,$nameref,$reverse,$final_scantron)=@_;
  614:     my $result;
  615:     if ($#$awardref == -1) { $result = "NO_RESPONSE"; }
  616:     if ($result eq '' ) {
  617: 	my $blankcount;
  618: 	foreach my $award (@$awardref) {
  619: 	    if ($award eq '') {
  620: 		$result='MISSING_ANSWER';
  621: 		$blankcount++;
  622: 	    }
  623: 	}
  624: 	if ($blankcount == ($#$awardref + 1)) {
  625: 	    return ('NO_RESPONSE');
  626: 	}
  627:     }
  628: 
  629:     if ($Apache::lonxml::internal_error) { $result='INTERNAL_ERROR'; }
  630: 
  631:     if (!$final_scantron && defined($result)) { return ($result); }
  632: 
  633:     # if in scantron mode, if the award for any response is 
  634:     # assigned score, then the part gets an assigned score
  635:     if ($final_scantron 
  636: 	&& grep {$_ eq 'ASSIGNED_SCORE'} (@$awardref)) {
  637: 	return ('ASSIGNED_SCORE');
  638:     }
  639: 
  640:     # if in scantron mode, if the award for any response is 
  641:     # correct and there are non-correct responses,
  642:     # then the part gets an assigned score
  643:     if ($final_scantron 
  644: 	&& (grep { $_ eq 'EXACT_ANS' ||
  645: 		   $_ eq 'APPROX_ANS'  } (@$awardref))
  646: 	&& (grep { $_ ne 'EXACT_ANS' &&
  647: 		   $_ ne 'APPROX_ANS'  } (@$awardref))) {
  648: 	return ('ASSIGNED_SCORE');
  649:     }
  650:     # these awards are ordered from most important error through best correct
  651:     my $awards = (!$reverse) ? \%fwd_awards : \%rev_awards ;
  652: 
  653:     my $best = $max;
  654:     my $j=0;
  655:     my $which;
  656:     foreach my $award (@$awardref) {
  657: 	if ($awards->{$award} < $best) {
  658: 	    $best  = $awards->{$award};
  659: 	    $which = $j;
  660: 	}
  661: 	$j++;
  662:     }
  663: 
  664:     if (defined($which)) {
  665: 	if (ref($nameref)) {
  666: 	    return ($$awardref[$which],$$msgref[$which],$$nameref[$which]);
  667: 	} else {
  668: 	    return ($$awardref[$which],$$msgref[$which]);
  669: 	}
  670:     }
  671:     return ('ERROR',undef);
  672: }
  673: }
  674: 
  675: sub decideoutput {
  676:     my ($award,$awarded,$awardmsg,$solved,$previous,$target)=@_;
  677: 
  678:     my $message='';
  679:     my $button=0;
  680:     my $previousmsg;
  681:     my $css_class='orange';
  682:     my $added_computer_text=0;
  683:     my %possible_class =
  684: 	( 'correct'         => 'LC_answer_correct',
  685: 	  'charged_try'     => 'LC_answer_charged_try',
  686: 	  'not_charged_try' => 'LC_answer_not_charged_try',
  687: 	  'no_grade'        => 'LC_answer_no_grade',
  688: 	  'no_message'      => 'LC_no_message',
  689: 	  );
  690: 
  691:     my $part = $Apache::inputtags::part;
  692:     my $tohandgrade = &Apache::lonnet::EXT("resource.$part.handgrade");
  693:     my $handgrade = ('yes' eq lc($tohandgrade)); 
  694:     
  695:     my $computer = ($handgrade)? ''
  696: 	                       : " ".&mt("Computer's answer now shown above.");
  697:     &Apache::lonxml::debug("handgrade has :$handgrade:");
  698: 
  699:     if ($previous) { $previousmsg=&mt('You have entered that answer before'); }
  700:     
  701:     if ($solved =~ /^correct/) {
  702:         $css_class=$possible_class{'correct'};
  703: 	$message=&mt('You are correct.');
  704: 	if ($awarded < 1 && $awarded > 0) {
  705: 	    $message=&mt('You are partially correct.');
  706: 	    $css_class=$possible_class{'not_charged_try'};
  707: 	} elsif ($awarded < 1) {
  708: 	    $message=&mt('Incorrect.');
  709: 	    $css_class=$possible_class{'charged_try'};
  710: 	}
  711: 	if ($env{'request.filename'} =~ 
  712: 	    m|/res/lib/templates/examupload.problem$|) {
  713: 	    $message = &mt("A score has been assigned.");
  714: 	    $added_computer_text=1;
  715: 	} else {
  716: 	    if ($target eq 'tex') {
  717: 		$message = '\textbf{'.$message.'}';
  718: 	    } else {
  719: 		$message = "<b>".$message."</b>";
  720: 		$message.= $computer;
  721: 	    }
  722: 	    $added_computer_text=1;
  723: 	    if ($awarded > 0) {
  724: 		my ($symb) = &Apache::lonnet::whichuser();
  725: 		if (($symb ne '') 
  726: 		    &&
  727: 		    ($env{'course.'.$env{'request.course.id'}.
  728: 			      '.disable_receipt_display'} ne 'yes') &&
  729:                     ($Apache::lonhomework::type ne 'practice')) { 
  730: 		    $message.=(($target eq 'web')?'<br />':' ').
  731: 			&mt('Your receipt is [_1]',
  732: 			    (&Apache::lonnet::receipt($Apache::inputtags::part).
  733: 			     (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'')));
  734: 		}
  735: 	    }
  736: 	}
  737: 	$button=0;
  738: 	$previousmsg='';
  739:     } elsif ($solved =~ /^excused/) {
  740: 	if ($target eq 'tex') {
  741: 	    $message = ' \textbf{'.&mt('You are excused from the problem.').'} ';
  742: 	} else {
  743: 	    $message = "<b>".&mt('You are excused from the problem.')."</b>";
  744: 	}
  745: 	$css_class=$possible_class{'charged_try'};
  746: 	$button=0;
  747: 	$previousmsg='';
  748:     } elsif ($award eq 'EXACT_ANS' || $award eq 'APPROX_ANS' ) {
  749: 	if ($solved =~ /^incorrect/ || $solved eq '') {
  750: 	    $message = &mt("Incorrect").".";
  751: 	    $css_class=$possible_class{'charged_try'};
  752: 	    $button=1;
  753: 	} else {
  754: 	    if ($target eq 'tex') {
  755: 		$message = '\textbf{'.&mt('You are correct.').'}';
  756: 	    } else {
  757: 		$message = "<b>".&mt('You are correct.')."</b>";
  758: 		$message.= $computer;
  759: 	    }
  760: 	    $added_computer_text=1;
  761: 	    if  ($awarded > 0 
  762: 		 && $env{'course.'.
  763: 			     $env{'request.course.id'}.
  764: 			     '.disable_receipt_display'} ne 'yes') { 
  765: 		$message.=(($target eq 'web')?'<br />':' ').
  766: 		    &mt('Your receipt is [_1]',
  767: 			(&Apache::lonnet::receipt($Apache::inputtags::part).
  768: 			 (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'')));
  769: 	    }
  770: 	    $css_class=$possible_class{'correct'};
  771: 	    $button=0;
  772: 	    $previousmsg='';
  773: 	}
  774:     } elsif ($award eq 'NO_RESPONSE') {
  775: 	$message = '';
  776: 	$css_class=$possible_class{'no_feedback'};
  777: 	$button=1;
  778:     } elsif ($award eq 'EXTRA_ANSWER') {
  779: 	$message = &mt('Some extra items were submitted.');
  780: 	$css_class=$possible_class{'not_charged_try'};
  781: 	$button = 1;
  782:     } elsif ($award eq 'MISSING_ANSWER') {
  783: 	$message = &mt('Some items were not submitted.');
  784:         if ($target ne 'tex') {
  785:            $message .= &Apache::loncommon::help_open_topic('Some_Items_Were_Not_Submitted');
  786:         }
  787: 	$css_class=$possible_class{'not_charged_try'};
  788: 	$button = 1;
  789:     } elsif ($award eq 'ERROR') {
  790: 	$message = &mt('An error occurred while grading your answer.');
  791: 	$css_class=$possible_class{'not_charged_try'};
  792: 	$button = 1;
  793:     } elsif ($award eq 'TOO_LONG') {
  794: 	$message = &mt("The submitted answer was too long.");
  795: 	$css_class=$possible_class{'not_charged_try'};
  796: 	$button=1;
  797:     } elsif ($award eq 'WANTED_NUMERIC') {
  798: 	$message = &mt("This question expects a numeric answer.");
  799: 	$css_class=$possible_class{'not_charged_try'};
  800: 	$button=1;
  801:     } elsif ($award eq 'MISORDERED_RANK') {
  802:         $message = &mt('You have provided an invalid ranking.');
  803:         if ($target ne 'tex') {
  804:             $message.=' '.&mt('Please refer to [_1]',&Apache::loncommon::help_open_topic('Ranking_Problems',&mt('help on ranking problems')));
  805:         }
  806: 	$css_class=$possible_class{'not_charged_try'};
  807: 	$button=1;
  808:     } elsif ($award eq 'EXCESS_FILESIZE') {
  809:         $message = &mt('Submission won\'t be graded. The combined size of submitted files exceeded the amount allowed.');
  810:         $css_class=$possible_class{'not_charged_try'};
  811:         $button=1;
  812:     } elsif ($award eq 'INVALID_FILETYPE') {
  813: 	$message = &mt('Submission won\'t be graded. The type of file submitted is not allowed.');
  814: 	$css_class=$possible_class{'not_charged_try'};
  815: 	$button=1;
  816:     } elsif ($award eq 'SIG_FAIL') {
  817: 	my ($used,$min,$max)=split(':',$awardmsg);
  818: 	my $word = ($used < $min) ? 'more' : 'fewer';
  819: 	$message = &mt("Submission not graded. Use $word digits.",$used);
  820: 	$css_class=$possible_class{'not_charged_try'};
  821: 	$button=1;
  822:     } elsif ($award eq 'UNIT_INVALID_INSTRUCTOR') {
  823: 	$message = &mt('Error in instructor specifed unit. This error has been reported to the instructor.', $awardmsg);
  824: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
  825: 	$css_class=$possible_class{'not_charged_try'};
  826: 	$button=1;
  827:     } elsif ($award eq 'UNIT_INVALID_STUDENT') {
  828: 	$message = &mt('Unable to interpret units. Computer reads units as "[_1]".',&markup_unit($awardmsg,$target));
  829: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
  830: 	$css_class=$possible_class{'not_charged_try'};
  831: 	$button=1;
  832:     } elsif ($award eq 'UNIT_FAIL' || $award eq 'UNIT_IRRECONCIBLE') {
  833: 	$message = &mt('Incompatible units. No conversion found between "[_1]" and the required units.',&markup_unit($awardmsg,$target));
  834: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
  835: 	$css_class=$possible_class{'not_charged_try'};
  836: 	$button=1;
  837:     } elsif ($award eq 'UNIT_NOTNEEDED') {
  838: 	$message = &mt('Only a number required. Computer reads units of "[_1]".',&markup_unit($awardmsg,$target));
  839: 	$css_class=$possible_class{'not_charged_try'};
  840: 	$button=1;
  841:     } elsif ($award eq 'NO_UNIT') {
  842: 	$message = &mt("Units required").'.';
  843: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units')};
  844: 	$css_class=$possible_class{'not_charged_try'};
  845: 	$button=1;
  846:     } elsif ($award eq 'COMMA_FAIL') {
  847: 	$message = &mt("Proper comma separation is required").'.';
  848: 	$css_class=$possible_class{'not_charged_try'};
  849: 	$button=1;
  850:     } elsif ($award eq 'BAD_FORMULA') {
  851: 	$message = &mt("Unable to understand formula").'.';
  852:         if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Formula_Answers')};
  853: 	$css_class=$possible_class{'not_charged_try'};
  854: 	$button=1;
  855:     } elsif ($award eq 'INTERNAL_ERROR') {
  856:         $message = &mt("An internal error occurred while processing your answer. Please try again later.");
  857:         $css_class=$possible_class{'not_charged_try'};
  858:         $button=1;
  859:     } elsif ($award eq 'INCORRECT') {
  860: 	$message = &mt("Incorrect").'.';
  861: 	$css_class=$possible_class{'charged_try'};
  862: 	$button=1;
  863:     } elsif ($award eq 'SUBMITTED') {
  864: 	$message = &mt("Your submission has been recorded.");
  865: 	$css_class=$possible_class{'no_grade'};
  866: 	$button=1;
  867:     } elsif ($award eq 'DRAFT') {
  868: 	$message = &mt("A draft copy has been saved.");
  869: 	$css_class=$possible_class{'not_charged_try'};
  870: 	$button=1;
  871:     } elsif ($award eq 'ASSIGNED_SCORE') {
  872: 	$message = &mt("A score has been assigned.");
  873: 	$css_class=$possible_class{'correct'};
  874: 	$button=0;
  875:     } elsif ($award eq '') {
  876: 	if ($handgrade && $Apache::inputtags::status[-1] eq 'SHOW_ANSWER') {
  877: 	    $message = &mt("Nothing submitted.");
  878: 	    $css_class=$possible_class{'charged_try'};
  879: 	} else {
  880: 	    $css_class=$possible_class{'not_charged_try'};
  881: 	}
  882: 	$button=1;
  883:     } else {
  884: 	$message = &mt("Unknown message").": $award";
  885: 	$button=1;
  886:     }
  887:     my (undef,undef,$domain,$user)=&Apache::lonnet::whichuser();
  888:     foreach my $resid(@Apache::inputtags::response){
  889:         if ($Apache::lonhomework::history{"resource.$part.$resid.handback"}) {
  890: 	    $message.='<br />';
  891: 	    my @files = split(/\s*,\s*/,
  892: 			      $Apache::lonhomework::history{"resource.$part.$resid.handback"});
  893: 	    my $file_msg;
  894: 	    foreach my $file (@files) {
  895: 		$file_msg.= '<br /><a href="/uploaded/'."$domain/$user".'/'.$file.'">'.$file.'</a>';
  896: 	    }
  897: 	    $message .= &mt('Returned file(s): [_1]',$file_msg);
  898: 	}
  899:     }
  900: 
  901:     if (&Apache::lonhomework::hide_problem_status()
  902: 	&& $Apache::inputtags::status[-1] ne 'SHOW_ANSWER'
  903: 	&& &hide_award($award)) {
  904: 	$message = &mt("Answer Submitted: Your final submission will be graded after the due date.");
  905: 	$css_class=$possible_class{'no_grade'};
  906: 	$button=1;
  907:     }
  908:     if ($Apache::inputtags::status[-1] eq 'SHOW_ANSWER' && 
  909: 	!$added_computer_text && $target ne 'tex') {
  910: 	$message.= $computer;
  911: 	$added_computer_text=1;
  912:     }
  913:     if ($Apache::lonhomework::type eq 'practice') {
  914:        if ($target eq 'web') {
  915:            $message .= '<br />';
  916:        } else {
  917:            $message .= ' ';      
  918:        }
  919:        $message.=&mt('Submissions to practice problems are not permanently recorded.');
  920:     }
  921: 
  922:     return ($button,$css_class,$message,$previousmsg);
  923: }
  924: 
  925: sub markup_unit {
  926:     my ($unit,$target)=@_;
  927:     if ($target eq 'tex') {
  928: 	return '\texttt{'.&Apache::lonxml::latex_special_symbols($unit).'}'; 
  929:     } else {
  930: 	return "<tt>".$unit."</tt>";
  931:     }
  932: }
  933: 
  934: sub removealldata {
  935:     my ($id)=@_;
  936:     foreach my $key (keys(%Apache::lonhomework::results)) {
  937: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
  938: 	    &Apache::lonxml::debug("Removing $key");
  939: 	    delete($Apache::lonhomework::results{$key});
  940: 	}
  941:     }
  942: }
  943: 
  944: sub hidealldata {
  945:     my ($id)=@_;
  946:     foreach my $key (keys(%Apache::lonhomework::results)) {
  947: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
  948: 	    &Apache::lonxml::debug("Hidding $key");
  949: 	    my $newkey=$key;
  950: 	    $newkey=~s/^(resource\.\Q$id\E\.[^\.]+\.)(.*)$/${1}hidden${2}/;
  951: 	    $Apache::lonhomework::results{$newkey}=
  952: 		$Apache::lonhomework::results{$key};
  953: 	    delete($Apache::lonhomework::results{$key});
  954: 	}
  955:     }
  956: }
  957: 
  958: sub setgradedata {
  959:     my ($award,$msg,$id,$previously_used) = @_;
  960:     if ($Apache::lonhomework::scantronmode && 
  961: 	&Apache::lonnet::validCODE($env{'form.CODE'})) {
  962: 	$Apache::lonhomework::results{"resource.CODE"}=$env{'form.CODE'};
  963:     } elsif ($Apache::lonhomework::scantronmode && 
  964: 	     $env{'form.CODE'} eq '' &&
  965: 	     $Apache::lonhomework::history{"resource.CODE"} ne '') {
  966: 	$Apache::lonhomework::results{"resource.CODE"}='';
  967:     }
  968: 
  969:     if (!$Apache::lonhomework::scantronmode &&
  970: 	$Apache::inputtags::status['-1'] ne 'CAN_ANSWER' &&
  971: 	$Apache::inputtags::status['-1'] ne 'CANNOT_ANSWER') {
  972: 	$Apache::lonhomework::results{"resource.$id.afterduedate"}=$award;
  973: 	return '';
  974:     } elsif ( $Apache::lonhomework::history{"resource.$id.solved"} !~
  975: 	      /^correct/ 
  976: 	      || $Apache::lonhomework::scantronmode 
  977: 	      || &Apache::lonhomework::hide_problem_status()  ) {
  978:         # the student doesn't already have it correct,
  979: 	# or we are in a mode (scantron orno problem status) where a correct 
  980:         # can become incorrect
  981: 	# handle assignment of tries and solved status
  982: 	my $solvemsg;
  983: 	if ($Apache::lonhomework::scantronmode) {
  984: 	    $solvemsg='correct_by_scantron';
  985: 	} else {
  986: 	    $solvemsg='correct_by_student';
  987: 	}
  988: 	if ($Apache::lonhomework::history{"resource.$id.afterduedate"}) {
  989: 	    $Apache::lonhomework::results{"resource.$id.afterduedate"}='';
  990: 	}
  991: 	if ( $award eq 'ASSIGNED_SCORE') {
  992: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
  993: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
  994: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  995: 		$solvemsg;
  996: 	    my $numawards=scalar(@Apache::inputtags::response);
  997: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = 0;
  998: 	    foreach my $res (@Apache::inputtags::response) {
  999: 		if (defined($Apache::lonhomework::results{"resource.$id.$res.awarded"})) {
 1000: 		    $Apache::lonhomework::results{"resource.$id.awarded"}+=
 1001: 			$Apache::lonhomework::results{"resource.$id.$res.awarded"};
 1002: 		} else {
 1003: 		    $Apache::lonhomework::results{"resource.$id.awarded"}+=
 1004: 			&awarddetail_to_awarded($Apache::lonhomework::results{"resource.$id.$res.awarddetail"});
 1005: 		}
 1006: 	    }
 1007: 	    if ($numawards > 0) {
 1008: 		$Apache::lonhomework::results{"resource.$id.awarded"}/=
 1009: 		    $numawards;
 1010: 	    }
 1011: 	} elsif ( $award eq 'APPROX_ANS' || $award eq 'EXACT_ANS' ) {
 1012: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1013: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1014: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1015: 		$solvemsg;
 1016: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
 1017: 	} elsif ( $award eq 'INCORRECT' ) {
 1018: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1019: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1020: 	    if (&Apache::lonhomework::hide_problem_status()
 1021: 		|| $Apache::lonhomework::scantronmode) {
 1022: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1023: 	    }
 1024: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1025: 		'incorrect_attempted';
 1026: 	} elsif ( $award eq 'SUBMITTED' ) {
 1027: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
 1028: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1029: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1030: 		'ungraded_attempted';
 1031: 	} elsif ( $award eq 'DRAFT' ) {
 1032: 	    $Apache::lonhomework::results{"resource.$id.solved"} = '';
 1033: 	} elsif ( $award eq 'NO_RESPONSE' ) {
 1034: 	    #no real response so delete any data that got stored
 1035: 	    &removealldata($id);
 1036: 	    return '';
 1037: 	} else {
 1038: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
 1039: 		'incorrect_attempted';
 1040: 	    if (&Apache::lonhomework::show_no_problem_status()
 1041: 		|| $Apache::lonhomework::scantronmode) {
 1042: 		$Apache::lonhomework::results{"resource.$id.tries"} =
 1043: 		    $Apache::lonhomework::history{"resource.$id.tries"} + 1;
 1044: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
 1045: 	    }
 1046: 
 1047: 	    if (&Apache::lonhomework::show_some_problem_status()) {
 1048: 		# clear out the awarded if they had gotten it wrong/right
 1049: 		# and are now in an error mode	
 1050: 		$Apache::lonhomework::results{"resource.$id.awarded"} = '';
 1051: 	    }
 1052: 	}
 1053: 	if (defined($msg)) {
 1054: 	    $Apache::lonhomework::results{"resource.$id.awardmsg"} = $msg;
 1055: 	}
 1056: 	# did either of the overall awards chage? If so ignore the 
 1057: 	# previous check
 1058: 	if (($Apache::lonhomework::results{"resource.$id.awarded"} eq
 1059: 	     $Apache::lonhomework::history{"resource.$id.awarded"}) &&
 1060: 	    ($Apache::lonhomework::results{"resource.$id.solved"} eq
 1061: 	     $Apache::lonhomework::history{"resource.$id.solved"})) {
 1062: 	    # check if this was a previous submission if it was delete the
 1063: 	    # unneeded data and update the previously_used attribute
 1064: 	    if ( $previously_used eq 'PREVIOUSLY_USED') {
 1065: 		if (&Apache::lonhomework::show_problem_status()) {
 1066: 		    delete($Apache::lonhomework::results{"resource.$id.tries"});
 1067: 		    $Apache::lonhomework::results{"resource.$id.previous"} = '1';
 1068: 		}
 1069: 	    } elsif ( $previously_used eq 'PREVIOUSLY_LAST') {
 1070: 		#delete all data as they student didn't do anything, but save
 1071: 		#the list of collaborators.
 1072: 		&removealldata($id);
 1073: 		#and since they didn't do anything we were never here
 1074: 		return '';
 1075: 	    } else {
 1076: 		$Apache::lonhomework::results{"resource.$id.previous"} = '0';
 1077: 	    }
 1078: 	}
 1079:     } elsif ( $Apache::lonhomework::history{"resource.$id.solved"} =~
 1080: 	      /^correct/ ) {
 1081: 	#delete all data as they student already has it correct
 1082: 	&removealldata($id);
 1083: 	#and since they didn't do anything we were never here
 1084: 	return '';
 1085:     }
 1086:     $Apache::lonhomework::results{"resource.$id.award"} = $award;
 1087:     if ($award eq 'SUBMITTED') {
 1088: 	&Apache::response::add_to_gradingqueue();
 1089:     }
 1090: }
 1091: 
 1092: sub find_which_previous {
 1093:     my ($version) = @_;
 1094:     my $part = $Apache::inputtags::part;
 1095:     my (@previous_version);
 1096:     foreach my $resp (@Apache::inputtags::response) {
 1097: 	my $key = "$version:resource.$part.$resp.submission";
 1098: 	my $submission = $Apache::lonhomework::history{$key};
 1099: 	my %previous = &Apache::response::check_for_previous($submission,
 1100: 							     $part,$resp,
 1101: 							     $version);
 1102: 	push(@previous_version,$previous{'version'});
 1103:     }
 1104:     return &previous_match(\@previous_version,
 1105: 			   scalar(@Apache::inputtags::response));
 1106: }
 1107: 
 1108: sub previous_match {
 1109:     my ($previous_array,$count) = @_;
 1110:     my $match = 0;
 1111:     my @matches;
 1112:     foreach my $versionar (@$previous_array) {
 1113: 	foreach my $version (@$versionar) {
 1114: 	    $matches[$version]++;
 1115: 	}
 1116:     }
 1117:     my $which=0;
 1118:     foreach my $elem (@matches) {
 1119: 	if ($elem eq $count) {
 1120: 	    $match=1;
 1121: 	    last;
 1122: 	}
 1123: 	$which++;
 1124:     }
 1125:     return ($match,$which);
 1126: }
 1127: 
 1128: sub grade {
 1129:     my ($target) = @_;
 1130:     my $id = $Apache::inputtags::part;
 1131:     my $response='';
 1132:     if ( defined $env{'form.submitted'}) {
 1133: 	my (@awards,@msgs);
 1134: 	foreach $response (@Apache::inputtags::response) {
 1135: 	    &Apache::lonxml::debug("looking for response.$id.$response.awarddetail");
 1136: 	    my $value=$Apache::lonhomework::results{"resource.$id.$response.awarddetail"};
 1137: 	    &Apache::lonxml::debug("keeping $value from $response for $id");
 1138: 	    push (@awards,$value);
 1139: 	    $value=$Apache::lonhomework::results{"resource.$id.$response.awardmsg"};
 1140: 	    &Apache::lonxml::debug("got message $value from $response for $id");
 1141: 	    push (@msgs,$value);
 1142: 	}
 1143: 	my ($finalaward,$msg) = 
 1144: 	    &finalizeawards(\@awards,\@msgs,undef,undef,
 1145: 			    $Apache::lonhomework::scantronmode);
 1146: 	my $previously_used;
 1147: 	if ( $#Apache::inputtags::previous eq $#awards ) {
 1148: 	    my ($match) =
 1149: 		&previous_match(\@Apache::inputtags::previous_version,
 1150: 				scalar(@Apache::inputtags::response));
 1151: 
 1152: 	    if ($match) {
 1153: 		$previously_used = 'PREVIOUSLY_LAST';
 1154: 		foreach my $value (@Apache::inputtags::previous) {
 1155: 		    if ($value eq 'PREVIOUSLY_USED' ) {
 1156: 			$previously_used = $value;
 1157: 			last;
 1158: 		    }
 1159: 		}
 1160: 	    }
 1161: 	}
 1162: 	&Apache::lonxml::debug("final award $finalaward, $previously_used, message $msg");
 1163: 	&setgradedata($finalaward,$msg,$id,$previously_used);
 1164:     }
 1165:     return '';
 1166: }
 1167: 
 1168: sub get_grade_messages {
 1169:     my ($id,$prefix,$target,$status) = @_;
 1170: 
 1171:     my ($message,$latemessage,$trystr,$previousmsg);
 1172:     my $showbutton = 1;
 1173: 
 1174:     my $award = $Apache::lonhomework::history{"$prefix.award"};
 1175:     my $awarded = $Apache::lonhomework::history{"$prefix.awarded"};
 1176:     my $solved = $Apache::lonhomework::history{"$prefix.solved"};
 1177:     my $previous = $Apache::lonhomework::history{"$prefix.previous"};
 1178:     my $awardmsg = $Apache::lonhomework::history{"$prefix.awardmsg"};
 1179:     &Apache::lonxml::debug("Found Award |$award|$solved|$awardmsg");
 1180:     if ( $award ne '' || $solved ne '' || $status eq 'SHOW_ANSWER') {
 1181: 	&Apache::lonxml::debug('Getting message');
 1182: 	($showbutton,my $css_class,$message,$previousmsg) =
 1183: 	    &decideoutput($award,$awarded,$awardmsg,$solved,$previous,
 1184: 			  $target);
 1185: 	if ($target eq 'tex') {
 1186: 	    $message='\vskip 2 mm '.$message.' ';
 1187: 	} else {
 1188: 	    $message="<td class=\"$css_class\">$message</td>";
 1189: 	    if ($previousmsg) {
 1190: 		$previousmsg="<td class=\"LC_answer_previous\">$previousmsg</td>";
 1191: 	    }
 1192: 	}
 1193:     }
 1194:     my $tries = $Apache::lonhomework::history{"$prefix.tries"};
 1195:     my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
 1196:     &Apache::lonxml::debug("got maxtries of :$maxtries:");
 1197:     #if tries are set to negative turn off the Tries/Button and messages
 1198:     if (defined($maxtries) && $maxtries < 0) { return ''; }
 1199:     if ( $tries eq '' ) { $tries = '0'; }
 1200:     if ( $maxtries eq '' ) { $maxtries = '2'; } 
 1201:     if ( $maxtries eq 'con_lost' ) { $maxtries = '0'; } 
 1202:     my $tries_text=&mt('Tries');
 1203:     if ( $Apache::lonhomework::type eq 'survey' ||
 1204: 	 $Apache::lonhomework::parsing_a_task) {
 1205: 	$tries_text=&mt('Submissions');
 1206:     }
 1207: 
 1208:     if ($showbutton) {
 1209: 	if ($target eq 'tex') {
 1210: 	    if ($env{'request.state'} ne "construct"
 1211: 		&& $Apache::lonhomework::type ne 'exam'
 1212: 		&& $env{'form.suppress_tries'} ne 'yes') {
 1213: 		$trystr = ' {\vskip 1 mm \small \textit{'.$tries_text.'} '.
 1214: 		    $tries.'/'.$maxtries.'} \vskip 2 mm ';
 1215: 	    } else {
 1216: 		$trystr = '\vskip 0 mm ';
 1217: 	    }
 1218: 	} else {
 1219: 	    $trystr = "<td><nobr>".$tries_text." $tries";
 1220: 	    if ($Apache::lonhomework::parsing_a_task) {
 1221: 	    } elsif($env{'request.state'} ne 'construct') {
 1222: 		$trystr.="/$maxtries";
 1223: 	    } else {
 1224: 		if (defined($Apache::inputtags::params{'maxtries'})) {
 1225: 		    $trystr.="/".$Apache::inputtags::params{'maxtries'};
 1226: 		}
 1227: 	    }
 1228: 	    $trystr.="</nobr></td>";
 1229: 	}
 1230:     }
 1231: 
 1232:     if ($Apache::lonhomework::history{"$prefix.afterduedate"}) {
 1233: 	#last submissions was after due date
 1234: 	$latemessage=&mt(' The last submission was after the Due Date ');;
 1235: 	if ($target eq 'web') {
 1236: 	    $latemessage='<td class="LC_answer_late">'.$latemessage.'</td>';
 1237: 	}
 1238:     }
 1239:     return ($previousmsg,$latemessage,$message,$trystr,$showbutton);
 1240: }
 1241: 
 1242: sub gradestatus {
 1243:     my ($id,$target,$no_previous) = @_;
 1244:     my $showbutton = 1;
 1245:     my $message = '';
 1246:     my $latemessage = '';
 1247:     my $trystr='';
 1248:     my $button='';
 1249:     my $previousmsg='';
 1250: 
 1251:     my $status = $Apache::inputtags::status['-1'];
 1252:     &Apache::lonxml::debug("gradestatus has :$status:");
 1253:     if ( $status ne 'CLOSED' 
 1254: 	 && $status ne 'UNAVAILABLE' 
 1255: 	 && $status ne 'INVALID_ACCESS' 
 1256: 	 && $status ne 'NEEDS_CHECKIN' 
 1257: 	 && $status ne 'NOT_IN_A_SLOT') {  
 1258: 
 1259: 	($previousmsg,$latemessage,$message,$trystr) =
 1260: 	    &get_grade_messages($id,"resource.$id",$target,$status,
 1261: 				$showbutton);
 1262: 	if ( $status eq 'SHOW_ANSWER' || $status eq 'CANNOT_ANSWER') {
 1263: 	    $showbutton = 0;
 1264: 	}
 1265: 	if ( $status eq 'SHOW_ANSWER') {
 1266: 	    undef($previousmsg);
 1267: 	}
 1268: 	if ( $showbutton ) { 
 1269: 	    if ($target ne 'tex') {
 1270: 		$button = 
 1271: 		    '<input 
 1272:                           onmouseup="javascript:setSubmittedPart(\''.$id.'\')"
 1273:                            onsubmit="javascript:setSubmittedPart(\''.$id.'\')"
 1274:                         type="submit" name="submit_'.$id.'"
 1275:                          value="'.&mt('Submit Answer').'" />';
 1276: 	    }
 1277: 	}
 1278: 
 1279:     }
 1280:     my $output= $previousmsg.$latemessage.$message.$trystr;
 1281:     if ($output =~ /^\s*$/) {
 1282: 	return $button;
 1283:     } else {
 1284: 	if ($target eq 'tex') {
 1285: 	    return $button.' \vskip 0 mm '.$output.' ';
 1286: 	} else {
 1287: 	    $output =
 1288: 		'<table><tr><td>'.$button.'</td>'.$output;
 1289: 	    if (!$no_previous) {
 1290: 		$output.='<td>'.&previous_tries($id,$target).'</td>';
 1291: 	    }
 1292: 	    $output.= '</tr></table>';
 1293: 	    return $output;
 1294: 	}
 1295:     }
 1296: }
 1297: 
 1298: sub previous_tries {
 1299:     my ($id,$target) = @_;
 1300:     my $output;
 1301:     my $status = $Apache::inputtags::status['-1'];
 1302: 
 1303:     my $count;
 1304:     my %count_lookup;
 1305: 
 1306:     foreach my $i (1..$Apache::lonhomework::history{'version'}) {
 1307: 	my $prefix = $i.":resource.$id";
 1308: 
 1309: 	next if (!exists($Apache::lonhomework::history{"$prefix.award"}));
 1310: 	$count++;
 1311: 	$count_lookup{$i} = $count;
 1312: 	
 1313: 	my ($previousmsg,$latemessage,$message,$trystr);
 1314: 
 1315: 	($previousmsg,$latemessage,$message,$trystr) =
 1316: 	    &get_grade_messages($id,"$prefix",$target,$status);
 1317: 
 1318: 	if ($previousmsg ne '') {
 1319: 	    my ($match,$which) = &find_which_previous($i);
 1320: 	    $message=$previousmsg;
 1321: 	    my $previous = $count_lookup{$which};
 1322: 	    $message =~ s{(</td>)}{ as submission \# $previous $1};
 1323: 	} elsif ($Apache::lonhomework::history{"$prefix.tries"}) {
 1324: 	    if (!(&Apache::lonhomework::hide_problem_status()
 1325: 		  && $Apache::inputtags::status[-1] ne 'SHOW_ANSWER')
 1326: 		&& $Apache::lonhomework::history{"$prefix.solved"} =~/^correct/
 1327: 		) {
 1328: 		
 1329:                 my $txt_correct = &mt('Correct');
 1330: 		$message =~ s{(<td.*?>)(.*?)(</td>)}
 1331:                              {$1 <strong>$txt_correct</strong>. $3}s;
 1332: 	    }
 1333:             my $trystr = "(".&mt('Try [_1]',$Apache::lonhomework::history{"$prefix.tries"}).")";
 1334: 	    $message =~ s{(</td>)}{ $trystr $1};
 1335: 	}
 1336: 	my ($class) = ($message =~ m{<td.*class="([^"]*)"}); #"
 1337: 	$message =~ s{(<td.*?>)}{<td>};
 1338: 	
 1339: 
 1340: 	$output.='<tr class="'.$class.'">';
 1341: 	$output.='<td align="center">'.$count.'</td>';
 1342: 	$output.=$message;
 1343: 
 1344: 	foreach my $resid (@Apache::inputtags::response) {
 1345: 	    my $prefix = $prefix.".$resid";
 1346: 	    if (exists($Apache::lonhomework::history{"$prefix.submission"})) {
 1347: 		my $submission =
 1348: 		    $Apache::inputtags::submission_display{"$prefix.submission"};
 1349: 		if (!defined($submission)) {
 1350: 		    $submission = 
 1351: 			$Apache::lonhomework::history{"$prefix.submission"};
 1352: 		}
 1353: 		$output.='<td>'.$submission.'</td>';
 1354: 	    } else {
 1355: 		$output.='<td></td>';
 1356: 	    }
 1357: 	}
 1358: 	$output.=&Apache::loncommon::end_data_table_row()."\n";
 1359:     }
 1360:     return if ($output eq '');
 1361:     my $headers = 
 1362: 	'<tr>'.'<th>'.&mt('Submission #').'</th><th>'.&mt('Try').
 1363: 	'</th><th colspan="'.scalar(@Apache::inputtags::response).'">'.
 1364: 	&mt('Submitted Answer').'</th>';
 1365:     $output ='<table class="LC_prior_tries">'.$headers.$output.'</table>';
 1366:     #return $output;
 1367:     $output = &Apache::loncommon::js_ready($output); 
 1368:     $output.='<br /><form action=""><center><input type="button" name="close" value="'.&mt('Close Window').'" onClick="window.close()" /></center></form>';
 1369: 
 1370:     my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
 1371:     my $start_page =
 1372: 	&Apache::loncommon::start_page('Previous Tries', undef,
 1373: 				       {'only_body'      => 1,
 1374: 					'bgcolor'        => '#FFFFFF',
 1375: 					'js_ready'       => 1,
 1376: 				        'inherit_jsmath' => 1, });
 1377:     my $end_page =
 1378: 	&Apache::loncommon::end_page({'js_ready' => 1,});
 1379:     my $prefix = $env{'form.request.prefix'};
 1380:     $prefix =~ tr{.}{_};
 1381:     my $function_name = "LONCAPA_previous_tries_".$prefix.
 1382: 	$Apache::lonxml::curdepth.'_'.$env{'form.counter'};
 1383:     my $result ="<script type=\"text/javascript\">
 1384: // <![CDATA[
 1385:     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()}
 1386: // ]]>
 1387: </script><a href=\"javascript:$function_name();void(0);\">".&mt("Previous Tries")."</a><br />";
 1388:     #use Data::Dumper;
 1389:     #&Apache::lonnet::logthis(&Dumper(\%Apache::inputtags::submission_display));
 1390:     return $result;
 1391: }
 1392: 
 1393: 1;
 1394: __END__
 1395: 
 1396: =pod
 1397: 
 1398: =back
 1399: 
 1400: =cut
 1401:  

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