File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.244: download - view: text, annotated - select for diffs
Sat Jul 26 19:11:23 2008 UTC (15 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_7_0, version_2_6_99_1, HEAD
- Add <br /> only when target is web.

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

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