File:  [LON-CAPA] / loncom / homework / inputtags.pm
Revision 1.219: download - view: text, annotated - select for diffs
Thu Mar 15 02:52:16 2007 UTC (17 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- implement some of the suggestions from bug#2622 about prior tries display

    1: # The LearningOnline Network with CAPA
    2: # input  definitons
    3: #
    4: # $Id: inputtags.pm,v 1.219 2007/03/15 02:52:16 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 $bgcolor='orange';
  590:     my $added_computer_text=0;
  591:     my %possiblecolors =
  592: 	( 'correct'         => '#aaffaa',
  593: 	  'charged_try'     => '#ffaaaa',
  594: 	  'not_charged_try' => '#ffffaa',
  595: 	  'no_grade'        => '#ffffaa',
  596: 	  'no_message'      => '#ffffff',
  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:         $bgcolor=$possiblecolors{'correct'};
  611: 	$message=&mt('You are correct.');
  612: 	if ($awarded < 1 && $awarded > 0) {
  613: 	    $message=&mt('You are partially correct.');
  614: 	    $bgcolor=$possiblecolors{'not_charged_try'};
  615: 	} elsif ($awarded < 1) {
  616: 	    $message=&mt('Incorrect.');
  617: 	    $bgcolor=$possiblecolors{'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 ((!$env{'course.'.
  633: 			     $env{'request.course.id'}.
  634: 			     '.disable_receipt_display'} eq 'yes')&&
  635: 		    $symb) { 
  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: 	}
  641: 	$button=0;
  642: 	$previousmsg='';
  643:     } elsif ($solved =~ /^excused/) {
  644: 	if ($target eq 'tex') {
  645: 	    $message = ' \textbf{'.&mt('You are excused from the problem.').'} ';
  646: 	} else {
  647: 	    $message = "<b>".&mt('You are excused from the problem.')."</b>";
  648: 	}
  649: 	$bgcolor=$possiblecolors{'charged_try'};
  650: 	$button=0;
  651: 	$previousmsg='';
  652:     } elsif ($award eq 'EXACT_ANS' || $award eq 'APPROX_ANS' ) {
  653: 	if ($solved =~ /^incorrect/ || $solved eq '') {
  654: 	    $message = &mt("Incorrect").".";
  655: 	    $bgcolor=$possiblecolors{'charged_try'};
  656: 	    $button=1;
  657: 	} else {
  658: 	    if ($target eq 'tex') {
  659: 		$message = '\textbf{'.&mt('You are correct.').'}';
  660: 	    } else {
  661: 		$message = "<b>".&mt('You are correct.')."</b>";
  662: 		$message.= $computer;
  663: 	    }
  664: 	    $added_computer_text=1;
  665: 	    unless ($env{'course.'.
  666: 			     $env{'request.course.id'}.
  667: 			     '.disable_receipt_display'} eq 'yes') { 
  668: 		$message.=(($target eq 'web')?'<br />':' ').
  669: 		    'Your receipt is '.&Apache::lonnet::receipt($Apache::inputtags::part).
  670: 		    (($target eq 'web')?&Apache::loncommon::help_open_topic('Receipt'):'');
  671: 	    }
  672: 	    $bgcolor=$possiblecolors{'correct'};
  673: 	    $button=0;
  674: 	    $previousmsg='';
  675: 	}
  676:     } elsif ($award eq 'NO_RESPONSE') {
  677: 	$message = '';
  678: 	$bgcolor=$possiblecolors{'no_feedback'};
  679: 	$button=1;
  680:     } elsif ($award eq 'EXTRA_ANSWER') {
  681: 	$message = &mt('Some extra items were submitted.');
  682: 	$bgcolor=$possiblecolors{'not_charged_try'};
  683: 	$button = 1;
  684:     } elsif ($award eq 'MISSING_ANSWER') {
  685: 	$message = &mt('Some items were not submitted.');
  686: 	$bgcolor=$possiblecolors{'not_charged_try'};
  687: 	$button = 1;
  688:     } elsif ($award eq 'ERROR') {
  689: 	$message = &mt('An error occured while grading your answer.');
  690: 	$bgcolor=$possiblecolors{'not_charged_try'};
  691: 	$button = 1;
  692:     } elsif ($award eq 'TOO_LONG') {
  693: 	$message = &mt("The submitted answer was too long.");
  694: 	$bgcolor=$possiblecolors{'not_charged_try'};
  695: 	$button=1;
  696:     } elsif ($award eq 'WANTED_NUMERIC') {
  697: 	$message = &mt("This question expects a numeric answer.");
  698: 	$bgcolor=$possiblecolors{'not_charged_try'};
  699: 	$button=1;
  700:     } elsif ($award eq 'MISORDERED_RANK') {
  701: 	$message = &mt('You have provided an invalid ranking');
  702: 	if ($target ne 'tex') {
  703: 	    $message.=', '.&mt('please refer to').' '.&Apache::loncommon::help_open_topic('Ranking_Problems','help on ranking problems');
  704: 	}
  705: 	$bgcolor=$possiblecolors{'not_charged_try'};
  706: 	$button=1;
  707:     } elsif ($award eq 'INVALID_FILETYPE') {
  708: 	$message = &mt('Submission won\'t be graded. The type of file submitted is not allowed.');
  709: 	$bgcolor=$possiblecolors{'not_charged_try'};
  710: 	$button=1;
  711:     } elsif ($award eq 'SIG_FAIL') {
  712: 	my ($used,$min,$max)=split(':',$awardmsg);
  713: 	my $word = ($used < $min) ? 'more' : 'fewer';
  714: 	$message = &mt("Submission not graded.  Use $word digits.",$used);
  715: 	$bgcolor=$possiblecolors{'not_charged_try'};
  716: 	$button=1;
  717:     } elsif ($award eq 'UNIT_INVALID_INSTRUCTOR') {
  718: 	$message = &mt('Error in instructor specifed unit. This error has been reported to the instructor.', $awardmsg);
  719: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
  720: 	$bgcolor=$possiblecolors{'not_charged_try'};
  721: 	$button=1;
  722:     } elsif ($award eq 'UNIT_INVALID_STUDENT') {
  723: 	$message = &mt('Unable to interpret units. Computer reads units as "[_1]".',&markup_unit($awardmsg,$target));
  724: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
  725: 	$bgcolor=$possiblecolors{'not_charged_try'};
  726: 	$button=1;
  727:     } elsif ($award eq 'UNIT_FAIL' || $award eq 'UNIT_IRRECONCIBLE') {
  728: 	$message = &mt('Incompatible units. No conversion found between "[_1]" and the required units.',&markup_unit($awardmsg,$target));
  729: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units');} 
  730: 	$bgcolor=$possiblecolors{'not_charged_try'};
  731: 	$button=1;
  732:     } elsif ($award eq 'UNIT_NOTNEEDED') {
  733: 	$message = &mt('Only a number required. Computer reads units of "[_1]".',&markup_unit($awardmsg,$target));
  734: 	$bgcolor=$possiblecolors{'not_charged_try'};
  735: 	$button=1;
  736:     } elsif ($award eq 'NO_UNIT') {
  737: 	$message = &mt("Units required").'.';
  738: 	if ($target ne 'tex') {$message.=&Apache::loncommon::help_open_topic('Physical_Units')};
  739: 	$bgcolor=$possiblecolors{'not_charged_try'};
  740: 	$button=1;
  741:     } elsif ($award eq 'COMMA_FAIL') {
  742: 	$message = &mt("Proper comma separation is required").'.';
  743: 	$bgcolor=$possiblecolors{'not_charged_try'};
  744: 	$button=1;
  745:     } elsif ($award eq 'BAD_FORMULA') {
  746: 	$message = &mt("Unable to understand formula");
  747: 	$bgcolor=$possiblecolors{'not_charged_try'};
  748: 	$button=1;
  749:     } elsif ($award eq 'INCORRECT') {
  750: 	$message = &mt("Incorrect").'.';
  751: 	$bgcolor=$possiblecolors{'charged_try'};
  752: 	$button=1;
  753:     } elsif ($award eq 'SUBMITTED') {
  754: 	$message = &mt("Your submission has been recorded.");
  755: 	$bgcolor=$possiblecolors{'no_grade'};
  756: 	$button=1;
  757:     } elsif ($award eq 'DRAFT') {
  758: 	$message = &mt("A draft copy has been saved.");
  759: 	$bgcolor=$possiblecolors{'not_charged_try'};
  760: 	$button=1;
  761:     } elsif ($award eq 'ASSIGNED_SCORE') {
  762: 	$message = &mt("A score has been assigned.");
  763: 	$bgcolor=$possiblecolors{'correct'};
  764: 	$button=0;
  765:     } elsif ($award eq '') {
  766: 	if ($handgrade && $Apache::inputtags::status[-1] eq 'SHOW_ANSWER') {
  767: 	    $message = &mt("Nothing submitted.");
  768: 	    $bgcolor=$possiblecolors{'charged_try'};
  769: 	} else {
  770: 	    $bgcolor=$possiblecolors{'not_charged_try'};
  771: 	}
  772: 	$button=1;
  773:     } else {
  774: 	$message = &mt("Unknown message").": $award";
  775: 	$button=1;
  776:     }
  777:     my (undef,undef,$domain,$user)=&Apache::lonnet::whichuser();
  778:     foreach my $resid(@Apache::inputtags::response){
  779:         if ($Apache::lonhomework::history{"resource.$part.$resid.handback"}) {
  780: 	    $message.='<br />';
  781: 	    my @files = split(/\s*,\s*/,
  782: 			      $Apache::lonhomework::history{"resource.$part.$resid.handback"});
  783: 	    my $file_msg;
  784: 	    foreach my $file (@files) {
  785: 		$file_msg.= '<br /><a href="/uploaded/'."$domain/$user".'/'.$file.'">'.$file.'</a>';
  786: 	    }
  787: 	    $message .= &mt('Returned file(s): [_1]',$file_msg);
  788: 	}
  789:     }
  790: 
  791:     if (lc($Apache::lonhomework::problemstatus) eq 'no'  && 
  792: 	$Apache::inputtags::status[-1] ne 'SHOW_ANSWER') {
  793: 	$message = &mt("Answer Submitted: Your final submission will be graded after the due date.");
  794: 	$bgcolor=$possiblecolors{'no_grade'};
  795: 	$button=1;
  796:     }
  797:     if ($Apache::inputtags::status[-1] eq 'SHOW_ANSWER' && 
  798: 	!$added_computer_text && $target ne 'tex') {
  799: 	$message.= $computer;
  800: 	$added_computer_text=1;
  801:     }
  802:     return ($button,$bgcolor,$message,$previousmsg);
  803: }
  804: 
  805: sub markup_unit {
  806:     my ($unit,$target)=@_;
  807:     if ($target eq 'tex') {
  808: 	return '\texttt{'.&Apache::lonxml::latex_special_symbols($unit).'}'; 
  809:     } else {
  810: 	return "<tt>".$unit."</tt>";
  811:     }
  812: }
  813: 
  814: sub removealldata {
  815:     my ($id)=@_;
  816:     foreach my $key (keys(%Apache::lonhomework::results)) {
  817: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
  818: 	    &Apache::lonxml::debug("Removing $key");
  819: 	    delete($Apache::lonhomework::results{$key});
  820: 	}
  821:     }
  822: }
  823: 
  824: sub hidealldata {
  825:     my ($id)=@_;
  826:     foreach my $key (keys(%Apache::lonhomework::results)) {
  827: 	if (($key =~ /^resource\.\Q$id\E\./) && ($key !~ /\.collaborators$/)) {
  828: 	    &Apache::lonxml::debug("Hidding $key");
  829: 	    my $newkey=$key;
  830: 	    $newkey=~s/^(resource\.\Q$id\E\.[^\.]+\.)(.*)$/${1}hidden${2}/;
  831: 	    $Apache::lonhomework::results{$newkey}=
  832: 		$Apache::lonhomework::results{$key};
  833: 	    delete($Apache::lonhomework::results{$key});
  834: 	}
  835:     }
  836: }
  837: 
  838: sub setgradedata {
  839:     my ($award,$msg,$id,$previously_used) = @_;
  840:     if ($Apache::lonhomework::scantronmode && 
  841: 	&Apache::lonnet::validCODE($env{'form.CODE'})) {
  842: 	$Apache::lonhomework::results{"resource.CODE"}=$env{'form.CODE'};
  843:     } elsif ($Apache::lonhomework::scantronmode && 
  844: 	     $env{'form.CODE'} eq '' &&
  845: 	     $Apache::lonhomework::history{"resource.CODE"} ne '') {
  846: 	$Apache::lonhomework::results{"resource.CODE"}='';
  847:     }
  848: 
  849:     if (!$Apache::lonhomework::scantronmode &&
  850: 	$Apache::inputtags::status['-1'] ne 'CAN_ANSWER' &&
  851: 	$Apache::inputtags::status['-1'] ne 'CANNOT_ANSWER') {
  852: 	$Apache::lonhomework::results{"resource.$id.afterduedate"}=$award;
  853: 	return '';
  854:     } elsif ( $Apache::lonhomework::history{"resource.$id.solved"} !~
  855: 	      /^correct/ || $Apache::lonhomework::scantronmode ||
  856: 	      lc($Apache::lonhomework::problemstatus) eq 'no') {
  857:         # the student doesn't already have it correct,
  858: 	# or we are in a mode (scantron orno problem status) where a correct 
  859:         # can become incorrect
  860: 	# handle assignment of tries and solved status
  861: 	my $solvemsg;
  862: 	if ($Apache::lonhomework::scantronmode) {
  863: 	    $solvemsg='correct_by_scantron';
  864: 	} else {
  865: 	    $solvemsg='correct_by_student';
  866: 	}
  867: 	if ($Apache::lonhomework::history{"resource.$id.afterduedate"}) {
  868: 	    $Apache::lonhomework::results{"resource.$id.afterduedate"}='';
  869: 	}
  870: 	if ( $award eq 'ASSIGNED_SCORE') {
  871: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
  872: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
  873: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  874: 		$solvemsg;
  875: 	    my $numawards=scalar(@Apache::inputtags::response);
  876: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = 0;
  877: 	    foreach my $res (@Apache::inputtags::response) {
  878: 		$Apache::lonhomework::results{"resource.$id.awarded"}+=
  879: 		    $Apache::lonhomework::results{"resource.$id.$res.awarded"};
  880: 	    }
  881: 	    if ($numawards > 0) {
  882: 		$Apache::lonhomework::results{"resource.$id.awarded"}/=
  883: 		    $numawards;
  884: 	    }
  885: 	} elsif ( $award eq 'APPROX_ANS' || $award eq 'EXACT_ANS' ) {
  886: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
  887: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
  888: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  889: 		$solvemsg;
  890: 	    $Apache::lonhomework::results{"resource.$id.awarded"} = '1';
  891: 	} elsif ( $award eq 'INCORRECT' ) {
  892: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
  893: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
  894: 	    if (lc($Apache::lonhomework::problemstatus) eq 'no' ||
  895: 		$Apache::lonhomework::scantronmode) {
  896: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
  897: 	    }
  898: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  899: 		'incorrect_attempted';
  900: 	} elsif ( $award eq 'SUBMITTED' ) {
  901: 	    $Apache::lonhomework::results{"resource.$id.tries"} =
  902: 		$Apache::lonhomework::history{"resource.$id.tries"} + 1;
  903: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  904: 		'ungraded_attempted';
  905: 	} elsif ( $award eq 'DRAFT' ) {
  906: 	    $Apache::lonhomework::results{"resource.$id.solved"} = '';
  907: 	} elsif ( $award eq 'NO_RESPONSE' ) {
  908: 	    #no real response so delete any data that got stored
  909: 	    &removealldata($id);
  910: 	    return '';
  911: 	} else {
  912: 	    $Apache::lonhomework::results{"resource.$id.solved"} =
  913: 		'incorrect_attempted';
  914: 	    if (lc($Apache::lonhomework::problemstatus) eq 'no' ||
  915: 		$Apache::lonhomework::scantronmode) {
  916: 		$Apache::lonhomework::results{"resource.$id.tries"} =
  917: 		    $Apache::lonhomework::history{"resource.$id.tries"} + 1;
  918: 		$Apache::lonhomework::results{"resource.$id.awarded"} = 0;
  919: 	    }
  920: 	}
  921: 	if (defined($msg)) {
  922: 	    $Apache::lonhomework::results{"resource.$id.awardmsg"} = $msg;
  923: 	}
  924: 	# did either of the overall awards chage? If so ignore the 
  925: 	# previous check
  926: 	if (($Apache::lonhomework::results{"resource.$id.awarded"} eq
  927: 	     $Apache::lonhomework::history{"resource.$id.awarded"}) &&
  928: 	    ($Apache::lonhomework::results{"resource.$id.solved"} eq
  929: 	     $Apache::lonhomework::history{"resource.$id.solved"})) {
  930: 	    # check if this was a previous submission if it was delete the
  931: 	    # unneeded data and update the previously_used attribute
  932: 	    if ( $previously_used eq 'PREVIOUSLY_USED') {
  933: 		if (lc($Apache::lonhomework::problemstatus) ne 'no') {
  934: 		    delete($Apache::lonhomework::results{"resource.$id.tries"});
  935: 		    $Apache::lonhomework::results{"resource.$id.previous"} = '1';
  936: 		}
  937: 	    } elsif ( $previously_used eq 'PREVIOUSLY_LAST') {
  938: 		#delete all data as they student didn't do anything, but save
  939: 		#the list of collaborators.
  940: 		&removealldata($id);
  941: 		#and since they didn't do anything we were never here
  942: 		return '';
  943: 	    } else {
  944: 		$Apache::lonhomework::results{"resource.$id.previous"} = '0';
  945: 	    }
  946: 	}
  947:     } elsif ( $Apache::lonhomework::history{"resource.$id.solved"} =~
  948: 	      /^correct/ ) {
  949: 	#delete all data as they student already has it correct
  950: 	&removealldata($id);
  951: 	#and since they didn't do anything we were never here
  952: 	return '';
  953:     }
  954:     $Apache::lonhomework::results{"resource.$id.award"} = $award;
  955:     if ($award eq 'SUBMITTED') {
  956: 	&Apache::response::add_to_gradingqueue();
  957:     }
  958: }
  959: 
  960: sub find_which_previous {
  961:     my ($version) = @_;
  962:     my $part = $Apache::inputtags::part;
  963:     my (@previous_version);
  964:     foreach my $resp (@Apache::inputtags::response) {
  965: 	my $key = "$version:resource.$part.$resp.submission";
  966: 	my $submission = $Apache::lonhomework::history{$key};
  967: 	my %previous = &Apache::response::check_for_previous($submission,
  968: 							     $part,$resp,
  969: 							     $version);
  970: 	push(@previous_version,$previous{'version'});
  971:     }
  972:     return &previous_match(\@previous_version,
  973: 			   scalar(@Apache::inputtags::response));
  974: }
  975: 
  976: sub previous_match {
  977:     my ($previous_array,$count) = @_;
  978:     my $match = 0;
  979:     my @matches;
  980:     foreach my $versionar (@$previous_array) {
  981: 	foreach my $version (@$versionar) {
  982: 	    $matches[$version]++;
  983: 	}
  984:     }
  985:     my $which=0;
  986:     foreach my $elem (@matches) {
  987: 	if ($elem eq $count) {
  988: 	    $match=1;
  989: 	    last;
  990: 	}
  991: 	$which++;
  992:     }
  993:     return ($match,$which);
  994: }
  995: 
  996: sub grade {
  997:     my ($target) = @_;
  998:     my $id = $Apache::inputtags::part;
  999:     my $response='';
 1000:     if ( defined $env{'form.submitted'}) {
 1001: 	my (@awards,@msgs);
 1002: 	foreach $response (@Apache::inputtags::response) {
 1003: 	    &Apache::lonxml::debug("looking for response.$id.$response.awarddetail");
 1004: 	    my $value=$Apache::lonhomework::results{"resource.$id.$response.awarddetail"};
 1005: 	    &Apache::lonxml::debug("keeping $value from $response for $id");
 1006: 	    push (@awards,$value);
 1007: 	    $value=$Apache::lonhomework::results{"resource.$id.$response.awardmsg"};
 1008: 	    &Apache::lonxml::debug("got message $value from $response for $id");
 1009: 	    push (@msgs,$value);
 1010: 	}
 1011: 	my ($finalaward,$msg) = &finalizeawards(\@awards,\@msgs);
 1012: 	my $previously_used;
 1013: 	if ( $#Apache::inputtags::previous eq $#awards ) {
 1014: 	    my ($match) =
 1015: 		&previous_match(\@Apache::inputtags::previous_version,
 1016: 				scalar(@Apache::inputtags::response));
 1017: 	    
 1018: 	    if ($match) {
 1019: 		$previously_used = 'PREVIOUSLY_LAST';
 1020: 		foreach my $value (@Apache::inputtags::previous) {
 1021: 		    if ($value eq 'PREVIOUSLY_USED' ) {
 1022: 			$previously_used = $value;
 1023: 			last;
 1024: 		    }
 1025: 		}
 1026: 	    }
 1027: 	}
 1028: 	&Apache::lonxml::debug("final award $finalaward, $previously_used, message $msg");
 1029: 	&setgradedata($finalaward,$msg,$id,$previously_used);
 1030:     }
 1031:     return '';
 1032: }
 1033: 
 1034: sub get_grade_messages {
 1035:     my ($id,$prefix,$target,$status) = @_;
 1036: 
 1037:     my ($message,$latemessage,$trystr,$previousmsg);
 1038:     my $showbutton = 1;
 1039: 
 1040:     my $award = $Apache::lonhomework::history{"$prefix.award"};
 1041:     my $awarded = $Apache::lonhomework::history{"$prefix.awarded"};
 1042:     my $solved = $Apache::lonhomework::history{"$prefix.solved"};
 1043:     my $previous = $Apache::lonhomework::history{"$prefix.previous"};
 1044:     my $awardmsg = $Apache::lonhomework::history{"$prefix.awardmsg"};
 1045:     &Apache::lonxml::debug("Found Award |$award|$solved|$awardmsg");
 1046:     if ( $award ne '' || $solved ne '' || $status eq 'SHOW_ANSWER') {
 1047: 	&Apache::lonxml::debug('Getting message');
 1048: 	($showbutton,my $bgcolor,$message,$previousmsg) =
 1049: 	    &decideoutput($award,$awarded,$awardmsg,$solved,$previous,
 1050: 			  $target);
 1051: 	if ($target eq 'tex') {
 1052: 	    $message='\vskip 2 mm '.$message.' ';
 1053: 	} else {
 1054: 	    $message="<td bgcolor=\"$bgcolor\">$message</td>";
 1055: 	    if ($previousmsg) {
 1056: 		$previousmsg="<td bgcolor=\"#aaaaff\">$previousmsg</td>";
 1057: 	    }
 1058: 	}
 1059:     }
 1060:     my $tries = $Apache::lonhomework::history{"$prefix.tries"};
 1061:     my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
 1062:     &Apache::lonxml::debug("got maxtries of :$maxtries:");
 1063:     #if tries are set to negative turn off the Tries/Button and messages
 1064:     if (defined($maxtries) && $maxtries < 0) { return ''; }
 1065:     if ( $tries eq '' ) { $tries = '0'; }
 1066:     if ( $maxtries eq '' ) { $maxtries = '2'; } 
 1067:     if ( $maxtries eq 'con_lost' ) { $maxtries = '0'; } 
 1068:     my $tries_text=&mt('Tries');
 1069:     if ( $Apache::lonhomework::type eq 'survey' ||
 1070: 	 $Apache::lonhomework::parsing_a_task) {
 1071: 	$tries_text=&mt('Submissions');
 1072:     }
 1073: 
 1074:     if ($showbutton) {
 1075: 	if ($target eq 'tex') {
 1076: 	    if ($env{'request.state'} ne "construct"
 1077: 		&& $Apache::lonhomework::type ne 'exam'
 1078: 		&& $env{'form.suppress_tries'} ne 'yes') {
 1079: 		$trystr = ' {\vskip 1 mm \small \textit{'.$tries_text.'} '.
 1080: 		    $tries.'/'.$maxtries.'} \vskip 2 mm ';
 1081: 	    } else {
 1082: 		$trystr = '\vskip 0 mm ';
 1083: 	    }
 1084: 	} else {
 1085: 	    $trystr = "<td><nobr>".$tries_text." $tries";
 1086: 	    if ($Apache::lonhomework::parsing_a_task) {
 1087: 	    } elsif($env{'request.state'} ne 'construct') {
 1088: 		$trystr.="/$maxtries";
 1089: 	    } else {
 1090: 		if (defined($Apache::inputtags::params{'maxtries'})) {
 1091: 		    $trystr.="/".$Apache::inputtags::params{'maxtries'};
 1092: 		}
 1093: 	    }
 1094: 	    $trystr.="</nobr></td>";
 1095: 	}
 1096:     }
 1097:     if ($Apache::lonhomework::history{"$prefix.afterduedate"}) {
 1098: 	#last submissions was after due date
 1099: 	$latemessage=&mt(' The last submission was after the Due Date ');;
 1100: 	if ($target eq 'web') {
 1101: 	    $latemessage='<td bgcolor="#ffaaaa">'.$latemessage.'</td>';
 1102: 	}
 1103:     }
 1104:     return ($previousmsg,$latemessage,$message,$trystr,$showbutton);
 1105: }
 1106: 
 1107: sub gradestatus {
 1108:     my ($id,$target) = @_;
 1109:     my $showbutton = 1;
 1110:     my $message = '';
 1111:     my $latemessage = '';
 1112:     my $trystr='';
 1113:     my $button='';
 1114:     my $previousmsg='';
 1115: 
 1116:     my $status = $Apache::inputtags::status['-1'];
 1117:     &Apache::lonxml::debug("gradestatus has :$status:");
 1118:     if ( $status ne 'CLOSED' 
 1119: 	 && $status ne 'UNAVAILABLE' 
 1120: 	 && $status ne 'INVALID_ACCESS' 
 1121: 	 && $status ne 'NEEDS_CHECKIN' 
 1122: 	 && $status ne 'NOT_IN_A_SLOT') {  
 1123: 
 1124: 	($previousmsg,$latemessage,$message,$trystr) =
 1125: 	    &get_grade_messages($id,"resource.$id",$target,$status,
 1126: 				$showbutton);
 1127: 	if ( $status eq 'SHOW_ANSWER' || $status eq 'CANNOT_ANSWER') {
 1128: 	    $showbutton = 0;
 1129: 	}
 1130: 	if ( $status eq 'SHOW_ANSWER') {
 1131: 	    undef($previousmsg);
 1132: 	}
 1133: 	if ( $showbutton ) { 
 1134: 	    if ($target ne 'tex') {
 1135: 		$button = '<input onsubmit="javascript:setSubmittedPart(\''.$id.'\')" type="submit" name="submit_'.$id.'" value="'.&mt('Submit Answer').'" />';
 1136: 	    }
 1137: 	}
 1138: 
 1139:     }
 1140:     my $output= $previousmsg.$latemessage.$message.$trystr;
 1141:     if ($output =~ /^\s*$/) {
 1142: 	return $button;
 1143:     } else {
 1144: 	if ($target eq 'tex') {
 1145: 	    return $button.' \vskip 0 mm '.$output.' ';
 1146: 	} else {
 1147: 	    return '<table><tr><td>'.$button.'</td>'.$output.'<td>'.&previous_tries($id,$target).'</td></tr></table>';
 1148: 	}
 1149:     }
 1150: }
 1151: 
 1152: sub previous_tries {
 1153:     my ($id,$target) = @_;
 1154:     my $output;
 1155:     my $status = $Apache::inputtags::status['-1'];
 1156: 
 1157:     my $count;
 1158:     my %count_lookup;
 1159: 
 1160:     foreach my $i (1..$Apache::lonhomework::history{'version'}) {
 1161: 	my $prefix = $i.":resource.$id";
 1162: 
 1163: 	next if (!exists($Apache::lonhomework::history{"$prefix.award"}));
 1164: 	$count++;
 1165: 	$count_lookup{$i} = $count;
 1166: 	
 1167: 	my ($previousmsg,$latemessage,$message,$trystr);
 1168: 
 1169: 	($previousmsg,$latemessage,$message,$trystr) =
 1170: 	    &get_grade_messages($id,"$prefix",$target,$status);
 1171: 	if (!exists($Apache::lonhomework::history{"$prefix.tries"})) {
 1172: 	    undef($trystr);
 1173: 	}
 1174: 
 1175: 	if ($previousmsg ne '') {
 1176: 	    my ($match,$which) = &find_which_previous($i);
 1177: 	    $message=$previousmsg;
 1178: 	    my $previous = $count_lookup{$which};
 1179: 	    $message =~ s{(</td>)}{ as submission $previous $1};
 1180: 	    
 1181: 	} elsif ($trystr ne '') { 
 1182: 	    ($trystr) = ($trystr =~ m{(\d+)/\d+});
 1183: 	    $message =~ s{(<td.*?>)}{$1 $trystr };
 1184: 	}
 1185: 
 1186: 
 1187: 	$output.='<tr>';
 1188: 	$output.='<td align ="center">'.$count.'</td>';
 1189: 	$output.=$message;
 1190: 
 1191: 	foreach my $resid (@Apache::inputtags::response) {
 1192: 	    my $prefix = $prefix.".$resid";
 1193: 	    if (exists($Apache::lonhomework::history{"$prefix.submission"})) {
 1194: 		my $submission =
 1195: 		    $Apache::inputtags::submission_display{"$prefix.submission"};
 1196: 		if (!defined($submission)) {
 1197: 		    $submission = 
 1198: 			$Apache::lonhomework::history{"$prefix.submission"};
 1199: 		}
 1200: 		$output.='<td>'.$submission.'</td>';
 1201: 	    } else {
 1202: 		$output.='<td></td>';
 1203: 	    }
 1204: 	}
 1205: 	$output.='</tr>'."\n";
 1206:     }
 1207:     return if ($output eq '');
 1208:     my $headers = 
 1209: 	'<tr>'.'<th>'.&mt('Submission #').'</th><th>'.&mt('Try').
 1210: 	'</th><th colspan="'.scalar(@Apache::inputtags::response).'">'.
 1211: 	&mt('Submitted Answer').'</th>';
 1212:     $output ='<table class="LC_prior_tries">'.$headers.$output.'</table>';
 1213:     $output .='<pre>'.join("\n",@Apache::inputtags::previous_version).'</pre>';
 1214:     #return $output;
 1215:     $output=~s/\\/\\\\/g;
 1216:     $output=~s/\'/\\\'/g;
 1217:     $output=~s/\s+/ /g;
 1218:     my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
 1219:     my $start_page =
 1220: 	&Apache::loncommon::start_page('Previous Tries', undef,
 1221: 				       {'only_body' => 1,
 1222: 					'bgcolor'   => '#FFFFFF',
 1223: 					'js_ready'  => 1,});
 1224:     my $end_page =
 1225: 	&Apache::loncommon::end_page({'js_ready' => 1,});
 1226:     
 1227:     my $result ="<script type=\"text/javascript\">
 1228: // <![CDATA[
 1229:     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()}
 1230: // ]]>
 1231: </script><a href=\"javascript:LONCAPA_previous_tries_$Apache::lonxml::curdepth();void(0);\">".&mt("Previous Tries")."</a><br />";
 1232:     #use Data::Dumper;
 1233:     #&Apache::lonnet::logthis(&Dumper(\%Apache::inputtags::submission_display));
 1234:     return $result;
 1235: }
 1236: 
 1237: 1;
 1238: __END__
 1239:  

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