File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.224: download - view: text, annotated - select for diffs
Mon May 21 22:57:17 2007 UTC (16 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- fix logic on when receipts should be displayed

    1: # The LearningOnline Network with CAPA
    2: # input  definitons
    3: #
    4: # $Id: inputtags.pm,v 1.224 2007/05/21 22:57:17 albertel 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 lib '/home/httpd/lib/perl/';
   35: use LONCAPA;
   36:  
   37: 
   38: BEGIN {
   39:     &Apache::lonxml::register('Apache::inputtags',('hiddenline','textfield','textline'));
   40: }
   41: 
   42: #   Initializes a set of global variables used during the parse of the problem.
   43: #
   44: #  @Apache::inputtags::input        - List of current input ids.
   45: #  @Apache::inputtags::inputlist    - List of all input ids seen this problem.
   46: #  @Apache::inputtags::response     - List of all current resopnse ids.
   47: #  @Apache::inputtags::responselist - List of all response ids seen this 
   48: #                                       problem.
   49: #  @Apache::inputtags::hint         - List of all hint ids.
   50: #  @Apache::inputtags::hintlist     - List of all hint ids seen this problem.
   51: #  @Apache::inputtags::previous     - List describing if specific responseds
   52: #                                       have been used
   53: #  @Apache::inputtags::previous_version - Submission responses were used in.
   54: #  $Apache::inputtags::part         - Current part id (valid only in 
   55: #                                       <problem>)
   56: #                                     0 if not in a part.
   57: #  @Apache::inputtags::partlist     - List of part ids seen in the current
   58: #                                       <problem>
   59: #  @Apache::inputtags::status       - List of problem  statuses. First 
   60: #                                     element is the status of the <problem>
   61: #                                     the remainder are for individual <part>s.
   62: #  %Apache::inputtags::params       - Hash of defined parameters for the
   63: #                                     current response.
   64: #  @Apache::inputtags::import       - List of all ids for <import> thes get
   65: #                                     join()ed and prepended.
   66: #  @Apache::inputtags::importlist   - List of all import ids seen.
   67: #  $Apache::inputtags::response_with_no_part
   68: #                                   - Flag set true if we have seen a response
   69: #                                     that is not inside a <part>
   70: #  %Apache::inputtags::answertxt    - <*response> tags store correct
   71: #                                     answer strings for display by <textline/>
   72: #                                     in this hash.
   73: #  %Apache::inputtags::submission_display
   74: #                                   - <*response> tags store improved display
   75: #                                     of submission strings for display by part
   76: #                                     end.
   77: 
   78: sub initialize_inputtags {
   79:     @Apache::inputtags::input=();
   80:     @Apache::inputtags::inputlist=();
   81:     @Apache::inputtags::response=();
   82:     @Apache::inputtags::responselist=();
   83:     @Apache::inputtags::hint=();
   84:     @Apache::inputtags::hintlist=();
   85:     @Apache::inputtags::previous=();
   86:     @Apache::inputtags::previous_version=();
   87:     $Apache::inputtags::part='';
   88:     @Apache::inputtags::partlist=();
   89:     @Apache::inputtags::status=();
   90:     %Apache::inputtags::params=();
   91:     @Apache::inputtags::import=();
   92:     @Apache::inputtags::importlist=();
   93:     $Apache::inputtags::response_with_no_part=0;
   94:     %Apache::inputtags::answertxt=();
   95:     %Apache::inputtags::submission_display=();
   96: }
   97: 
   98: sub check_for_duplicate_ids {
   99:     my %check;
  100:     foreach my $id (@Apache::inputtags::partlist,
  101: 		    @Apache::inputtags::responselist,
  102: 		    @Apache::inputtags::hintlist,
  103: 		    @Apache::inputtags::importlist) {
  104: 	$check{$id}++;
  105:     }
  106:     my @duplicates;
  107:     foreach my $id (sort(keys(%check))) {
  108: 	if ($check{$id} > 1) {
  109: 	    push(@duplicates,$id);
  110: 	}
  111:     }
  112:     if (@duplicates) {
  113: 	&Apache::lonxml::error("Duplicated ids found, problem will operate incorrectly. Duplicated ids seen: ",join(', ',@duplicates));
  114:     }
  115: }
  116: 
  117: sub start_input {
  118:     my ($parstack,$safeeval)=@_;
  119:     my $id = &Apache::lonxml::get_param('id',$parstack,$safeeval);
  120:     if ($id eq '') { $id = $Apache::lonxml::curdepth; }
  121:     push (@Apache::inputtags::input,$id);
  122:     push (@Apache::inputtags::inputlist,$id);
  123:     return $id;
  124: }
  125: 
  126: sub end_input {
  127:     pop @Apache::inputtags::input;
  128:     return '';
  129: }
  130: 
  131: sub addchars {
  132:     my ($fieldid,$addchars)=@_;
  133:     my $output='';
  134:     foreach (split(/\,/,$addchars)) {
  135: 	$output.='<a href="javascript:void(document.forms.lonhomework.'.
  136: 	    $fieldid.'.value+=\''.$_.'\')">'.$_.'</a> ';
  137:     }
  138:     return $output;
  139: }
  140: 
  141: sub start_textfield {
  142:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  143:     my $result = "";
  144:     my $id = &start_input($parstack,$safeeval);
  145:     my $resid=$Apache::inputtags::response[-1];
  146:     if ($target eq 'web') {
  147: 	$Apache::lonxml::evaluate--;
  148: 	my $partid=$Apache::inputtags::part;
  149: 	my $oldresponse = &HTML::Entities::encode($Apache::lonhomework::history{"resource.$partid.$resid.submission"},'<>&"');
  150: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  151: 	    my $cols = &Apache::lonxml::get_param('cols',$parstack,$safeeval);
  152: 	    if ( $cols eq '') { $cols = 80; }
  153: 	    my $rows = &Apache::lonxml::get_param('rows',$parstack,$safeeval);
  154: 	    if ( $rows eq '') { $rows = 16; }
  155: 	    my $addchars=&Apache::lonxml::get_param('addchars',$parstack,$safeeval);
  156: 	    $result='';
  157: 	    if ($addchars) {
  158: 		$result.=&addchars('HWVAL_'.$resid,$addchars);
  159: 	    }
  160: 	    &Apache::lonhtmlcommon::add_htmlareafields('HWVAL_'.$resid);
  161: 	    $result.= '<textarea wrap="hard" name="HWVAL_'.$resid.'" id="HWVAL_'.$resid.'" '.
  162: 		"rows=\"$rows\" cols=\"$cols\">".$oldresponse;
  163: 	    if ($oldresponse ne '') {
  164: 
  165: 		#get rid of any startup text if the user has already responded
  166: 		&Apache::lonxml::get_all_text("/textfield",$parser,$style);
  167: 	    }
  168: 	} else {
  169: 	    #show past answer in the essayresponse case
  170: 	    if ($oldresponse =~ /\S/
  171: 		&& &Apache::londefdef::is_inside_of($tagstack,
  172: 						    'essayresponse') ) {
  173: 		$result='<table class="LC_pastsubmission"><tr><td>'.
  174: 		    $oldresponse.'</td></tr></table>';
  175: 	    }
  176: 	    #get rid of any startup text
  177: 	    &Apache::lonxml::get_all_text("/textfield",$parser,$style);
  178: 	}
  179:     } elsif ($target eq 'grade') {
  180: 	my $seedtext=&Apache::lonxml::get_all_text("/textfield",$parser,
  181: 						   $style);
  182: 	if ($seedtext eq $env{'form.HWVAL_'.$resid}) {
  183: 	    # if the seed text is still there it wasn't a real submission
  184: 	    $env{'form.HWVAL_'.$resid}='';
  185: 	}
  186:     } elsif ($target eq 'edit') {
  187: 	$result.=&Apache::edit::tag_start($target,$token);
  188: 	$result.=&Apache::edit::text_arg('Rows:','rows',$token,4);
  189: 	$result.=&Apache::edit::text_arg('Columns:','cols',$token,4);
  190: 	$result.=&Apache::edit::text_arg
  191: 	    ('Click-On Texts (comma sep):','addchars',$token,10);
  192: 	my $bodytext=&Apache::lonxml::get_all_text("/textfield",$parser,
  193: 						   $style);
  194: 	$result.=&Apache::edit::editfield($token->[1],$bodytext,'Text you want to appear by default:',80,2);
  195:     } elsif ($target eq 'modified') {
  196: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  197: 						     $safeeval,'rows','cols',
  198: 						     'addchars');
  199: 	if ($constructtag) {
  200: 	    $result = &Apache::edit::rebuild_tag($token);
  201: 	} else {
  202: 	    $result=$token->[4];
  203: 	}
  204: 	$result.=&Apache::edit::modifiedfield("/textfield",$parser);
  205:     } elsif ($target eq 'tex') {
  206: 	my $number_of_lines = &Apache::lonxml::get_param('rows',$parstack,$safeeval);
  207: 	my $width_of_box = &Apache::lonxml::get_param('cols',$parstack,$safeeval);
  208: 	if ($$tagstack[-2] eq 'essayresponse' and $Apache::lonhomework::type eq 'exam') {
  209: 	    $result = '\fbox{\fbox{\parbox{\textwidth-5mm}{';
  210: 	    for (my $i=0;$i<int $number_of_lines*2;$i++) {$result.='\strut \\\\ ';}
  211: 	    $result.='\strut \\\\\strut \\\\\strut \\\\\strut \\\\}}}';
  212: 	} else {
  213: 	    my $TeXwidth=$width_of_box/80;
  214: 	    $result = '\vskip 1 mm \fbox{\fbox{\parbox{'.$TeXwidth.'\textwidth-5mm}{';
  215: 	    for (my $i=0;$i<int $number_of_lines*2;$i++) {$result.='\strut \\\\ ';}
  216: 	    $result.='}}}\vskip 2 mm ';
  217: 	}
  218:     }
  219:     return $result;
  220: }
  221: 
  222: sub end_textfield {
  223:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  224:     my $result;
  225:     if ($target eq 'web') {
  226: 	$Apache::lonxml::evaluate++;
  227: 	if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  228: 	    return "</textarea>";
  229: 	}
  230:     } elsif ($target eq 'edit') {
  231: 	$result=&Apache::edit::end_table();
  232:     }
  233:     &end_input;
  234:     return $result;
  235: }
  236: 
  237: sub exam_score_line {
  238:     my ($target) = @_;
  239: 
  240:     my $result;
  241:     if ($target eq 'tex') {
  242: 	my $repetition = &Apache::response::repetition();
  243: 	$result.='\begin{enumerate}';
  244: 	if ($env{'request.state'} eq "construct" ) {$result.='\item[\strut]';}
  245: 	foreach my $i (0..$repetition-1) {
  246: 	    $result.='\item[\textbf{'.
  247: 		($Apache::lonxml::counter+$i).
  248: 		'}.]\textit{Leave blank on scoring form}\vskip 0 mm';
  249: 	}
  250: 	$result.= '\end{enumerate}';
  251:     }
  252: 
  253:     return $result;
  254: }
  255: 
  256: sub exam_box {
  257:     my ($target) = @_;
  258:     my $result;
  259: 
  260:     if ($target eq 'tex') {
  261: 	$result .= '\fbox{\fbox{\parbox{\textwidth-5mm}{\strut\\\\\strut\\\\\strut\\\\\strut\\\\}}}';
  262: 	$result .= &exam_score_line($target);
  263:     } elsif ($target eq 'web') {
  264: 	my $id=$Apache::inputtags::response[-1];
  265: 	$result.= '<br /><br />
  266:                    <textarea name="HWVAL_'.$id.'" rows="4" cols="50">
  267:                    </textarea> <br /><br />';
  268:     }
  269:     return $result;
  270: }
  271: 
  272: sub needs_exam_box {
  273:     my ($tagstack) = @_;
  274:     my @tags = ('formularesponse',
  275: 		'stringresponse',
  276: 		'reactionresponse',
  277: 		'organicresponse',
  278: 		);
  279: 
  280:     foreach my $tag (@tags) {
  281: 	if (grep(/\Q$tag\E/,@$tagstack)) {
  282: 	    return 1;
  283: 	}
  284:     }
  285:     return 0;
  286: }
  287: 
  288: sub start_textline {
  289:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  290:     my $result = "";
  291:     my $input_id = &start_input($parstack,$safeeval);
  292:     if ($target eq 'web') {
  293: 	$Apache::lonxml::evaluate--;
  294: 	my $partid=$Apache::inputtags::part;
  295: 	my $id=$Apache::inputtags::response[-1];
  296: 	if (!&Apache::response::show_answer()) {
  297: 	    my $size = &Apache::lonxml::get_param('size',$parstack,$safeeval);
  298: 	    my $maxlength;
  299: 	    if ($size eq '') { $size=20; } else {
  300: 		if ($size < 20) {
  301: 		    $maxlength = ' maxlength="'.$size.'"';
  302: 		}
  303: 	    }
  304: 	    my $oldresponse = $Apache::lonhomework::history{"resource.$partid.$id.submission"};
  305: 	    &Apache::lonxml::debug("oldresponse $oldresponse is ".ref($oldresponse));
  306: 
  307: 	    if (ref($oldresponse) eq 'ARRAY') {
  308: 		$oldresponse = $oldresponse->[$#Apache::inputtags::inputlist];
  309: 	    }
  310: 	    $oldresponse = &HTML::Entities::encode($oldresponse,'<>&"');
  311: 
  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=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 finalizeawards {
  545:     my ($awardref,$msgref,$nameref,$reverse)=@_;
  546:     my $result;
  547:     if ($#$awardref == -1) { $result = "NO_RESPONSE"; }
  548:     if ($result eq '' ) {
  549: 	my $blankcount;
  550: 	foreach my $award (@$awardref) {
  551: 	    if ($award eq '') {
  552: 		$result='MISSING_ANSWER';
  553: 		$blankcount++;
  554: 	    }
  555: 	}
  556: 	if ($blankcount == ($#$awardref + 1)) { $result = 'NO_RESPONSE'; }
  557:     }
  558:     if (defined($result)) { return ($result); }
  559: 
  560:     # these awards are ordered from most important error through best correct
  561:     my $awards = (!$reverse) ? \%fwd_awards : \%rev_awards ;
  562: 
  563:     my $best = $max;
  564:     my $j=0;
  565:     my $which;
  566:     foreach my $award (@$awardref) {
  567: 	if ($awards->{$award} < $best) {
  568: 	    $best  = $awards->{$award};
  569: 	    $which = $j;
  570: 	}
  571: 	$j++;
  572:     }
  573:     if (defined($which)) {
  574: 	if (ref($nameref)) {
  575: 	    return ($$awardref[$which],$$msgref[$which],$$nameref[$which]);
  576: 	} else {
  577: 	    return ($$awardref[$which],$$msgref[$which]);
  578: 	}
  579:     }
  580:     return ('ERROR',undef);
  581: }
  582: }
  583: 
  584: sub decideoutput {
  585:     my ($award,$awarded,$awardmsg,$solved,$previous,$target)=@_;
  586:     my $message='';
  587:     my $button=0;
  588:     my $previousmsg;
  589:     my $css_class='orange';
  590:     my $added_computer_text=0;
  591:     my %possible_class =
  592: 	( 'correct'         => 'LC_answer_correct',
  593: 	  'charged_try'     => 'LC_answer_charged_try',
  594: 	  'not_charged_try' => 'LC_answer_not_charged_try',
  595: 	  'no_grade'        => 'LC_answer_no_grade',
  596: 	  'no_message'      => 'LC_no_message',
  597: 	  );
  598: 
  599:     my $part = $Apache::inputtags::part;
  600:     my $handgrade = 
  601: 	('yes' eq lc(&Apache::lonnet::EXT("resource.$part.handgrade")));
  602:     
  603:     my $computer = ($handgrade)? ''
  604: 	                       : " ".&mt("Computer's answer now shown above.");
  605:     &Apache::lonxml::debug("handgrade has :$handgrade:");
  606: 
  607:     if ($previous) { $previousmsg=&mt('You have entered that answer before'); }
  608:     
  609:     if ($solved =~ /^correct/) {
  610:         $css_class=$possible_class{'correct'};
  611: 	$message=&mt('You are correct.');
  612: 	if ($awarded < 1 && $awarded > 0) {
  613: 	    $message=&mt('You are partially correct.');
  614: 	    $css_class=$possible_class{'not_charged_try'};
  615: 	} elsif ($awarded < 1) {
  616: 	    $message=&mt('Incorrect.');
  617: 	    $css_class=$possible_class{'charged_try'};
  618: 	}
  619: 	if ($env{'request.filename'} =~ 
  620: 	    m|/res/lib/templates/examupload.problem$|) {
  621: 	    $message = &mt("A score has been assigned.");
  622: 	    $added_computer_text=1;
  623: 	} else {
  624: 	    if ($target eq 'tex') {
  625: 		$message = '\textbf{'.$message.'}';
  626: 	    } else {
  627: 		$message = "<b>".$message."</b>";
  628: 		$message.= $computer;
  629: 	    }
  630: 	    $added_computer_text=1;
  631: 	    my ($symb) = &Apache::lonnet::whichuser();
  632: 	    if (($symb ne '') 
  633: 		&&
  634: 		($env{'course.'.$env{'request.course.id'}.
  635: 			    '.disable_receipt_display'} ne 'yes')) { 
  636: 		$message.=(($target eq 'web')?'<br />':' ').
  637: 		    &mt('Your receipt is').' '.&Apache::lonnet::receipt($Apache::inputtags::part).
  638: 		    (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'');
  639: 	    }
  640: 	    &Apache::lonnet::logthis(" er \n$symb\n$message\n".$env{'course.'.
  641: 			     $env{'request.course.id'}.
  642: 			     '.disable_receipt_display'});
  643: 	}
  644: 	$button=0;
  645: 	$previousmsg='';
  646:     } elsif ($solved =~ /^excused/) {
  647: 	if ($target eq 'tex') {
  648: 	    $message = ' \textbf{'.&mt('You are excused from the problem.').'} ';
  649: 	} else {
  650: 	    $message = "<b>".&mt('You are excused from the problem.')."</b>";
  651: 	}
  652: 	$css_class=$possible_class{'charged_try'};
  653: 	$button=0;
  654: 	$previousmsg='';
  655:     } elsif ($award eq 'EXACT_ANS' || $award eq 'APPROX_ANS' ) {
  656: 	if ($solved =~ /^incorrect/ || $solved eq '') {
  657: 	    $message = &mt("Incorrect").".";
  658: 	    $css_class=$possible_class{'charged_try'};
  659: 	    $button=1;
  660: 	} else {
  661: 	    if ($target eq 'tex') {
  662: 		$message = '\textbf{'.&mt('You are correct.').'}';
  663: 	    } else {
  664: 		$message = "<b>".&mt('You are correct.')."</b>";
  665: 		$message.= $computer;
  666: 	    }
  667: 	    $added_computer_text=1;
  668: 	    unless ($env{'course.'.
  669: 			     $env{'request.course.id'}.
  670: 			     '.disable_receipt_display'} eq 'yes') { 
  671: 		$message.=(($target eq 'web')?'<br />':' ').
  672: 		    'Your receipt is '.&Apache::lonnet::receipt($Apache::inputtags::part).
  673: 		    (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'');
  674: 	    }
  675: 	    $css_class=$possible_class{'correct'};
  676: 	    $button=0;
  677: 	    $previousmsg='';
  678: 	}
  679:     } elsif ($award eq 'NO_RESPONSE') {
  680: 	$message = '';
  681: 	$css_class=$possible_class{'no_feedback'};
  682: 	$button=1;
  683:     } elsif ($award eq 'EXTRA_ANSWER') {
  684: 	$message = &mt('Some extra items were submitted.');
  685: 	$css_class=$possible_class{'not_charged_try'};
  686: 	$button = 1;
  687:     } elsif ($award eq 'MISSING_ANSWER') {
  688: 	$message = &mt('Some items were not submitted.');
  689: 	$css_class=$possible_class{'not_charged_try'};
  690: 	$button = 1;
  691:     } elsif ($award eq 'ERROR') {
  692: 	$message = &mt('An error occured while grading your answer.');
  693: 	$css_class=$possible_class{'not_charged_try'};
  694: 	$button = 1;
  695:     } elsif ($award eq 'TOO_LONG') {
  696: 	$message = &mt("The submitted answer was too long.");
  697: 	$css_class=$possible_class{'not_charged_try'};
  698: 	$button=1;
  699:     } elsif ($award eq 'WANTED_NUMERIC') {
  700: 	$message = &mt("This question expects a numeric answer.");
  701: 	$css_class=$possible_class{'not_charged_try'};
  702: 	$button=1;
  703:     } elsif ($award eq 'MISORDERED_RANK') {
  704: 	$message = &mt('You have provided an invalid ranking');
  705: 	if ($target ne 'tex') {
  706: 	    $message.=', '.&mt('please refer to').' '.&Apache::loncommon::help_open_topic('Ranking_Problems','help on ranking problems');
  707: 	}
  708: 	$css_class=$possible_class{'not_charged_try'};
  709: 	$button=1;
  710:     } elsif ($award eq 'INVALID_FILETYPE') {
  711: 	$message = &mt('Submission won\'t be graded. The type of file submitted is not allowed.');
  712: 	$css_class=$possible_class{'not_charged_try'};
  713: 	$button=1;
  714:     } elsif ($award eq 'SIG_FAIL') {
  715: 	my ($used,$min,$max)=split(':',$awardmsg);
  716: 	my $word = ($used < $min) ? 'more' : 'fewer';
  717: 	$message = &mt("Submission not graded.  Use $word digits.",$used);
  718: 	$css_class=$possible_class{'not_charged_try'};
  719: 	$button=1;
  720:     } elsif ($award eq 'UNIT_INVALID_INSTRUCTOR') {
  721: 	$message = &mt('Error in instructor specifed unit. This error has been reported to the instructor.', $awardmsg);
  722: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
  723: 	$css_class=$possible_class{'not_charged_try'};
  724: 	$button=1;
  725:     } elsif ($award eq 'UNIT_INVALID_STUDENT') {
  726: 	$message = &mt('Unable to interpret units. Computer reads units as "[_1]".',&markup_unit($awardmsg,$target));
  727: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
  728: 	$css_class=$possible_class{'not_charged_try'};
  729: 	$button=1;
  730:     } elsif ($award eq 'UNIT_FAIL' || $award eq 'UNIT_IRRECONCIBLE') {
  731: 	$message = &mt('Incompatible units. No conversion found between "[_1]" and the required units.',&markup_unit($awardmsg,$target));
  732: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
  733: 	$css_class=$possible_class{'not_charged_try'};
  734: 	$button=1;
  735:     } elsif ($award eq 'UNIT_NOTNEEDED') {
  736: 	$message = &mt('Only a number required. Computer reads units of "[_1]".',&markup_unit($awardmsg,$target));
  737: 	$css_class=$possible_class{'not_charged_try'};
  738: 	$button=1;
  739:     } elsif ($award eq 'NO_UNIT') {
  740: 	$message = &mt("Units required").'.';
  741: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units')};
  742: 	$css_class=$possible_class{'not_charged_try'};
  743: 	$button=1;
  744:     } elsif ($award eq 'COMMA_FAIL') {
  745: 	$message = &mt("Proper comma separation is required").'.';
  746: 	$css_class=$possible_class{'not_charged_try'};
  747: 	$button=1;
  748:     } elsif ($award eq 'BAD_FORMULA') {
  749: 	$message = &mt("Unable to understand formula");
  750: 	$css_class=$possible_class{'not_charged_try'};
  751: 	$button=1;
  752:     } elsif ($award eq 'INCORRECT') {
  753: 	$message = &mt("Incorrect").'.';
  754: 	$css_class=$possible_class{'charged_try'};
  755: 	$button=1;
  756:     } elsif ($award eq 'SUBMITTED') {
  757: 	$message = &mt("Your submission has been recorded.");
  758: 	$css_class=$possible_class{'no_grade'};
  759: 	$button=1;
  760:     } elsif ($award eq 'DRAFT') {
  761: 	$message = &mt("A draft copy has been saved.");
  762: 	$css_class=$possible_class{'not_charged_try'};
  763: 	$button=1;
  764:     } elsif ($award eq 'ASSIGNED_SCORE') {
  765: 	$message = &mt("A score has been assigned.");
  766: 	$css_class=$possible_class{'correct'};
  767: 	$button=0;
  768:     } elsif ($award eq '') {
  769: 	if ($handgrade && $Apache::inputtags::status[-1] eq 'SHOW_ANSWER') {
  770: 	    $message = &mt("Nothing submitted.");
  771: 	    $css_class=$possible_class{'charged_try'};
  772: 	} else {
  773: 	    $css_class=$possible_class{'not_charged_try'};
  774: 	}
  775: 	$button=1;
  776:     } else {
  777: 	$message = &mt("Unknown message").": $award";
  778: 	$button=1;
  779:     }
  780:     my (undef,undef,$domain,$user)=&Apache::lonnet::whichuser();
  781:     foreach my $resid(@Apache::inputtags::response){
  782:         if ($Apache::lonhomework::history{"resource.$part.$resid.handback"}) {
  783: 	    $message.='<br />';
  784: 	    my @files = split(/\s*,\s*/,
  785: 			      $Apache::lonhomework::history{"resource.$part.$resid.handback"});
  786: 	    my $file_msg;
  787: 	    foreach my $file (@files) {
  788: 		$file_msg.= '<br /><a href="/uploaded/'."$domain/$user".'/'.$file.'">'.$file.'</a>';
  789: 	    }
  790: 	    $message .= &mt('Returned file(s): [_1]',$file_msg);
  791: 	}
  792:     }
  793: 
  794:     if (lc($Apache::lonhomework::problemstatus) eq 'no'  && 
  795: 	$Apache::inputtags::status[-1] ne 'SHOW_ANSWER') {
  796: 	$message = &mt("Answer Submitted: Your final submission will be graded after the due date.");
  797: 	$css_class=$possible_class{'no_grade'};
  798: 	$button=1;
  799:     }
  800:     if ($Apache::inputtags::status[-1] eq 'SHOW_ANSWER' && 
  801: 	!$added_computer_text && $target ne 'tex') {
  802: 	$message.= $computer;
  803: 	$added_computer_text=1;
  804:     }
  805:     return ($button,$css_class,$message,$previousmsg);
  806: }
  807: 
  808: sub markup_unit {
  809:     my ($unit,$target)=@_;
  810:     if ($target eq 'tex') {
  811: 	return '\texttt{'.&Apache::lonxml::latex_special_symbols($unit).'}'; 
  812:     } else {
  813: 	return "<tt>".$unit."</tt>";
  814:     }
  815: }
  816: 
  817: sub removealldata {
  818:     my ($id)=@_;
  819:     foreach my $key (keys(%Apache::lonhomework::results)) {
  820: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
  821: 	    &Apache::lonxml::debug("Removing $key");
  822: 	    delete($Apache::lonhomework::results{$key});
  823: 	}
  824:     }
  825: }
  826: 
  827: sub hidealldata {
  828:     my ($id)=@_;
  829:     foreach my $key (keys(%Apache::lonhomework::results)) {
  830: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
  831: 	    &Apache::lonxml::debug("Hidding $key");
  832: 	    my $newkey=$key;
  833: 	    $newkey=~s/^(resource\.\Q$id\E\.[^\.]+\.)(.*)$/${1}hidden${2}/;
  834: 	    $Apache::lonhomework::results{$newkey}=
  835: 		$Apache::lonhomework::results{$key};
  836: 	    delete($Apache::lonhomework::results{$key});
  837: 	}
  838:     }
  839: }
  840: 
  841: sub setgradedata {
  842:     my ($award,$msg,$id,$previously_used) = @_;
  843:     if ($Apache::lonhomework::scantronmode && 
  844: 	&Apache::lonnet::validCODE($env{'form.CODE'})) {
  845: 	$Apache::lonhomework::results{"resource.CODE"}=$env{'form.CODE'};
  846:     } elsif ($Apache::lonhomework::scantronmode && 
  847: 	     $env{'form.CODE'} eq '' &&
  848: 	     $Apache::lonhomework::history{"resource.CODE"} ne '') {
  849: 	$Apache::lonhomework::results{"resource.CODE"}='';
  850:     }
  851: 
  852:     if (!$Apache::lonhomework::scantronmode &&
  853: 	$Apache::inputtags::status['-1'] ne 'CAN_ANSWER' &&
  854: 	$Apache::inputtags::status['-1'] ne 'CANNOT_ANSWER') {
  855: 	$Apache::lonhomework::results{"resource.$id.afterduedate"}=$award;
  856: 	return '';
  857:     } elsif ( $Apache::lonhomework::history{"resource.$id.solved"} !~
  858: 	      /^correct/ || $Apache::lonhomework::scantronmode ||
  859: 	      lc($Apache::lonhomework::problemstatus) eq 'no') {
  860:         # the student doesn't already have it correct,
  861: 	# or we are in a mode (scantron orno problem status) where a correct 
  862:         # can become incorrect
  863: 	# handle assignment of tries and solved status
  864: 	my $solvemsg;
  865: 	if ($Apache::lonhomework::scantronmode) {
  866: 	    $solvemsg='correct_by_scantron';
  867: 	} else {
  868: 	    $solvemsg='correct_by_student';
  869: 	}
  870: 	if ($Apache::lonhomework::history{"resource.$id.afterduedate"}) {
  871: 	    $Apache::lonhomework::results{"resource.$id.afterduedate"}='';
  872: 	}
  873: 	if ( $award eq 'ASSIGNED_SCORE') {
  874: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
  875: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
  876: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  877: 		$solvemsg;
  878: 	    my $numawards=scalar(@Apache::inputtags::response);
  879: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = 0;
  880: 	    foreach my $res (@Apache::inputtags::response) {
  881: 		$Apache::lonhomework::results{"resource.$id.awarded"}+=
  882: 		    $Apache::lonhomework::results{"resource.$id.$res.awarded"};
  883: 	    }
  884: 	    if ($numawards > 0) {
  885: 		$Apache::lonhomework::results{"resource.$id.awarded"}/=
  886: 		    $numawards;
  887: 	    }
  888: 	} elsif ( $award eq 'APPROX_ANS' || $award eq 'EXACT_ANS' ) {
  889: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
  890: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
  891: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  892: 		$solvemsg;
  893: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
  894: 	} elsif ( $award eq 'INCORRECT' ) {
  895: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
  896: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
  897: 	    if (lc($Apache::lonhomework::problemstatus) eq 'no' ||
  898: 		$Apache::lonhomework::scantronmode) {
  899: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
  900: 	    }
  901: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  902: 		'incorrect_attempted';
  903: 	} elsif ( $award eq 'SUBMITTED' ) {
  904: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
  905: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
  906: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  907: 		'ungraded_attempted';
  908: 	} elsif ( $award eq 'DRAFT' ) {
  909: 	    $Apache::lonhomework::results{"resource.$id.solved"} = '';
  910: 	} elsif ( $award eq 'NO_RESPONSE' ) {
  911: 	    #no real response so delete any data that got stored
  912: 	    &removealldata($id);
  913: 	    return '';
  914: 	} else {
  915: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  916: 		'incorrect_attempted';
  917: 	    if (lc($Apache::lonhomework::problemstatus) eq 'no' ||
  918: 		$Apache::lonhomework::scantronmode) {
  919: 		$Apache::lonhomework::results{"resource.$id.tries"} =
  920: 		    $Apache::lonhomework::history{"resource.$id.tries"} + 1;
  921: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
  922: 	    }
  923: 	}
  924: 	if (defined($msg)) {
  925: 	    $Apache::lonhomework::results{"resource.$id.awardmsg"} = $msg;
  926: 	}
  927: 	# did either of the overall awards chage? If so ignore the 
  928: 	# previous check
  929: 	if (($Apache::lonhomework::results{"resource.$id.awarded"} eq
  930: 	     $Apache::lonhomework::history{"resource.$id.awarded"}) &&
  931: 	    ($Apache::lonhomework::results{"resource.$id.solved"} eq
  932: 	     $Apache::lonhomework::history{"resource.$id.solved"})) {
  933: 	    # check if this was a previous submission if it was delete the
  934: 	    # unneeded data and update the previously_used attribute
  935: 	    if ( $previously_used eq 'PREVIOUSLY_USED') {
  936: 		if (lc($Apache::lonhomework::problemstatus) ne 'no') {
  937: 		    delete($Apache::lonhomework::results{"resource.$id.tries"});
  938: 		    $Apache::lonhomework::results{"resource.$id.previous"} = '1';
  939: 		}
  940: 	    } elsif ( $previously_used eq 'PREVIOUSLY_LAST') {
  941: 		#delete all data as they student didn't do anything, but save
  942: 		#the list of collaborators.
  943: 		&removealldata($id);
  944: 		#and since they didn't do anything we were never here
  945: 		return '';
  946: 	    } else {
  947: 		$Apache::lonhomework::results{"resource.$id.previous"} = '0';
  948: 	    }
  949: 	}
  950:     } elsif ( $Apache::lonhomework::history{"resource.$id.solved"} =~
  951: 	      /^correct/ ) {
  952: 	#delete all data as they student already has it correct
  953: 	&removealldata($id);
  954: 	#and since they didn't do anything we were never here
  955: 	return '';
  956:     }
  957:     $Apache::lonhomework::results{"resource.$id.award"} = $award;
  958:     if ($award eq 'SUBMITTED') {
  959: 	&Apache::response::add_to_gradingqueue();
  960:     }
  961: }
  962: 
  963: sub find_which_previous {
  964:     my ($version) = @_;
  965:     my $part = $Apache::inputtags::part;
  966:     my (@previous_version);
  967:     foreach my $resp (@Apache::inputtags::response) {
  968: 	my $key = "$version:resource.$part.$resp.submission";
  969: 	my $submission = $Apache::lonhomework::history{$key};
  970: 	my %previous = &Apache::response::check_for_previous($submission,
  971: 							     $part,$resp,
  972: 							     $version);
  973: 	push(@previous_version,$previous{'version'});
  974:     }
  975:     return &previous_match(\@previous_version,
  976: 			   scalar(@Apache::inputtags::response));
  977: }
  978: 
  979: sub previous_match {
  980:     my ($previous_array,$count) = @_;
  981:     my $match = 0;
  982:     my @matches;
  983:     foreach my $versionar (@$previous_array) {
  984: 	foreach my $version (@$versionar) {
  985: 	    $matches[$version]++;
  986: 	}
  987:     }
  988:     my $which=0;
  989:     foreach my $elem (@matches) {
  990: 	if ($elem eq $count) {
  991: 	    $match=1;
  992: 	    last;
  993: 	}
  994: 	$which++;
  995:     }
  996:     return ($match,$which);
  997: }
  998: 
  999: sub grade {
 1000:     my ($target) = @_;
 1001:     my $id = $Apache::inputtags::part;
 1002:     my $response='';
 1003:     if ( defined $env{'form.submitted'}) {
 1004: 	my (@awards,@msgs);
 1005: 	foreach $response (@Apache::inputtags::response) {
 1006: 	    &Apache::lonxml::debug("looking for response.$id.$response.awarddetail");
 1007: 	    my $value=$Apache::lonhomework::results{"resource.$id.$response.awarddetail"};
 1008: 	    &Apache::lonxml::debug("keeping $value from $response for $id");
 1009: 	    push (@awards,$value);
 1010: 	    $value=$Apache::lonhomework::results{"resource.$id.$response.awardmsg"};
 1011: 	    &Apache::lonxml::debug("got message $value from $response for $id");
 1012: 	    push (@msgs,$value);
 1013: 	}
 1014: 	my ($finalaward,$msg) = &finalizeawards(\@awards,\@msgs);
 1015: 	my $previously_used;
 1016: 	if ( $#Apache::inputtags::previous eq $#awards ) {
 1017: 	    my ($match) =
 1018: 		&previous_match(\@Apache::inputtags::previous_version,
 1019: 				scalar(@Apache::inputtags::response));
 1020: 	    
 1021: 	    if ($match) {
 1022: 		$previously_used = 'PREVIOUSLY_LAST';
 1023: 		foreach my $value (@Apache::inputtags::previous) {
 1024: 		    if ($value eq 'PREVIOUSLY_USED' ) {
 1025: 			$previously_used = $value;
 1026: 			last;
 1027: 		    }
 1028: 		}
 1029: 	    }
 1030: 	}
 1031: 	&Apache::lonxml::debug("final award $finalaward, $previously_used, message $msg");
 1032: 	&setgradedata($finalaward,$msg,$id,$previously_used);
 1033:     }
 1034:     return '';
 1035: }
 1036: 
 1037: sub get_grade_messages {
 1038:     my ($id,$prefix,$target,$status) = @_;
 1039: 
 1040:     my ($message,$latemessage,$trystr,$previousmsg);
 1041:     my $showbutton = 1;
 1042: 
 1043:     my $award = $Apache::lonhomework::history{"$prefix.award"};
 1044:     my $awarded = $Apache::lonhomework::history{"$prefix.awarded"};
 1045:     my $solved = $Apache::lonhomework::history{"$prefix.solved"};
 1046:     my $previous = $Apache::lonhomework::history{"$prefix.previous"};
 1047:     my $awardmsg = $Apache::lonhomework::history{"$prefix.awardmsg"};
 1048:     &Apache::lonxml::debug("Found Award |$award|$solved|$awardmsg");
 1049:     if ( $award ne '' || $solved ne '' || $status eq 'SHOW_ANSWER') {
 1050: 	&Apache::lonxml::debug('Getting message');
 1051: 	($showbutton,my $css_class,$message,$previousmsg) =
 1052: 	    &decideoutput($award,$awarded,$awardmsg,$solved,$previous,
 1053: 			  $target);
 1054: 	if ($target eq 'tex') {
 1055: 	    $message='\vskip 2 mm '.$message.' ';
 1056: 	} else {
 1057: 	    $message="<td class=\"$css_class\">$message</td>";
 1058: 	    if ($previousmsg) {
 1059: 		$previousmsg="<td class=\"LC_answer_previous\">$previousmsg</td>";
 1060: 	    }
 1061: 	}
 1062:     }
 1063:     my $tries = $Apache::lonhomework::history{"$prefix.tries"};
 1064:     my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
 1065:     &Apache::lonxml::debug("got maxtries of :$maxtries:");
 1066:     #if tries are set to negative turn off the Tries/Button and messages
 1067:     if (defined($maxtries) && $maxtries < 0) { return ''; }
 1068:     if ( $tries eq '' ) { $tries = '0'; }
 1069:     if ( $maxtries eq '' ) { $maxtries = '2'; } 
 1070:     if ( $maxtries eq 'con_lost' ) { $maxtries = '0'; } 
 1071:     my $tries_text=&mt('Tries');
 1072:     if ( $Apache::lonhomework::type eq 'survey' ||
 1073: 	 $Apache::lonhomework::parsing_a_task) {
 1074: 	$tries_text=&mt('Submissions');
 1075:     }
 1076: 
 1077:     if ($showbutton) {
 1078: 	if ($target eq 'tex') {
 1079: 	    if ($env{'request.state'} ne "construct"
 1080: 		&& $Apache::lonhomework::type ne 'exam'
 1081: 		&& $env{'form.suppress_tries'} ne 'yes') {
 1082: 		$trystr = ' {\vskip 1 mm \small \textit{'.$tries_text.'} '.
 1083: 		    $tries.'/'.$maxtries.'} \vskip 2 mm ';
 1084: 	    } else {
 1085: 		$trystr = '\vskip 0 mm ';
 1086: 	    }
 1087: 	} else {
 1088: 	    $trystr = "<td><nobr>".$tries_text." $tries";
 1089: 	    if ($Apache::lonhomework::parsing_a_task) {
 1090: 	    } elsif($env{'request.state'} ne 'construct') {
 1091: 		$trystr.="/$maxtries";
 1092: 	    } else {
 1093: 		if (defined($Apache::inputtags::params{'maxtries'})) {
 1094: 		    $trystr.="/".$Apache::inputtags::params{'maxtries'};
 1095: 		}
 1096: 	    }
 1097: 	    $trystr.="</nobr></td>";
 1098: 	}
 1099:     }
 1100: 
 1101:     if ($Apache::lonhomework::history{"$prefix.afterduedate"}) {
 1102: 	#last submissions was after due date
 1103: 	$latemessage=&mt(' The last submission was after the Due Date ');;
 1104: 	if ($target eq 'web') {
 1105: 	    $latemessage='<td class="LC_answer_late">'.$latemessage.'</td>';
 1106: 	}
 1107:     }
 1108:     return ($previousmsg,$latemessage,$message,$trystr,$showbutton);
 1109: }
 1110: 
 1111: sub gradestatus {
 1112:     my ($id,$target,$no_previous) = @_;
 1113:     my $showbutton = 1;
 1114:     my $message = '';
 1115:     my $latemessage = '';
 1116:     my $trystr='';
 1117:     my $button='';
 1118:     my $previousmsg='';
 1119: 
 1120:     my $status = $Apache::inputtags::status['-1'];
 1121:     &Apache::lonxml::debug("gradestatus has :$status:");
 1122:     if ( $status ne 'CLOSED' 
 1123: 	 && $status ne 'UNAVAILABLE' 
 1124: 	 && $status ne 'INVALID_ACCESS' 
 1125: 	 && $status ne 'NEEDS_CHECKIN' 
 1126: 	 && $status ne 'NOT_IN_A_SLOT') {  
 1127: 
 1128: 	($previousmsg,$latemessage,$message,$trystr) =
 1129: 	    &get_grade_messages($id,"resource.$id",$target,$status,
 1130: 				$showbutton);
 1131: 	if ( $status eq 'SHOW_ANSWER' || $status eq 'CANNOT_ANSWER') {
 1132: 	    $showbutton = 0;
 1133: 	}
 1134: 	if ( $status eq 'SHOW_ANSWER') {
 1135: 	    undef($previousmsg);
 1136: 	}
 1137: 	if ( $showbutton ) { 
 1138: 	    if ($target ne 'tex') {
 1139: 		$button = '<input onsubmit="javascript:setSubmittedPart(\''.$id.'\')" type="submit" name="submit_'.$id.'" value="'.&mt('Submit Answer').'" />';
 1140: 	    }
 1141: 	}
 1142: 
 1143:     }
 1144:     my $output= $previousmsg.$latemessage.$message.$trystr;
 1145:     if ($output =~ /^\s*$/) {
 1146: 	return $button;
 1147:     } else {
 1148: 	if ($target eq 'tex') {
 1149: 	    return $button.' \vskip 0 mm '.$output.' ';
 1150: 	} else {
 1151: 	    $output =
 1152: 		'<table><tr><td>'.$button.'</td>'.$output;
 1153: 	    if (!$no_previous) {
 1154: 		$output.='<td>'.&previous_tries($id,$target).'</td>';
 1155: 	    }
 1156: 	    $output.= '</tr></table>';
 1157: 	    return $output;
 1158: 	}
 1159:     }
 1160: }
 1161: 
 1162: sub previous_tries {
 1163:     my ($id,$target) = @_;
 1164:     my $output;
 1165:     my $status = $Apache::inputtags::status['-1'];
 1166: 
 1167:     my $count;
 1168:     my %count_lookup;
 1169: 
 1170:     foreach my $i (1..$Apache::lonhomework::history{'version'}) {
 1171: 	my $prefix = $i.":resource.$id";
 1172: 
 1173: 	next if (!exists($Apache::lonhomework::history{"$prefix.award"}));
 1174: 	$count++;
 1175: 	$count_lookup{$i} = $count;
 1176: 	
 1177: 	my ($previousmsg,$latemessage,$message,$trystr);
 1178: 
 1179: 	($previousmsg,$latemessage,$message,$trystr) =
 1180: 	    &get_grade_messages($id,"$prefix",$target,$status);
 1181: 
 1182: 	if ($previousmsg ne '') {
 1183: 	    my ($match,$which) = &find_which_previous($i);
 1184: 	    $message=$previousmsg;
 1185: 	    my $previous = $count_lookup{$which};
 1186: 	    $message =~ s{(</td>)}{ as submission # $previous $1};
 1187: 	} elsif ($Apache::lonhomework::history{"$prefix.tries"}) {
 1188: 	    if ( $Apache::lonhomework::history{"$prefix.solved"} =~ 
 1189: 		 /^correct/) {
 1190: 		$message =~ s{(<td.*?>)(.*?)(</td>)}
 1191: 		             {$1 <strong>Correct</strong>. $3};
 1192: 	    }
 1193: 	    my $trystr = "(Try ".
 1194: 		$Apache::lonhomework::history{"$prefix.tries"}.')';
 1195: 	    $message =~ s{(</td>)}{ $trystr $1};
 1196: 	}
 1197: 	my ($class) = ($message =~ m{<td.*class="([^"]*)"}); #"
 1198: 	$message =~ s{(<td.*?>)}{<td>};
 1199: 	
 1200: 
 1201: 	$output.='<tr class="'.$class.'">';
 1202: 	$output.='<td align="center">'.$count.'</td>';
 1203: 	$output.=$message;
 1204: 
 1205: 	foreach my $resid (@Apache::inputtags::response) {
 1206: 	    my $prefix = $prefix.".$resid";
 1207: 	    if (exists($Apache::lonhomework::history{"$prefix.submission"})) {
 1208: 		my $submission =
 1209: 		    $Apache::inputtags::submission_display{"$prefix.submission"};
 1210: 		if (!defined($submission)) {
 1211: 		    $submission = 
 1212: 			$Apache::lonhomework::history{"$prefix.submission"};
 1213: 		}
 1214: 		$output.='<td>'.$submission.'</td>';
 1215: 	    } else {
 1216: 		$output.='<td></td>';
 1217: 	    }
 1218: 	}
 1219: 	$output.=&Apache::loncommon::end_data_table_row()."\n";
 1220:     }
 1221:     return if ($output eq '');
 1222:     my $headers = 
 1223: 	'<tr>'.'<th>'.&mt('Submission #').'</th><th>'.&mt('Try').
 1224: 	'</th><th colspan="'.scalar(@Apache::inputtags::response).'">'.
 1225: 	&mt('Submitted Answer').'</th>';
 1226:     $output ='<table class="LC_prior_tries">'.$headers.$output.'</table>';
 1227:     #return $output;
 1228:     $output=~s/\\/\\\\/g;
 1229:     $output=~s/\'/\\\'/g;
 1230:     $output=~s/\s+/ /g;
 1231:     my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
 1232:     my $start_page =
 1233: 	&Apache::loncommon::start_page('Previous Tries', undef,
 1234: 				       {'only_body' => 1,
 1235: 					'bgcolor'   => '#FFFFFF',
 1236: 					'js_ready'  => 1,});
 1237:     my $end_page =
 1238: 	&Apache::loncommon::end_page({'js_ready' => 1,});
 1239:     
 1240:     my $result ="<script type=\"text/javascript\">
 1241: // <![CDATA[
 1242:     function LONCAPA_previous_tries_$Apache::lonxml::curdepth() {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()}
 1243: // ]]>
 1244: </script><a href=\"javascript:LONCAPA_previous_tries_$Apache::lonxml::curdepth();void(0);\">".&mt("Previous Tries")."</a><br />";
 1245:     #use Data::Dumper;
 1246:     #&Apache::lonnet::logthis(&Dumper(\%Apache::inputtags::submission_display));
 1247:     return $result;
 1248: }
 1249: 
 1250: 1;
 1251: __END__
 1252:  

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