File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.467: download - view: text, annotated - select for diffs
Fri Oct 26 00:39:09 2007 UTC (16 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- data table the previous submissions

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.467 2007/10/26 00:39:09 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: 
   29: package Apache::grades;
   30: use strict;
   31: use Apache::style;
   32: use Apache::lonxml;
   33: use Apache::lonnet;
   34: use Apache::loncommon;
   35: use Apache::lonhtmlcommon;
   36: use Apache::lonnavmaps;
   37: use Apache::lonhomework;
   38: use Apache::lonpickcode;
   39: use Apache::loncoursedata;
   40: use Apache::lonmsg();
   41: use Apache::Constants qw(:common);
   42: use Apache::lonlocal;
   43: use Apache::lonenc;
   44: use String::Similarity;
   45: use LONCAPA;
   46: 
   47: use POSIX qw(floor);
   48: 
   49: 
   50: my %perm=();
   51: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
   52:                                    # index is "symb.part_id"
   53: 
   54: my %first_bubble_line = ();	# First bubble line no. for each bubble.
   55: 
   56: # Save and restore the bubble lines array to the form env.
   57: 
   58: 
   59: sub save_bubble_lines {
   60:     foreach my $line (keys(%bubble_lines_per_response)) {
   61: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
   62: 	$env{"form.scantron.first_bubble_line.$line"} =
   63: 	    $first_bubble_line{$line};
   64:     }
   65: }
   66: 
   67: 
   68: sub restore_bubble_lines {
   69:     my $line = 0;
   70:     %bubble_lines_per_response = ();
   71:     while ($env{"form.scantron.bubblelines.$line"}) {
   72: 	my $value = $env{"form.scantron.bubblelines.$line"};
   73: 	$bubble_lines_per_response{$line} = $value;
   74: 	$first_bubble_line{$line}  =
   75: 	    $env{"form.scantron.first_bubble_line.$line"};
   76: 	$line++;
   77:     }
   78: 
   79: }
   80: 
   81: #  Given the parsed scanline, get the response for 
   82: #  'answer' number n:
   83: 
   84: sub get_response_bubbles {
   85:     my ($parsed_line, $response)  = @_;
   86: 
   87: 
   88:     my $bubble_line = $first_bubble_line{$response-1} +1;
   89:     my $bubble_lines= $bubble_lines_per_response{$response-1};
   90:     
   91:     my $selected = "";
   92: 
   93:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
   94: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
   95: 	$bubble_line++;
   96:     }
   97:     return $selected;
   98: }
   99: 
  100: 
  101: # ----- These first few routines are general use routines.----
  102: 
  103: # Return the number of occurences of a pattern in a string.
  104: 
  105: sub occurence_count {
  106:     my ($string, $pattern) = @_;
  107: 
  108:     my @matches = ($string =~ /$pattern/g);
  109: 
  110:     return scalar(@matches);
  111: }
  112: 
  113: 
  114: # Take a string known to have digits and convert all the
  115: # digits into letters in the range J,A..I.
  116: 
  117: sub digits_to_letters {
  118:     my ($input) = @_;
  119: 
  120:     my @alphabet = ('J', 'A'..'I');
  121: 
  122:     my @input    = split(//, $input);
  123:     my $output ='';
  124:     for (my $i = 0; $i < scalar(@input); $i++) {
  125: 	if ($input[$i] =~ /\d/) {
  126: 	    $output .= $alphabet[$input[$i]];
  127: 	} else {
  128: 	    $output .= $input[$i];
  129: 	}
  130:     }
  131:     return $output;
  132: }
  133: 
  134: #
  135: # --- Retrieve the parts from the metadata file.---
  136: sub getpartlist {
  137:     my ($symb) = @_;
  138: 
  139:     my $navmap   = Apache::lonnavmaps::navmap->new();
  140:     my $res      = $navmap->getBySymb($symb);
  141:     my $partlist = $res->parts();
  142:     my $url      = $res->src();
  143:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  144: 
  145:     my @stores;
  146:     foreach my $part (@{ $partlist }) {
  147: 	foreach my $key (@metakeys) {
  148: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  149: 	}
  150:     }
  151:     return @stores;
  152: }
  153: 
  154: # --- Get the symbolic name of a problem and the url
  155: sub get_symb {
  156:     my ($request,$silent) = @_;
  157:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  158:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  159:     if ($symb eq '') { 
  160: 	if (!$silent) {
  161: 	    $request->print("Unable to handle ambiguous references:$url:.");
  162: 	    return ();
  163: 	}
  164:     }
  165:     &Apache::lonenc::check_decrypt(\$symb);
  166:     return ($symb);
  167: }
  168: 
  169: #--- Format fullname, username:domain if different for display
  170: #--- Use anywhere where the student names are listed
  171: sub nameUserString {
  172:     my ($type,$fullname,$uname,$udom) = @_;
  173:     if ($type eq 'header') {
  174: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
  175:     } else {
  176: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  177: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  178:     }
  179: }
  180: 
  181: #--- Get the partlist and the response type for a given problem. ---
  182: #--- Indicate if a response type is coded handgraded or not. ---
  183: sub response_type {
  184:     my ($symb) = shift;
  185: 
  186:     my $navmap = Apache::lonnavmaps::navmap->new();
  187:     my $res = $navmap->getBySymb($symb);
  188:     my $partlist = $res->parts();
  189:     my %vPart = 
  190: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  191:     my (%response_types,%handgrade);
  192:     foreach my $part (@{ $partlist }) {
  193: 	next if (%vPart && !exists($vPart{$part}));
  194: 
  195: 	my @types = $res->responseType($part);
  196: 	my @ids = $res->responseIds($part);
  197: 	for (my $i=0; $i < scalar(@ids); $i++) {
  198: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  199: 	    $handgrade{$part.'_'.$ids[$i]} = 
  200: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  201: 				     '.handgrade',$symb);
  202: 	}
  203:     }
  204:     return ($partlist,\%handgrade,\%response_types);
  205: }
  206: 
  207: sub flatten_responseType {
  208:     my ($responseType) = @_;
  209:     my @part_response_id =
  210: 	map { 
  211: 	    my $part = $_;
  212: 	    map {
  213: 		[$part,$_]
  214: 		} sort(keys(%{ $responseType->{$part} }));
  215: 	} sort(keys(%$responseType));
  216:     return @part_response_id;
  217: }
  218: 
  219: sub get_display_part {
  220:     my ($partID,$symb)=@_;
  221:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  222:     if (defined($display) and $display ne '') {
  223: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  224:     } else {
  225: 	$display=$partID;
  226:     }
  227:     return $display;
  228: }
  229: 
  230: #--- Show resource title
  231: #--- and parts and response type
  232: sub showResourceInfo {
  233:     my ($symb,$probTitle,$checkboxes) = @_;
  234:     my $col=3;
  235:     if ($checkboxes) { $col=4; }
  236:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  237:     $result .='<table border="0">';
  238:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  239:     my %resptype = ();
  240:     my $hdgrade='no';
  241:     my %partsseen;
  242:     foreach my $partID (sort keys(%$responseType)) {
  243: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
  244: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  245: 	    my $responsetype = $responseType->{$partID}->{$resID};
  246: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  247: 	    $result.='<tr>';
  248: 	    if ($checkboxes) {
  249: 		if (exists($partsseen{$partID})) {
  250: 		    $result.="<td>&nbsp;</td>";
  251: 		} else {
  252: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  253: 		}
  254: 		$partsseen{$partID}=1;
  255: 	    }
  256: 	    my $display_part=&get_display_part($partID,$symb);
  257: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
  258: 		$resID.'</span></td>'.
  259: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
  260: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
  261: 	}
  262:     }
  263:     $result.='</table>'."\n";
  264:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  265: }
  266: 
  267: sub reset_caches {
  268:     &reset_analyze_cache();
  269:     &reset_perm();
  270: }
  271: 
  272: {
  273:     my %analyze_cache;
  274: 
  275:     sub reset_analyze_cache {
  276: 	undef(%analyze_cache);
  277:     }
  278: 
  279:     sub get_analyze {
  280: 	my ($symb,$uname,$udom)=@_;
  281: 	my $key = "$symb\0$uname\0$udom";
  282: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  283: 
  284: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  285: 	$url=&Apache::lonnet::clutter($url);
  286: 	my $subresult=&Apache::lonnet::ssi($url,
  287: 					   ('grade_target' => 'analyze'),
  288: 					   ('grade_domain' => $udom),
  289: 					   ('grade_symb' => $symb),
  290: 					   ('grade_courseid' => 
  291: 					    $env{'request.course.id'}),
  292: 					   ('grade_username' => $uname));
  293: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  294: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  295: 	return $analyze_cache{$key} = \%analyze;
  296:     }
  297: 
  298:     sub get_order {
  299: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  300: 	my $analyze = &get_analyze($symb,$uname,$udom);
  301: 	return $analyze->{"$partid.$respid.shown"};
  302:     }
  303: 
  304:     sub get_radiobutton_correct_foil {
  305: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  306: 	my $analyze = &get_analyze($symb,$uname,$udom);
  307: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  308: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  309: 		return $foil;
  310: 	    }
  311: 	}
  312:     }
  313: }
  314: 
  315: #--- Clean response type for display
  316: #--- Currently filters option/rank/radiobutton/match/essay/Task
  317: #        response types only.
  318: sub cleanRecord {
  319:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  320: 	$uname,$udom) = @_;
  321:     my $grayFont = '<span class="LC_internal_info">';
  322:     if ($response =~ /^(option|rank)$/) {
  323: 	my %answer=&Apache::lonnet::str2hash($answer);
  324: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  325: 	my ($toprow,$bottomrow);
  326: 	foreach my $foil (@$order) {
  327: 	    if ($grading{$foil} == 1) {
  328: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  329: 	    } else {
  330: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  331: 	    }
  332: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  333: 	}
  334: 	return '<blockquote><table border="1">'.
  335: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  336: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  337: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  338:     } elsif ($response eq 'match') {
  339: 	my %answer=&Apache::lonnet::str2hash($answer);
  340: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  341: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  342: 	my ($toprow,$middlerow,$bottomrow);
  343: 	foreach my $foil (@$order) {
  344: 	    my $item=shift(@items);
  345: 	    if ($grading{$foil} == 1) {
  346: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  347: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  348: 	    } else {
  349: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  350: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  351: 	    }
  352: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  353: 	}
  354: 	return '<blockquote><table border="1">'.
  355: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  356: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  357: 	    $middlerow.'</tr>'.
  358: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  359: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  360:     } elsif ($response eq 'radiobutton') {
  361: 	my %answer=&Apache::lonnet::str2hash($answer);
  362: 	my ($toprow,$bottomrow);
  363: 	my $correct = 
  364: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  365: 	foreach my $foil (@$order) {
  366: 	    if (exists($answer{$foil})) {
  367: 		if ($foil eq $correct) {
  368: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  369: 		} else {
  370: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  371: 		}
  372: 	    } else {
  373: 		$toprow.='<td>'.&mt('false').'</td>';
  374: 	    }
  375: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  376: 	}
  377: 	return '<blockquote><table border="1">'.
  378: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  379: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  380: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  381:     } elsif ($response eq 'essay') {
  382: 	if (! exists ($env{'form.'.$symb})) {
  383: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  384: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  385: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  386: 
  387: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  388: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  389: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  390: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  391: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  392: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  393: 	}
  394: 	$answer =~ s-\n-<br />-g;
  395: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  396:     } elsif ( $response eq 'organic') {
  397: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  398: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  399: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  400: 	return $result;
  401:     } elsif ( $response eq 'Task') {
  402: 	if ( $answer eq 'SUBMITTED') {
  403: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  404: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  405: 	    return $result;
  406: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  407: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  408: 			       keys(%{$record}));
  409: 	    return join('<br />',($version,@matches));
  410: 			       
  411: 			       
  412: 	} else {
  413: 	    my $result =
  414: 		'<p>'
  415: 		.&mt('Overall result: [_1]',
  416: 		     $record->{$version."resource.$respid.$partid.status"})
  417: 		.'</p>';
  418: 	    
  419: 	    $result .= '<ul>';
  420: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  421: 			     keys(%{$record}));
  422: 	    foreach my $grade (sort(@grade)) {
  423: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  424: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  425: 				     $dim, $record->{$grade}).
  426: 			  '</li>';
  427: 	    }
  428: 	    $result.='</ul>';
  429: 	    return $result;
  430: 	}
  431:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  432: 	$answer = 
  433: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  434: 							      $answer);
  435:     }
  436:     return $answer;
  437: }
  438: 
  439: #-- A couple of common js functions
  440: sub commonJSfunctions {
  441:     my $request = shift;
  442:     $request->print(<<COMMONJSFUNCTIONS);
  443: <script type="text/javascript" language="javascript">
  444:     function radioSelection(radioButton) {
  445: 	var selection=null;
  446: 	if (radioButton.length > 1) {
  447: 	    for (var i=0; i<radioButton.length; i++) {
  448: 		if (radioButton[i].checked) {
  449: 		    return radioButton[i].value;
  450: 		}
  451: 	    }
  452: 	} else {
  453: 	    if (radioButton.checked) return radioButton.value;
  454: 	}
  455: 	return selection;
  456:     }
  457: 
  458:     function pullDownSelection(selectOne) {
  459: 	var selection="";
  460: 	if (selectOne.length > 1) {
  461: 	    for (var i=0; i<selectOne.length; i++) {
  462: 		if (selectOne[i].selected) {
  463: 		    return selectOne[i].value;
  464: 		}
  465: 	    }
  466: 	} else {
  467:             // only one value it must be the selected one
  468: 	    return selectOne.value;
  469: 	}
  470:     }
  471: </script>
  472: COMMONJSFUNCTIONS
  473: }
  474: 
  475: #--- Dumps the class list with usernames,list of sections,
  476: #--- section, ids and fullnames for each user.
  477: sub getclasslist {
  478:     my ($getsec,$filterlist,$getgroup) = @_;
  479:     my @getsec;
  480:     my @getgroup;
  481:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  482:     if (!ref($getsec)) {
  483: 	if ($getsec ne '' && $getsec ne 'all') {
  484: 	    @getsec=($getsec);
  485: 	}
  486:     } else {
  487: 	@getsec=@{$getsec};
  488:     }
  489:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  490:     if (!ref($getgroup)) {
  491: 	if ($getgroup ne '' && $getgroup ne 'all') {
  492: 	    @getgroup=($getgroup);
  493: 	}
  494:     } else {
  495: 	@getgroup=@{$getgroup};
  496:     }
  497:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  498: 
  499:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  500:     # Bail out if we were unable to get the classlist
  501:     return if (! defined($classlist));
  502:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  503:     #
  504:     my %sections;
  505:     my %fullnames;
  506:     foreach my $student (keys(%$classlist)) {
  507:         my $end      = 
  508:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  509:         my $start    = 
  510:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  511:         my $id       = 
  512:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  513:         my $section  = 
  514:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  515:         my $fullname = 
  516:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  517:         my $status   = 
  518:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  519:         my $group   = 
  520:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  521: 	# filter students according to status selected
  522: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  523: 	    if (!($stu_status =~ $status)) {
  524: 		delete($classlist->{$student});
  525: 		next;
  526: 	    }
  527: 	}
  528: 	# filter students according to groups selected
  529: 	my @stu_groups = split(/,/,$group);
  530: 	if (@getgroup) {
  531: 	    my $exclude = 1;
  532: 	    foreach my $grp (@getgroup) {
  533: 	        foreach my $stu_group (@stu_groups) {
  534: 	            if ($stu_group eq $grp) {
  535: 	                $exclude = 0;
  536:     	            } 
  537: 	        }
  538:     	        if (($grp eq 'none') && !$group) {
  539:         	        $exclude = 0;
  540:         	}
  541: 	    }
  542: 	    if ($exclude) {
  543: 	        delete($classlist->{$student});
  544: 	    }
  545: 	}
  546: 	$section = ($section ne '' ? $section : 'none');
  547: 	if (&canview($section)) {
  548: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  549: 		$sections{$section}++;
  550: 		if ($classlist->{$student}) {
  551: 		    $fullnames{$student}=$fullname;
  552: 		}
  553: 	    } else {
  554: 		delete($classlist->{$student});
  555: 	    }
  556: 	} else {
  557: 	    delete($classlist->{$student});
  558: 	}
  559:     }
  560:     my %seen = ();
  561:     my @sections = sort(keys(%sections));
  562:     return ($classlist,\@sections,\%fullnames);
  563: }
  564: 
  565: sub canmodify {
  566:     my ($sec)=@_;
  567:     if ($perm{'mgr'}) {
  568: 	if (!defined($perm{'mgr_section'})) {
  569: 	    # can modify whole class
  570: 	    return 1;
  571: 	} else {
  572: 	    if ($sec eq $perm{'mgr_section'}) {
  573: 		#can modify the requested section
  574: 		return 1;
  575: 	    } else {
  576: 		# can't modify the request section
  577: 		return 0;
  578: 	    }
  579: 	}
  580:     }
  581:     #can't modify
  582:     return 0;
  583: }
  584: 
  585: sub canview {
  586:     my ($sec)=@_;
  587:     if ($perm{'vgr'}) {
  588: 	if (!defined($perm{'vgr_section'})) {
  589: 	    # can modify whole class
  590: 	    return 1;
  591: 	} else {
  592: 	    if ($sec eq $perm{'vgr_section'}) {
  593: 		#can modify the requested section
  594: 		return 1;
  595: 	    } else {
  596: 		# can't modify the request section
  597: 		return 0;
  598: 	    }
  599: 	}
  600:     }
  601:     #can't modify
  602:     return 0;
  603: }
  604: 
  605: #--- Retrieve the grade status of a student for all the parts
  606: sub student_gradeStatus {
  607:     my ($symb,$udom,$uname,$partlist) = @_;
  608:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  609:     my %partstatus = ();
  610:     foreach (@$partlist) {
  611: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  612: 	$status              = 'nothing' if ($status eq '');
  613: 	$partstatus{$_}      = $status;
  614: 	my $subkey           = "resource.$_.submitted_by";
  615: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  616:     }
  617:     return %partstatus;
  618: }
  619: 
  620: # hidden form and javascript that calls the form
  621: # Use by verifyscript and viewgrades
  622: # Shows a student's view of problem and submission
  623: sub jscriptNform {
  624:     my ($symb) = @_;
  625:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  626:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  627: 	'    function viewOneStudent(user,domain) {'."\n".
  628: 	'	document.onestudent.student.value = user;'."\n".
  629: 	'	document.onestudent.userdom.value = domain;'."\n".
  630: 	'	document.onestudent.submit();'."\n".
  631: 	'    }'."\n".
  632: 	'</script>'."\n";
  633:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  634: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  635: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  636: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  637: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  638: 	'<input type="hidden" name="command" value="submission" />'."\n".
  639: 	'<input type="hidden" name="student" value="" />'."\n".
  640: 	'<input type="hidden" name="userdom" value="" />'."\n".
  641: 	'</form>'."\n";
  642:     return $jscript;
  643: }
  644: 
  645: 
  646: 
  647: # Given the score (as a number [0-1] and the weight) what is the final
  648: # point value? This function will round to the nearest tenth, third,
  649: # or quarter if one of those is within the tolerance of .00001.
  650: sub compute_points {
  651:     my ($score, $weight) = @_;
  652:     
  653:     my $tolerance = .00001;
  654:     my $points = $score * $weight;
  655: 
  656:     # Check for nearness to 1/x.
  657:     my $check_for_nearness = sub {
  658:         my ($factor) = @_;
  659:         my $num = ($points * $factor) + $tolerance;
  660:         my $floored_num = floor($num);
  661:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  662:             return $floored_num / $factor;
  663:         }
  664:         return $points;
  665:     };
  666: 
  667:     $points = $check_for_nearness->(10);
  668:     $points = $check_for_nearness->(3);
  669:     $points = $check_for_nearness->(4);
  670:     
  671:     return $points;
  672: }
  673: 
  674: #------------------ End of general use routines --------------------
  675: 
  676: #
  677: # Find most similar essay
  678: #
  679: 
  680: sub most_similar {
  681:     my ($uname,$udom,$uessay,$old_essays)=@_;
  682: 
  683: # ignore spaces and punctuation
  684: 
  685:     $uessay=~s/\W+/ /gs;
  686: 
  687: # ignore empty submissions (occuring when only files are sent)
  688: 
  689:     unless ($uessay=~/\w+/) { return ''; }
  690: 
  691: # these will be returned. Do not care if not at least 50 percent similar
  692:     my $limit=0.6;
  693:     my $sname='';
  694:     my $sdom='';
  695:     my $scrsid='';
  696:     my $sessay='';
  697: # go through all essays ...
  698:     foreach my $tkey (keys(%$old_essays)) {
  699: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  700: # ... except the same student
  701:         next if (($tname eq $uname) && ($tdom eq $udom));
  702: 	my $tessay=$old_essays->{$tkey};
  703: 	$tessay=~s/\W+/ /gs;
  704: # String similarity gives up if not even limit
  705: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  706: # Found one
  707: 	if ($tsimilar>$limit) {
  708: 	    $limit=$tsimilar;
  709: 	    $sname=$tname;
  710: 	    $sdom=$tdom;
  711: 	    $scrsid=$tcrsid;
  712: 	    $sessay=$old_essays->{$tkey};
  713: 	}
  714:     }
  715:     if ($limit>0.6) {
  716:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  717:     } else {
  718:        return ('','','','',0);
  719:     }
  720: }
  721: 
  722: #-------------------------------------------------------------------
  723: 
  724: #------------------------------------ Receipt Verification Routines
  725: #
  726: #--- Check whether a receipt number is valid.---
  727: sub verifyreceipt {
  728:     my $request  = shift;
  729: 
  730:     my $courseid = $env{'request.course.id'};
  731:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  732: 	$env{'form.receipt'};
  733:     $receipt     =~ s/[^\-\d]//g;
  734:     my ($symb)   = &get_symb($request);
  735: 
  736:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
  737: 	$receipt.'</h3></span>'."\n".
  738: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
  739: 
  740:     my ($string,$contents,$matches) = ('','',0);
  741:     my (undef,undef,$fullname) = &getclasslist('all','0');
  742:     
  743:     my $receiptparts=0;
  744:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  745: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  746:     my $parts=['0'];
  747:     if ($receiptparts) { ($parts)=&response_type($symb); }
  748:     foreach (sort 
  749: 	     {
  750: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  751: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  752: 		 }
  753: 		 return $a cmp $b;
  754: 	     } (keys(%$fullname))) {
  755: 	my ($uname,$udom)=split(/\:/);
  756: 	foreach my $part (@$parts) {
  757: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  758: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
  759: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  760: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  761: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  762: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  763: 		if ($receiptparts) {
  764: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  765: 		}
  766: 		$contents.='</tr>'."\n";
  767: 		
  768: 		$matches++;
  769: 	    }
  770: 	}
  771:     }
  772:     if ($matches == 0) {
  773: 	$string = $title.'No match found for the above receipt.';
  774:     } else {
  775: 	$string = &jscriptNform($symb).$title.
  776: 	    'The above receipt matches the following student'.
  777: 	    ($matches <= 1 ? '.' : 's.')."\n".
  778: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
  779: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
  780: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
  781: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
  782: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
  783: 	if ($receiptparts) {
  784: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
  785: 	}
  786: 	$string.='</tr>'."\n".$contents.
  787: 	    '</table></td></tr></table>'."\n";
  788:     }
  789:     return $string.&show_grading_menu_form($symb);
  790: }
  791: 
  792: #--- This is called by a number of programs.
  793: #--- Called from the Grading Menu - View/Grade an individual student
  794: #--- Also called directly when one clicks on the subm button 
  795: #    on the problem page.
  796: sub listStudents {
  797:     my ($request) = shift;
  798: 
  799:     my ($symb) = &get_symb($request);
  800:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  801:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  802:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  803:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  804:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  805:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  806:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  807: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  808: 
  809:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
  810: 	' Submissions for a Student or a Group of Students</span></h3>';
  811: 
  812:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  813: 
  814:     $request->print(<<LISTJAVASCRIPT);
  815: <script type="text/javascript" language="javascript">
  816:     function checkSelect(checkBox) {
  817: 	var ctr=0;
  818: 	var sense="";
  819: 	if (checkBox.length > 1) {
  820: 	    for (var i=0; i<checkBox.length; i++) {
  821: 		if (checkBox[i].checked) {
  822: 		    ctr++;
  823: 		}
  824: 	    }
  825: 	    sense = "a student or group of students";
  826: 	} else {
  827: 	    if (checkBox.checked) {
  828: 		ctr = 1;
  829: 	    }
  830: 	    sense = "the student";
  831: 	}
  832: 	if (ctr == 0) {
  833: 	    alert("Please select "+sense+" before clicking on the Next button.");
  834: 	    return false;
  835: 	}
  836: 	document.gradesub.submit();
  837:     }
  838: 
  839:     function reLoadList(formname) {
  840: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  841: 	formname.command.value = 'submission';
  842: 	formname.submit();
  843:     }
  844: </script>
  845: LISTJAVASCRIPT
  846: 
  847:     &commonJSfunctions($request);
  848:     $request->print($result);
  849: 
  850:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  851:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  852:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  853: 	"\n".$table.
  854: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
  855: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
  856: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
  857: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
  858: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
  859: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
  860: 	'&nbsp;<b>Submissions: </b>'."\n";
  861:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  862: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
  863:     }
  864:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  865:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  866:     $env{'form.Status'} = $saveStatus;
  867:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
  868: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
  869: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
  870: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
  871:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
  872:         '<option value="1">Whole Points</option>'.
  873:         '<option value=".5">Half Points</option>'.
  874:         '<option value=".25">Quarter Points</option>'.
  875:         '<option value=".1">Tenths of a Point</option>'.
  876:         '</select>'.
  877:         &build_section_inputs().
  878: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  879: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  880: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  881: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  882: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  883: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  884: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  885: 
  886:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  887: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  888:     } else {
  889: 	$gradeTable.='<b>Student Status:</b> '.
  890: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
  891:     }
  892: 
  893:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
  894: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
  895: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  896: 
  897: # checkall buttons
  898:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  899:     $gradeTable.='<input type="button" '."\n".
  900: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  901: 	'value="Next->" /> <br />'."\n";
  902:     $gradeTable.=&check_buttons();
  903:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
  904:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  905:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
  906: 	'<table border="0"><tr bgcolor="#e6ffff">';
  907:     my $loop = 0;
  908:     while ($loop < 2) {
  909: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
  910: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
  911: 	if ($env{'form.showgrading'} eq 'yes' 
  912: 	    && $submitonly ne 'queued'
  913: 	    && $submitonly ne 'all') {
  914: 	    foreach (sort(@$partlist)) {
  915: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
  916: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
  917: 		    ' Status&nbsp;</b></td>';
  918: 	    }
  919: 	} elsif ($submitonly eq 'queued') {
  920: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
  921: 	}
  922: 	$loop++;
  923: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  924:     }
  925:     $gradeTable.='</tr>'."\n";
  926: 
  927:     my $ctr = 0;
  928:     foreach my $student (sort 
  929: 			 {
  930: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  931: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  932: 			     }
  933: 			     return $a cmp $b;
  934: 			 }
  935: 			 (keys(%$fullname))) {
  936: 	my ($uname,$udom) = split(/:/,$student);
  937: 
  938: 	my %status = ();
  939: 
  940: 	if ($submitonly eq 'queued') {
  941: 	    my %queue_status = 
  942: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  943: 							$udom,$uname);
  944: 	    next if (!defined($queue_status{'gradingqueue'}));
  945: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  946: 	}
  947: 
  948: 	if ($env{'form.showgrading'} eq 'yes' 
  949: 	    && $submitonly ne 'queued'
  950: 	    && $submitonly ne 'all') {
  951: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  952: 	    my $submitted = 0;
  953: 	    my $graded = 0;
  954: 	    my $incorrect = 0;
  955: 	    foreach (keys(%status)) {
  956: 		$submitted = 1 if ($status{$_} ne 'nothing');
  957: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  958: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  959: 		
  960: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  961: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  962: 		    $submitted = 0;
  963: 		    my ($part)=split(/\./,$partid);
  964: 		    $gradeTable.='<input type="hidden" name="'.
  965: 			$student.':'.$part.':submitted_by" value="'.
  966: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
  967: 		}
  968: 	    }
  969: 	    
  970: 	    next if (!$submitted && ($submitonly eq 'yes' ||
  971: 				     $submitonly eq 'incorrect' ||
  972: 				     $submitonly eq 'graded'));
  973: 	    next if (!$graded && ($submitonly eq 'graded'));
  974: 	    next if (!$incorrect && $submitonly eq 'incorrect');
  975: 	}
  976: 
  977: 	$ctr++;
  978: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  979:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  980: 	if ( $perm{'vgr'} eq 'F' ) {
  981: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
  982: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
  983:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
  984:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
  985: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
  986: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
  987: 	       '&nbsp;'.$section.'/'.$group.'</td>'."\n";
  988: 
  989: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
  990: 		foreach (sort keys(%status)) {
  991: 		    next if (/^resource.*?submitted_by$/);
  992: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
  993: 		}
  994: 	    }
  995: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
  996: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
  997: 	}
  998:     }
  999:     if ($ctr%2 ==1) {
 1000: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1001: 	    if ($env{'form.showgrading'} eq 'yes' 
 1002: 		&& $submitonly ne 'queued'
 1003: 		&& $submitonly ne 'all') {
 1004: 		foreach (@$partlist) {
 1005: 		    $gradeTable.='<td>&nbsp;</td>';
 1006: 		}
 1007: 	    } elsif ($submitonly eq 'queued') {
 1008: 		$gradeTable.='<td>&nbsp;</td>';
 1009: 	    }
 1010: 	$gradeTable.='</tr>';
 1011:     }
 1012: 
 1013:     $gradeTable.='</table></td></tr></table>'."\n".
 1014: 	'<input type="button" '.
 1015: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1016: 	'value="Next->" /></form>'."\n";
 1017:     if ($ctr == 0) {
 1018: 	my $num_students=(scalar(keys(%$fullname)));
 1019: 	if ($num_students eq 0) {
 1020: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
 1021: 	} else {
 1022: 	    my $submissions='submissions';
 1023: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1024: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1025: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1026: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1027: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
 1028: 		' students checked for '.$submissions.')</span><br />';
 1029: 	}
 1030:     } elsif ($ctr == 1) {
 1031: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
 1032:     }
 1033:     $gradeTable.=&show_grading_menu_form($symb);
 1034:     $request->print($gradeTable);
 1035:     return '';
 1036: }
 1037: 
 1038: #---- Called from the listStudents routine
 1039: 
 1040: sub check_script {
 1041:     my ($form, $type)=@_;
 1042:     my $chkallscript='<script type="text/javascript">
 1043:     function checkall() {
 1044:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1045:             ele = document.forms.'.$form.'.elements[i];
 1046:             if (ele.name == "'.$type.'") {
 1047:             document.forms.'.$form.'.elements[i].checked=true;
 1048:                                        }
 1049:         }
 1050:     }
 1051: 
 1052:     function checksec() {
 1053:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1054:             ele = document.forms.'.$form.'.elements[i];
 1055:            string = document.forms.'.$form.'.chksec.value;
 1056:            if
 1057:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1058:               document.forms.'.$form.'.elements[i].checked=true;
 1059:             }
 1060:         }
 1061:     }
 1062: 
 1063: 
 1064:     function uncheckall() {
 1065:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1066:             ele = document.forms.'.$form.'.elements[i];
 1067:             if (ele.name == "'.$type.'") {
 1068:             document.forms.'.$form.'.elements[i].checked=false;
 1069:                                        }
 1070:         }
 1071:     }
 1072: 
 1073: </script>'."\n";
 1074:     return $chkallscript;
 1075: }
 1076: 
 1077: sub check_buttons {
 1078:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
 1079:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
 1080:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
 1081:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1082:     return $buttons;
 1083: }
 1084: 
 1085: #     Displays the submissions for one student or a group of students
 1086: sub processGroup {
 1087:     my ($request)  = shift;
 1088:     my $ctr        = 0;
 1089:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1090:     my $total      = scalar(@stuchecked)-1;
 1091: 
 1092:     foreach my $student (@stuchecked) {
 1093: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1094: 	$env{'form.student'}        = $uname;
 1095: 	$env{'form.userdom'}        = $udom;
 1096: 	$env{'form.fullname'}       = $fullname;
 1097: 	&submission($request,$ctr,$total);
 1098: 	$ctr++;
 1099:     }
 1100:     return '';
 1101: }
 1102: 
 1103: #------------------------------------------------------------------------------------
 1104: #
 1105: #-------------------------- Next few routines handles grading by student, essentially
 1106: #                           handles essay response type problem/part
 1107: #
 1108: #--- Javascript to handle the submission page functionality ---
 1109: sub sub_page_js {
 1110:     my $request = shift;
 1111:     $request->print(<<SUBJAVASCRIPT);
 1112: <script type="text/javascript" language="javascript">
 1113:     function updateRadio(formname,id,weight) {
 1114: 	var gradeBox = formname["GD_BOX"+id];
 1115: 	var radioButton = formname["RADVAL"+id];
 1116: 	var oldpts = formname["oldpts"+id].value;
 1117: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1118: 	gradeBox.value = pts;
 1119: 	var resetbox = false;
 1120: 	if (isNaN(pts) || pts < 0) {
 1121: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1122: 	    for (var i=0; i<radioButton.length; i++) {
 1123: 		if (radioButton[i].checked) {
 1124: 		    gradeBox.value = i;
 1125: 		    resetbox = true;
 1126: 		}
 1127: 	    }
 1128: 	    if (!resetbox) {
 1129: 		formtextbox.value = "";
 1130: 	    }
 1131: 	    return;
 1132: 	}
 1133: 
 1134: 	if (pts > weight) {
 1135: 	    var resp = confirm("You entered a value ("+pts+
 1136: 			       ") greater than the weight for the part. Accept?");
 1137: 	    if (resp == false) {
 1138: 		gradeBox.value = oldpts;
 1139: 		return;
 1140: 	    }
 1141: 	}
 1142: 
 1143: 	for (var i=0; i<radioButton.length; i++) {
 1144: 	    radioButton[i].checked=false;
 1145: 	    if (pts == i && pts != "") {
 1146: 		radioButton[i].checked=true;
 1147: 	    }
 1148: 	}
 1149: 	updateSelect(formname,id);
 1150: 	formname["stores"+id].value = "0";
 1151:     }
 1152: 
 1153:     function writeBox(formname,id,pts) {
 1154: 	var gradeBox = formname["GD_BOX"+id];
 1155: 	if (checkSolved(formname,id) == 'update') {
 1156: 	    gradeBox.value = pts;
 1157: 	} else {
 1158: 	    var oldpts = formname["oldpts"+id].value;
 1159: 	    gradeBox.value = oldpts;
 1160: 	    var radioButton = formname["RADVAL"+id];
 1161: 	    for (var i=0; i<radioButton.length; i++) {
 1162: 		radioButton[i].checked=false;
 1163: 		if (i == oldpts) {
 1164: 		    radioButton[i].checked=true;
 1165: 		}
 1166: 	    }
 1167: 	}
 1168: 	formname["stores"+id].value = "0";
 1169: 	updateSelect(formname,id);
 1170: 	return;
 1171:     }
 1172: 
 1173:     function clearRadBox(formname,id) {
 1174: 	if (checkSolved(formname,id) == 'noupdate') {
 1175: 	    updateSelect(formname,id);
 1176: 	    return;
 1177: 	}
 1178: 	gradeSelect = formname["GD_SEL"+id];
 1179: 	for (var i=0; i<gradeSelect.length; i++) {
 1180: 	    if (gradeSelect[i].selected) {
 1181: 		var selectx=i;
 1182: 	    }
 1183: 	}
 1184: 	var stores = formname["stores"+id];
 1185: 	if (selectx == stores.value) { return };
 1186: 	var gradeBox = formname["GD_BOX"+id];
 1187: 	gradeBox.value = "";
 1188: 	var radioButton = formname["RADVAL"+id];
 1189: 	for (var i=0; i<radioButton.length; i++) {
 1190: 	    radioButton[i].checked=false;
 1191: 	}
 1192: 	stores.value = selectx;
 1193:     }
 1194: 
 1195:     function checkSolved(formname,id) {
 1196: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1197: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1198: 	    if (!reply) {return "noupdate";}
 1199: 	    formname.overRideScore.value = 'yes';
 1200: 	}
 1201: 	return "update";
 1202:     }
 1203: 
 1204:     function updateSelect(formname,id) {
 1205: 	formname["GD_SEL"+id][0].selected = true;
 1206: 	return;
 1207:     }
 1208: 
 1209: //=========== Check that a point is assigned for all the parts  ============
 1210:     function checksubmit(formname,val,total,parttot) {
 1211: 	formname.gradeOpt.value = val;
 1212: 	if (val == "Save & Next") {
 1213: 	    for (i=0;i<=total;i++) {
 1214: 		for (j=0;j<parttot;j++) {
 1215: 		    var partid = formname["partid"+i+"_"+j].value;
 1216: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1217: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1218: 			if (points == "") {
 1219: 			    var name = formname["name"+i].value;
 1220: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1221: 			    var resp = confirm("You did not assign a score for "+studentID+
 1222: 					       ", part "+partid+". Continue?");
 1223: 			    if (resp == false) {
 1224: 				formname["GD_BOX"+i+"_"+partid].focus();
 1225: 				return false;
 1226: 			    }
 1227: 			}
 1228: 		    }
 1229: 		    
 1230: 		}
 1231: 	    }
 1232: 	    
 1233: 	}
 1234: 	if (val == "Grade Student") {
 1235: 	    formname.showgrading.value = "yes";
 1236: 	    if (formname.Status.value == "") {
 1237: 		formname.Status.value = "Active";
 1238: 	    }
 1239: 	    formname.studentNo.value = total;
 1240: 	}
 1241: 	formname.submit();
 1242:     }
 1243: 
 1244: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1245:     function checkSubmitPage(formname,total) {
 1246: 	noscore = new Array(100);
 1247: 	var ptr = 0;
 1248: 	for (i=1;i<total;i++) {
 1249: 	    var partid = formname["q_"+i].value;
 1250: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1251: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1252: 		var status = formname["solved"+i+"_"+partid].value;
 1253: 		if (points == "" && status != "correct_by_student") {
 1254: 		    noscore[ptr] = i;
 1255: 		    ptr++;
 1256: 		}
 1257: 	    }
 1258: 	}
 1259: 	if (ptr != 0) {
 1260: 	    var sense = ptr == 1 ? ": " : "s: ";
 1261: 	    var prolist = "";
 1262: 	    if (ptr == 1) {
 1263: 		prolist = noscore[0];
 1264: 	    } else {
 1265: 		var i = 0;
 1266: 		while (i < ptr-1) {
 1267: 		    prolist += noscore[i]+", ";
 1268: 		    i++;
 1269: 		}
 1270: 		prolist += "and "+noscore[i];
 1271: 	    }
 1272: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1273: 	    if (resp == false) {
 1274: 		return false;
 1275: 	    }
 1276: 	}
 1277: 
 1278: 	formname.submit();
 1279:     }
 1280: </script>
 1281: SUBJAVASCRIPT
 1282: }
 1283: 
 1284: #--- javascript for essay type problem --
 1285: sub sub_page_kw_js {
 1286:     my $request = shift;
 1287:     my $iconpath = $request->dir_config('lonIconsURL');
 1288:     &commonJSfunctions($request);
 1289: 
 1290:     my $inner_js_msg_central=<<INNERJS;
 1291:     <script text="text/javascript">
 1292:     function checkInput() {
 1293:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1294:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1295:       var usrctr = document.msgcenter.usrctr.value;
 1296:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1297:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1298: 
 1299:       var msgchk = "";
 1300:       if (document.msgcenter.subchk.checked) {
 1301:          msgchk = "msgsub,";
 1302:       }
 1303:       var includemsg = 0;
 1304:       for (var i=1; i<=nmsg; i++) {
 1305:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1306:           var frmmsg = document.msgcenter["msg"+i];
 1307:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1308:           var showflg = opener.document.SCORE["shownOnce"+i];
 1309:           showflg.value = "1";
 1310:           var chkbox = document.msgcenter["msgn"+i];
 1311:           if (chkbox.checked) {
 1312:              msgchk += "savemsg"+i+",";
 1313:              includemsg = 1;
 1314:           }
 1315:       }
 1316:       if (document.msgcenter.newmsgchk.checked) {
 1317:          msgchk += "newmsg"+usrctr;
 1318:          includemsg = 1;
 1319:       }
 1320:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1321:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1322:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1323:       includemsg.value = msgchk;
 1324: 
 1325:       self.close()
 1326: 
 1327:     }
 1328:     </script>
 1329: INNERJS
 1330: 
 1331:     my $inner_js_highlight_central=<<INNERJS;
 1332:  <script type="text/javascript">
 1333:     function updateChoice(flag) {
 1334:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1335:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1336:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1337:       opener.document.SCORE.refresh.value = "on";
 1338:       if (opener.document.SCORE.keywords.value!=""){
 1339:          opener.document.SCORE.submit();
 1340:       }
 1341:       self.close()
 1342:     }
 1343: </script>
 1344: INNERJS
 1345: 
 1346:     my $start_page_msg_central = 
 1347:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1348: 				       {'js_ready'  => 1,
 1349: 					'only_body' => 1,
 1350: 					'bgcolor'   =>'#FFFFFF',});
 1351:     my $end_page_msg_central = 
 1352: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1353: 
 1354: 
 1355:     my $start_page_highlight_central = 
 1356:         &Apache::loncommon::start_page('Highlight Central',
 1357: 				       $inner_js_highlight_central,
 1358: 				       {'js_ready'  => 1,
 1359: 					'only_body' => 1,
 1360: 					'bgcolor'   =>'#FFFFFF',});
 1361:     my $end_page_highlight_central = 
 1362: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1363: 
 1364:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1365:     $docopen=~s/^document\.//;
 1366:     $request->print(<<SUBJAVASCRIPT);
 1367: <script type="text/javascript" language="javascript">
 1368: 
 1369: //===================== Show list of keywords ====================
 1370:   function keywords(formname) {
 1371:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1372:     if (nret==null) return;
 1373:     formname.keywords.value = nret;
 1374: 
 1375:     if (formname.keywords.value != "") {
 1376: 	formname.refresh.value = "on";
 1377: 	formname.submit();
 1378:     }
 1379:     return;
 1380:   }
 1381: 
 1382: //===================== Script to view submitted by ==================
 1383:   function viewSubmitter(submitter) {
 1384:     document.SCORE.refresh.value = "on";
 1385:     document.SCORE.NCT.value = "1";
 1386:     document.SCORE.unamedom0.value = submitter;
 1387:     document.SCORE.submit();
 1388:     return;
 1389:   }
 1390: 
 1391: //===================== Script to add keyword(s) ==================
 1392:   function getSel() {
 1393:     if (document.getSelection) txt = document.getSelection();
 1394:     else if (document.selection) txt = document.selection.createRange().text;
 1395:     else return;
 1396:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1397:     if (cleantxt=="") {
 1398: 	alert("Please select a word or group of words from document and then click this link.");
 1399: 	return;
 1400:     }
 1401:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1402:     if (nret==null) return;
 1403:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1404:     if (document.SCORE.keywords.value != "") {
 1405: 	document.SCORE.refresh.value = "on";
 1406: 	document.SCORE.submit();
 1407:     }
 1408:     return;
 1409:   }
 1410: 
 1411: //====================== Script for composing message ==============
 1412:    // preload images
 1413:    img1 = new Image();
 1414:    img1.src = "$iconpath/mailbkgrd.gif";
 1415:    img2 = new Image();
 1416:    img2.src = "$iconpath/mailto.gif";
 1417: 
 1418:   function msgCenter(msgform,usrctr,fullname) {
 1419:     var Nmsg  = msgform.savemsgN.value;
 1420:     savedMsgHeader(Nmsg,usrctr,fullname);
 1421:     var subject = msgform.msgsub.value;
 1422:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1423:     re = /msgsub/;
 1424:     var shwsel = "";
 1425:     if (re.test(msgchk)) { shwsel = "checked" }
 1426:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1427:     displaySubject(checkEntities(subject),shwsel);
 1428:     for (var i=1; i<=Nmsg; i++) {
 1429: 	var testmsg = "savemsg"+i+",";
 1430: 	re = new RegExp(testmsg,"g");
 1431: 	shwsel = "";
 1432: 	if (re.test(msgchk)) { shwsel = "checked" }
 1433: 	var message = document.SCORE["savemsg"+i].value;
 1434: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1435: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1436: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1437:     }
 1438:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1439:     shwsel = "";
 1440:     re = /newmsg/;
 1441:     if (re.test(msgchk)) { shwsel = "checked" }
 1442:     newMsg(newmsg,shwsel);
 1443:     msgTail(); 
 1444:     return;
 1445:   }
 1446: 
 1447:   function checkEntities(strx) {
 1448:     if (strx.length == 0) return strx;
 1449:     var orgStr = ["&", "<", ">", '"']; 
 1450:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1451:     var counter = 0;
 1452:     while (counter < 4) {
 1453: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1454: 	counter++;
 1455:     }
 1456:     return strx;
 1457:   }
 1458: 
 1459:   function strReplace(strx, orgStr, newStr) {
 1460:     return strx.split(orgStr).join(newStr);
 1461:   }
 1462: 
 1463:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1464:     var height = 70*Nmsg+250;
 1465:     var scrollbar = "no";
 1466:     if (height > 600) {
 1467: 	height = 600;
 1468: 	scrollbar = "yes";
 1469:     }
 1470:     var xpos = (screen.width-600)/2;
 1471:     xpos = (xpos < 0) ? '0' : xpos;
 1472:     var ypos = (screen.height-height)/2-30;
 1473:     ypos = (ypos < 0) ? '0' : ypos;
 1474: 
 1475:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1476:     pWin.focus();
 1477:     pDoc = pWin.document;
 1478:     pDoc.$docopen;
 1479:     pDoc.write('$start_page_msg_central');
 1480: 
 1481:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1482:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1483:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1484: 
 1485:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1486:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1487:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1488: }
 1489:     function displaySubject(msg,shwsel) {
 1490:     pDoc = pWin.document;
 1491:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1492:     pDoc.write("<td>Subject<\\/td>");
 1493:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1494:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1495: }
 1496: 
 1497:   function displaySavedMsg(ctr,msg,shwsel) {
 1498:     pDoc = pWin.document;
 1499:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1500:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1501:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1502:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1503: }
 1504: 
 1505:   function newMsg(newmsg,shwsel) {
 1506:     pDoc = pWin.document;
 1507:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1508:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1509:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1510:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1511: }
 1512: 
 1513:   function msgTail() {
 1514:     pDoc = pWin.document;
 1515:     pDoc.write("<\\/table>");
 1516:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1517:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1518:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1519:     pDoc.write("<\\/form>");
 1520:     pDoc.write('$end_page_msg_central');
 1521:     pDoc.close();
 1522: }
 1523: 
 1524: //====================== Script for keyword highlight options ==============
 1525:   function kwhighlight() {
 1526:     var kwclr    = document.SCORE.kwclr.value;
 1527:     var kwsize   = document.SCORE.kwsize.value;
 1528:     var kwstyle  = document.SCORE.kwstyle.value;
 1529:     var redsel = "";
 1530:     var grnsel = "";
 1531:     var blusel = "";
 1532:     if (kwclr=="red")   {var redsel="checked"};
 1533:     if (kwclr=="green") {var grnsel="checked"};
 1534:     if (kwclr=="blue")  {var blusel="checked"};
 1535:     var sznsel = "";
 1536:     var sz1sel = "";
 1537:     var sz2sel = "";
 1538:     if (kwsize=="0")  {var sznsel="checked"};
 1539:     if (kwsize=="+1") {var sz1sel="checked"};
 1540:     if (kwsize=="+2") {var sz2sel="checked"};
 1541:     var synsel = "";
 1542:     var syisel = "";
 1543:     var sybsel = "";
 1544:     if (kwstyle=="")    {var synsel="checked"};
 1545:     if (kwstyle=="<i>") {var syisel="checked"};
 1546:     if (kwstyle=="<b>") {var sybsel="checked"};
 1547:     highlightCentral();
 1548:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1549:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1550:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1551:     highlightend();
 1552:     return;
 1553:   }
 1554: 
 1555:   function highlightCentral() {
 1556: //    if (window.hwdWin) window.hwdWin.close();
 1557:     var xpos = (screen.width-400)/2;
 1558:     xpos = (xpos < 0) ? '0' : xpos;
 1559:     var ypos = (screen.height-330)/2-30;
 1560:     ypos = (ypos < 0) ? '0' : ypos;
 1561: 
 1562:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1563:     hwdWin.focus();
 1564:     var hDoc = hwdWin.document;
 1565:     hDoc.$docopen;
 1566:     hDoc.write('$start_page_highlight_central');
 1567:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1568:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1569: 
 1570:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1571:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1572:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1573:   }
 1574: 
 1575:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1576:     var hDoc = hwdWin.document;
 1577:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1578:     hDoc.write("<td align=\\"left\\">");
 1579:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1580:     hDoc.write("<td align=\\"left\\">");
 1581:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1582:     hDoc.write("<td align=\\"left\\">");
 1583:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1584:     hDoc.write("<\\/tr>");
 1585:   }
 1586: 
 1587:   function highlightend() { 
 1588:     var hDoc = hwdWin.document;
 1589:     hDoc.write("<\\/table>");
 1590:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1591:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1592:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1593:     hDoc.write("<\\/form>");
 1594:     hDoc.write('$end_page_highlight_central');
 1595:     hDoc.close();
 1596:   }
 1597: 
 1598: </script>
 1599: SUBJAVASCRIPT
 1600: }
 1601: 
 1602: sub get_increment {
 1603:     my $increment = $env{'form.increment'};
 1604:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1605:         $increment != .1) {
 1606:         $increment = 1;
 1607:     }
 1608:     return $increment;
 1609: }
 1610: 
 1611: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1612: sub gradeBox {
 1613:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1614:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1615: 	'" src="'.$request->dir_config('lonIconsURL').
 1616: 	'/check.gif" height="16" border="0" />';
 1617:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1618:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1619:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1620:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1621:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1622: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1623:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1624:     my $display_part= &get_display_part($partid,$symb);
 1625:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1626: 				       [$partid]);
 1627:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1628:     if ($last_resets{$partid}) {
 1629:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1630:     }
 1631:     $result.='<table border="0"><tr><td>'.
 1632: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
 1633:     my $ctr = 0;
 1634:     my $thisweight = 0;
 1635:     my $increment = &get_increment();
 1636:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1637:     while ($thisweight<=$wgt) {
 1638: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1639: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1640: 	    $thisweight.')" value="'.$thisweight.'" '.
 1641: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1642: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1643:         $thisweight += $increment;
 1644: 	$ctr++;
 1645:     }
 1646:     $result.='</tr></table>';
 1647:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
 1648:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1649: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1650: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1651: 	$wgt.')" /></td>'."\n";
 1652:     $result.='<td>/'.$wgt.' '.$wgtmsg.
 1653: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1654: 	' </td><td>'."\n";
 1655:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1656: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1657:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1658: 	$result.='<option></option>'.
 1659: 	    '<option selected="selected">excused</option>';
 1660:     } else {
 1661: 	$result.='<option selected="selected"></option>'.
 1662: 	    '<option>excused</option>';
 1663:     }
 1664:     $result.='<option>reset status</option></select>'."\n";
 1665:     $result.="&nbsp;&nbsp;\n";
 1666:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1667: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1668: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1669: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1670:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1671:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1672:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1673:         $aggtries.'" />'."\n";
 1674:     $result.='</td></tr></table>'."\n";
 1675:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1676:     return $result;
 1677: }
 1678: 
 1679: sub handback_box {
 1680:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1681:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1682:     my (@respids);
 1683:      my @part_response_id = &flatten_responseType($responseType);
 1684:     foreach my $part_response_id (@part_response_id) {
 1685:     	my ($part,$resp) = @{ $part_response_id };
 1686:         if ($part eq $partid) {
 1687:             push(@respids,$resp);
 1688:         }
 1689:     }
 1690:     my $result;
 1691:     foreach my $respid (@respids) {
 1692: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1693: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1694: 	next if (!@$files);
 1695: 	my $file_counter = 1;
 1696: 	foreach my $file (@$files) {
 1697: 	    if ($file =~ /\/portfolio\//) {
 1698:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1699:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1700:     	        $file_disp = "$name.$ext";
 1701:     	        $file = $file_path.$file_disp;
 1702:     	        $result.=&mt('Return commented version of [_1] to student.',
 1703:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1704:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1705:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1706:     	        $result.='(File will be uploaded when you click on Save &amp; Next below.)<br />';
 1707:     	        $file_counter++;
 1708: 	    }
 1709: 	}
 1710:     }
 1711:     return $result;    
 1712: }
 1713: 
 1714: sub show_problem {
 1715:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1716:     my $rendered;
 1717:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1718:     &Apache::lonxml::remember_problem_counter();
 1719:     if ($mode eq 'both' or $mode eq 'text') {
 1720: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1721: 						       $env{'request.course.id'},
 1722: 						       undef,\%form);
 1723:     }
 1724:     if ($removeform) {
 1725: 	$rendered=~s|<form(.*?)>||g;
 1726: 	$rendered=~s|</form>||g;
 1727: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1728:     }
 1729:     my $companswer;
 1730:     if ($mode eq 'both' or $mode eq 'answer') {
 1731: 	&Apache::lonxml::restore_problem_counter();
 1732: 	$companswer=
 1733: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1734: 						    $env{'request.course.id'},
 1735: 						    %form);
 1736:     }
 1737:     if ($removeform) {
 1738: 	$companswer=~s|<form(.*?)>||g;
 1739: 	$companswer=~s|</form>||g;
 1740: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1741:     }
 1742:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 1743:     $result.='<table border="0" width="100%">';
 1744:     if ($viewon) {
 1745: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
 1746: 	if ($mode eq 'both' or $mode eq 'text') {
 1747: 	    $result.='View of the problem - ';
 1748: 	} else {
 1749: 	    $result.='Correct answer: ';
 1750: 	}
 1751: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
 1752:     }
 1753:     if ($mode eq 'both') {
 1754: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
 1755: 	$result.='<b>Correct answer:</b><br />'.$companswer;
 1756:     } elsif ($mode eq 'text') {
 1757: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
 1758:     } elsif ($mode eq 'answer') {
 1759: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
 1760:     }
 1761:     $result.='</td></tr></table>';
 1762:     $result.='</td></tr></table><br />';
 1763:     return $result;
 1764: }
 1765: 
 1766: sub files_exist {
 1767:     my ($r, $symb) = @_;
 1768:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1769: 
 1770:     foreach my $student (@students) {
 1771:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1772:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1773: 					      $udom,$uname);
 1774:         my ($string,$timestamp)= &get_last_submission(\%record);
 1775:         foreach my $submission (@$string) {
 1776:             my ($partid,$respid) =
 1777: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1778:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1779: 					   \%record);
 1780:             return 1 if (@$files);
 1781:         }
 1782:     }
 1783:     return 0;
 1784: }
 1785: 
 1786: sub download_all_link {
 1787:     my ($r,$symb) = @_;
 1788:     my $all_students = 
 1789: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1790: 
 1791:     my $parts =
 1792: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1793: 
 1794:     my $identifier = &Apache::loncommon::get_cgi_id();
 1795:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
 1796:                             'cgi.'.$identifier.'.symb' => $symb,
 1797:                             'cgi.'.$identifier.'.parts' => $parts,);
 1798:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1799: 	      &mt('Download All Submitted Documents').'</a>');
 1800:     return
 1801: }
 1802: 
 1803: sub build_section_inputs {
 1804:     my $section_inputs;
 1805:     if ($env{'form.section'} eq '') {
 1806:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1807:     } else {
 1808:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1809:         foreach my $section (@sections) {
 1810:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1811:         }
 1812:     }
 1813:     return $section_inputs;
 1814: }
 1815: 
 1816: # --------------------------- show submissions of a student, option to grade 
 1817: sub submission {
 1818:     my ($request,$counter,$total) = @_;
 1819:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1820:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1821:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1822:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1823:     my $symb = &get_symb($request); 
 1824:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1825: 
 1826:     if (!&canview($usec)) {
 1827: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1828: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1829: 			$env{'request.course.id'}.')</span>');
 1830: 	$request->print(&show_grading_menu_form($symb));
 1831: 	return;
 1832:     }
 1833: 
 1834:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1835:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1836:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1837:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1838:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1839: 	'" src="'.$request->dir_config('lonIconsURL').
 1840: 	'/check.gif" height="16" border="0" />';
 1841: 
 1842:     my %old_essays;
 1843:     # header info
 1844:     if ($counter == 0) {
 1845: 	&sub_page_js($request);
 1846: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1847: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1848: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1849: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1850: 	    &download_all_link($request, $symb);
 1851: 	}
 1852: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
 1853: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
 1854: 
 1855: 	if ($env{'form.handgrade'} eq 'no') {
 1856: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
 1857: 		$checkIcon.' symbol.'."\n";
 1858: 	    $request->print($checkMark);
 1859: 	}
 1860: 
 1861: 	# option to display problem, only once else it cause problems 
 1862:         # with the form later since the problem has a form.
 1863: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1864: 	    my $mode;
 1865: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1866: 		$mode='both';
 1867: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1868: 		$mode='text';
 1869: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1870: 		$mode='answer';
 1871: 	    }
 1872: 	    &Apache::lonxml::clear_problem_counter();
 1873: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1874: 	}
 1875: 
 1876: 	# kwclr is the only variable that is guaranteed to be non blank 
 1877:         # if this subroutine has been called once.
 1878: 	my %keyhash = ();
 1879: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1880: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1881: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1882: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1883: 
 1884: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1885: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1886: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1887: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1888: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1889: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1890: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1891: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1892: 	}
 1893: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1894: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1895: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1896: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1897: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1898: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1899: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1900: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1901: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1902: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1903: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1904: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1905: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1906: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1907: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1908: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1909: 			&build_section_inputs().
 1910: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1911: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1912: 			'<input type="hidden" name="NCT"'.
 1913: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1914: 	if ($env{'form.handgrade'} eq 'yes') {
 1915: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1916: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1917: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1918: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1919: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1920: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1921: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1922: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1923: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1924: 	    }
 1925: 	}
 1926: 	
 1927: 	my ($cts,$prnmsg) = (1,'');
 1928: 	while ($cts <= $env{'form.savemsgN'}) {
 1929: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1930: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1931: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1932: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1933: 		'" />'."\n".
 1934: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1935: 	    $cts++;
 1936: 	}
 1937: 	$request->print($prnmsg);
 1938: 
 1939: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1940: #
 1941: # Print out the keyword options line
 1942: #
 1943: 	    $request->print(<<KEYWORDS);
 1944: &nbsp;<b>Keyword Options:</b>&nbsp;
 1945: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1946: <a href="#" onMouseDown="javascript:getSel(); return false"
 1947:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1948: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1949: KEYWORDS
 1950: #
 1951: # Load the other essays for similarity check
 1952: #
 1953:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1954: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1955: 	    $apath=&escape($apath);
 1956: 	    $apath=~s/\W/\_/gs;
 1957: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 1958:         }
 1959:     }
 1960: 
 1961: # This is where output for one specific student would start
 1962:     my $bgcolor='#DDEEDD';
 1963:     if ($counter%2) { $bgcolor='#DDDDEE'; }
 1964:     $request->print("\n\n".
 1965:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
 1966: 
 1967:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 1968: 	my $mode;
 1969: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 1970: 	    $mode='both';
 1971: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 1972: 	    $mode='text';
 1973: 	} elsif ($env{'form.vAns'} eq 'all') {
 1974: 	    $mode='answer';
 1975: 	}
 1976: 	&Apache::lonxml::clear_problem_counter();
 1977: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
 1978:     }
 1979: 
 1980:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 1981:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1982: 
 1983:     # Display student info
 1984:     $request->print(($counter == 0 ? '' : '<br />'));
 1985:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
 1986: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
 1987: 
 1988:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
 1989:     $result.='<input type="hidden" name="name'.$counter.
 1990: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 1991: 
 1992:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 1993:     my $fullname;
 1994:     my $col_fullnames = [];
 1995:     if ($env{'form.handgrade'} eq 'yes') {
 1996: 	(my $sub_result,$fullname,$col_fullnames)=
 1997: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 1998: 				 $counter);
 1999: 	$result.=$sub_result;
 2000:     }
 2001:     $request->print($result."\n");
 2002: 
 2003:     # print student answer/submission
 2004:     # Options are (1) Handgaded submission only
 2005:     #             (2) Last submission, includes submission that is not handgraded 
 2006:     #                  (for multi-response type part)
 2007:     #             (3) Last submission plus the parts info
 2008:     #             (4) The whole record for this student
 2009:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2010: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2011: 	my $lastsubonly=''.
 2012: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
 2013: 	     $$timestamp)."</td></tr>\n";
 2014: 	if ($$timestamp eq '') {
 2015: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
 2016: 	} else {
 2017: 	    my %seenparts;
 2018: 	    my @part_response_id = &flatten_responseType($responseType);
 2019: 	    foreach my $part (@part_response_id) {
 2020: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2021: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2022: 
 2023: 		my ($partid,$respid) = @{ $part };
 2024: 		my $display_part=&get_display_part($partid,$symb);
 2025: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2026: 		    if (exists($seenparts{$partid})) { next; }
 2027: 		    $seenparts{$partid}=1;
 2028: 		    my $submitby='<b>Part:</b> '.$display_part.
 2029: 			' <b>Collaborative submission by:</b> '.
 2030: 			'<a href="javascript:viewSubmitter(\''.
 2031: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2032: 			'\');" target="_self">'.
 2033: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2034: 		    $request->print($submitby);
 2035: 		    next;
 2036: 		}
 2037: 		my $responsetype = $responseType->{$partid}->{$respid};
 2038: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2039: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
 2040: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2041: 			' )</span>&nbsp; &nbsp;'.
 2042: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
 2043: 		    next;
 2044: 		}
 2045: 		foreach (@$string) {
 2046: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
 2047: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2048: 		    my ($ressub,$subval) = split(/:/,$_,2);
 2049: 		    # Similarity check
 2050: 		    my $similar='';
 2051: 		    if($env{'form.checkPlag'}){
 2052: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2053: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2054: 			if ($osim) {
 2055: 			    $osim=int($osim*100.0);
 2056: 			    my %old_course_desc = 
 2057: 				&Apache::lonnet::coursedescription($ocrsid,
 2058: 								   {'one_time' => 1});
 2059: 
 2060: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2061: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2062: 				    $osim,
 2063: 				    &Apache::loncommon::plainname($oname,$odom),
 2064: 				    $oname,$odom,
 2065: 				    $old_course_desc{'description'},
 2066: 				    $old_course_desc{'num'},
 2067: 				    $old_course_desc{'domain'}).
 2068: 				'</span></h3><blockquote><i>'.
 2069: 				&keywords_highlight($oessay).
 2070: 				'</i></blockquote><hr />';
 2071: 			}
 2072: 		    }
 2073: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2074: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2075: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2076: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2077: 			my $display_part=&get_display_part($partid,$symb);
 2078: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
 2079: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2080: 			    ' )</span>&nbsp; &nbsp;';
 2081: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2082: 			if (@$files) {
 2083: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
 2084: 			    my $file_counter = 0;
 2085: 			    foreach my $file (@$files) {
 2086: 			        $file_counter ++;
 2087: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2088: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2089: 			    }
 2090: 			    $lastsubonly.='<br />';
 2091: 			}
 2092: 			$lastsubonly.='<b>Submitted Answer: </b>'.
 2093: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2094: 					 $respid,\%record,$order);
 2095: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2096: 		    }
 2097: 		}
 2098: 	    }
 2099: 	}
 2100: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
 2101: 	$request->print($lastsubonly);
 2102:     } elsif ($env{'form.lastSub'} eq 'datesub') {
 2103: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2104: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2105:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2106: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2107: 								 $env{'request.course.id'},
 2108: 								 $last,'.submission',
 2109: 								 'Apache::grades::keywords_highlight'));
 2110:     }
 2111: 
 2112:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2113: 	.$udom.'" />'."\n");
 2114:     
 2115:     # return if view submission with no grading option
 2116:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2117: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2118: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2119: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2120: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
 2121: 	if (($env{'form.command'} eq 'submission') || 
 2122: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2123: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2124: 	}
 2125: 	$request->print($toGrade);
 2126: 	return;
 2127:     } else {
 2128: 	$request->print('</td></tr></table></td></tr></table>'."\n");
 2129:     }
 2130: 
 2131:     # essay grading message center
 2132:     if ($env{'form.handgrade'} eq 'yes') {
 2133: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2134: 	my $msgfor = $givenn.' '.$lastname;
 2135: 	if (scalar(@$col_fullnames) > 0) {
 2136: 	    my $lastone = pop(@$col_fullnames);
 2137: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2138: 	}
 2139: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2140: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2141: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2142: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2143: 	    ',\''.$msgfor.'\');" target="_self">'.
 2144: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2145: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2146: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2147: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2148: 	    '<br />&nbsp;('.
 2149: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
 2150: 	$request->print($result);
 2151:     }
 2152:     if ($perm{'vgr'}) {
 2153: 	$request->print('<br />'.
 2154: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2155: 						   $uname,$udom,'check'));
 2156:     }
 2157:     if ($perm{'opa'}) {
 2158: 	$request->print('<br />'.
 2159: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2160: 					 $uname,$udom,$symb,'check'));
 2161:     }
 2162: 
 2163:     my %seen = ();
 2164:     my @partlist;
 2165:     my @gradePartRespid;
 2166:     my @part_response_id = &flatten_responseType($responseType);
 2167:     foreach my $part_response_id (@part_response_id) {
 2168:     	my ($partid,$respid) = @{ $part_response_id };
 2169: 	my $part_resp = join('_',@{ $part_response_id });
 2170: 	next if ($seen{$partid} > 0);
 2171: 	$seen{$partid}++;
 2172: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2173: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2174: 	push @partlist,$partid;
 2175: 	push @gradePartRespid,$partid.'.'.$respid;
 2176: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2177:     }
 2178:     $result='<input type="hidden" name="partlist'.$counter.
 2179: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2180:     $result.='<input type="hidden" name="gradePartRespid'.
 2181: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2182:     my $ctr = 0;
 2183:     while ($ctr < scalar(@partlist)) {
 2184: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2185: 	    $partlist[$ctr].'" />'."\n";
 2186: 	$ctr++;
 2187:     }
 2188:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
 2189: 
 2190: # Done with printing info for one student
 2191: 
 2192:     $request->print('</td></tr></table></p>');
 2193: 
 2194: 
 2195:     # print end of form
 2196:     if ($counter == $total) {
 2197: 	my $endform='<table border="0"><tr><td>'."\n";
 2198: 	$endform.='<input type="button" value="Save & Next" '.
 2199: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2200: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2201: 	my $ntstu ='<select name="NTSTU">'.
 2202: 	    '<option>1</option><option>2</option>'.
 2203: 	    '<option>3</option><option>5</option>'.
 2204: 	    '<option>7</option><option>10</option></select>'."\n";
 2205: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2206: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2207: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
 2208: 	$endform.='<input type="button" value="Previous" '.
 2209: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2210: 	    '<input type="button" value="Next" '.
 2211: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2212: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
 2213:         $endform.="<input type='hidden' value='".&get_increment().
 2214:             "' name='increment' />";
 2215: 	$endform.='</td><tr></table></form>';
 2216: 	$endform.=&show_grading_menu_form($symb);
 2217: 	$request->print($endform);
 2218:     }
 2219:     return '';
 2220: }
 2221: 
 2222: sub check_collaborators {
 2223:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2224:     my ($result,@col_fullnames);
 2225:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2226:     foreach my $part (keys(%$handgrade)) {
 2227: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2228: 					'.maxcollaborators',
 2229: 					$symb,$udom,$uname);
 2230: 	next if ($ncol <= 0);
 2231: 	$part =~ s/\_/\./g;
 2232: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2233: 	my (@good_collaborators, @bad_collaborators);
 2234: 	foreach my $possible_collaborator
 2235: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2236: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2237: 	    next if ($possible_collaborator eq '');
 2238: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2239: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2240: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2241: 	    # Doing this grep allows 'fuzzy' specification
 2242: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2243: 			       keys(%$classlist));
 2244: 	    if (! scalar(@matches)) {
 2245: 		push(@bad_collaborators, $possible_collaborator);
 2246: 	    } else {
 2247: 		push(@good_collaborators, @matches);
 2248: 	    }
 2249: 	}
 2250: 	if (scalar(@good_collaborators) != 0) {
 2251: 	    $result.='<br />'.&mt('Collaborators: ');
 2252: 	    foreach my $name (@good_collaborators) {
 2253: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2254: 		push(@col_fullnames, $givenn.' '.$lastname);
 2255: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2256: 	    }
 2257: 	    $result.='<br />'."\n";
 2258: 	    my ($part)=split(/\./,$part);
 2259: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2260: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2261: 		"\n";
 2262: 	}
 2263: 	if (scalar(@bad_collaborators) > 0) {
 2264: 	    $result.='<div class="LC_warning">';
 2265: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2266: 	    $result .= '</div>';
 2267: 	}         
 2268: 	if (scalar(@bad_collaborators > $ncol)) {
 2269: 	    $result .= '<div class="LC_warning">';
 2270: 	    $result .= &mt('This student has submitted too many '.
 2271: 		'collaborators.  Maximum is [_1].',$ncol);
 2272: 	    $result .= '</div>';
 2273: 	}
 2274:     }
 2275:     return ($result,$fullname,\@col_fullnames);
 2276: }
 2277: 
 2278: #--- Retrieve the last submission for all the parts
 2279: sub get_last_submission {
 2280:     my ($returnhash)=@_;
 2281:     my (@string,$timestamp);
 2282:     if ($$returnhash{'version'}) {
 2283: 	my %lasthash=();
 2284: 	my ($version);
 2285: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2286: 	    foreach my $key (sort(split(/\:/,
 2287: 					$$returnhash{$version.':keys'}))) {
 2288: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2289: 		$timestamp = 
 2290: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
 2291: 	    }
 2292: 	}
 2293: 	foreach my $key (keys(%lasthash)) {
 2294: 	    next if ($key !~ /\.submission$/);
 2295: 
 2296: 	    my ($partid,$foo) = split(/submission$/,$key);
 2297: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2298: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2299: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2300: 	}
 2301:     }
 2302:     if (!@string) {
 2303: 	$string[0] =
 2304: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2305:     }
 2306:     return (\@string,\$timestamp);
 2307: }
 2308: 
 2309: #--- High light keywords, with style choosen by user.
 2310: sub keywords_highlight {
 2311:     my $string    = shift;
 2312:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2313:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2314:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2315:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2316:     foreach my $keyword (@keylist) {
 2317: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2318:     }
 2319:     return $string;
 2320: }
 2321: 
 2322: #--- Called from submission routine
 2323: sub processHandGrade {
 2324:     my ($request) = shift;
 2325:     my $symb   = &get_symb($request);
 2326:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2327:     my $button = $env{'form.gradeOpt'};
 2328:     my $ngrade = $env{'form.NCT'};
 2329:     my $ntstu  = $env{'form.NTSTU'};
 2330:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2331:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2332: 
 2333:     if ($button eq 'Save & Next') {
 2334: 	my $ctr = 0;
 2335: 	while ($ctr < $ngrade) {
 2336: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2337: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2338: 	    if ($errorflag eq 'no_score') {
 2339: 		$ctr++;
 2340: 		next;
 2341: 	    }
 2342: 	    if ($errorflag eq 'not_allowed') {
 2343: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2344: 		$ctr++;
 2345: 		next;
 2346: 	    }
 2347: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2348: 	    my ($subject,$message,$msgstatus) = ('','','');
 2349: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2350:             my ($feedurl,$showsymb) =
 2351: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2352: 	    my $messagetail;
 2353: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2354: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2355: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2356: 		$subject.=' ['.$restitle.']';
 2357: 		my (@msgnum) = split(/,/,$includemsg);
 2358: 		foreach (@msgnum) {
 2359: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2360: 		}
 2361: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2362: 		if ($env{'form.withgrades'.$ctr}) {
 2363: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2364: 		    $messagetail = " for <a href=\"".
 2365: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2366: 		}
 2367: 		$msgstatus = 
 2368:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2369: 						     $message.$messagetail,
 2370:                                                      undef,$feedurl,undef,
 2371:                                                      undef,undef,$showsymb,
 2372:                                                      $restitle);
 2373: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2374: 				$msgstatus);
 2375: 	    }
 2376: 	    if ($env{'form.collaborator'.$ctr}) {
 2377: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2378: 		foreach my $collabstr (@collabstrs) {
 2379: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2380: 		    foreach my $collaborator (@collaborators) {
 2381: 			my ($errorflag,$pts,$wgt) = 
 2382: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2383: 					   $env{'form.unamedom'.$ctr},$part);
 2384: 			if ($errorflag eq 'not_allowed') {
 2385: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2386: 			    next;
 2387: 			} elsif ($message ne '') {
 2388: 			    my ($baseurl,$showsymb) = 
 2389: 				&get_feedurl_and_symb($symb,$collaborator,
 2390: 						      $udom);
 2391: 			    if ($env{'form.withgrades'.$ctr}) {
 2392: 				$messagetail = " for <a href=\"".
 2393:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2394: 			    }
 2395: 			    $msgstatus = 
 2396: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2397: 			}
 2398: 		    }
 2399: 		}
 2400: 	    }
 2401: 	    $ctr++;
 2402: 	}
 2403:     }
 2404: 
 2405:     if ($env{'form.handgrade'} eq 'yes') {
 2406: 	# Keywords sorted in alphabatical order
 2407: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2408: 	my %keyhash = ();
 2409: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2410: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2411: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2412: 	$env{'form.keywords'} = join(' ',@keywords);
 2413: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2414: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2415: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2416: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2417: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2418: 
 2419: 	# message center - Order of message gets changed. Blank line is eliminated.
 2420: 	# New messages are saved in env for the next student.
 2421: 	# All messages are saved in nohist_handgrade.db
 2422: 	my ($ctr,$idx) = (1,1);
 2423: 	while ($ctr <= $env{'form.savemsgN'}) {
 2424: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2425: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2426: 		$idx++;
 2427: 	    }
 2428: 	    $ctr++;
 2429: 	}
 2430: 	$ctr = 0;
 2431: 	while ($ctr < $ngrade) {
 2432: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2433: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2434: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2435: 		$idx++;
 2436: 	    }
 2437: 	    $ctr++;
 2438: 	}
 2439: 	$env{'form.savemsgN'} = --$idx;
 2440: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2441: 	my $putresult = &Apache::lonnet::put
 2442: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2443:     }
 2444:     # Called by Save & Refresh from Highlight Attribute Window
 2445:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2446:     if ($env{'form.refresh'} eq 'on') {
 2447: 	my ($ctr,$total) = (0,0);
 2448: 	while ($ctr < $ngrade) {
 2449: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2450: 	    $ctr++;
 2451: 	}
 2452: 	$env{'form.NTSTU'}=$ngrade;
 2453: 	$ctr = 0;
 2454: 	while ($ctr < $total) {
 2455: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2456: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2457: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2458: 	    &submission($request,$ctr,$total-1);
 2459: 	    $ctr++;
 2460: 	}
 2461: 	return '';
 2462:     }
 2463: 
 2464: # Go directly to grade student - from submission or link from chart page
 2465:     if ($button eq 'Grade Student') {
 2466: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2467: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2468: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2469: 	$env{'form.fullname'} = $$fullname{$processUser};
 2470: 	&submission($request,0,0);
 2471: 	return '';
 2472:     }
 2473: 
 2474:     # Get the next/previous one or group of students
 2475:     my $firststu = $env{'form.unamedom0'};
 2476:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2477:     my $ctr = 2;
 2478:     while ($laststu eq '') {
 2479: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2480: 	$ctr++;
 2481: 	$laststu = $firststu if ($ctr > $ngrade);
 2482:     }
 2483: 
 2484:     my (@parsedlist,@nextlist);
 2485:     my ($nextflg) = 0;
 2486:     foreach (sort 
 2487: 	     {
 2488: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2489: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2490: 		 }
 2491: 		 return $a cmp $b;
 2492: 	     } (keys(%$fullname))) {
 2493: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2494: 	    push @parsedlist,$_;
 2495: 	}
 2496: 	$nextflg = 1 if ($_ eq $laststu);
 2497: 	if ($button eq 'Previous') {
 2498: 	    last if ($_ eq $firststu);
 2499: 	    push @parsedlist,$_;
 2500: 	}
 2501:     }
 2502:     $ctr = 0;
 2503:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2504:     my ($partlist) = &response_type($symb);
 2505:     foreach my $student (@parsedlist) {
 2506: 	my $submitonly=$env{'form.submitonly'};
 2507: 	my ($uname,$udom) = split(/:/,$student);
 2508: 	
 2509: 	if ($submitonly eq 'queued') {
 2510: 	    my %queue_status = 
 2511: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2512: 							$udom,$uname);
 2513: 	    next if (!defined($queue_status{'gradingqueue'}));
 2514: 	}
 2515: 
 2516: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2517: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2518: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2519: 	    my $submitted = 0;
 2520: 	    my $ungraded = 0;
 2521: 	    my $incorrect = 0;
 2522: 	    foreach (keys(%status)) {
 2523: 		$submitted = 1 if ($status{$_} ne 'nothing');
 2524: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
 2525: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 2526: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 2527: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2528: 		    $submitted = 0;
 2529: 		}
 2530: 	    }
 2531: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2532: 				     $submitonly eq 'incorrect' ||
 2533: 				     $submitonly eq 'graded'));
 2534: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2535: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2536: 	}
 2537: 	push @nextlist,$student if ($ctr < $ntstu);
 2538: 	last if ($ctr == $ntstu);
 2539: 	$ctr++;
 2540:     }
 2541: 
 2542:     $ctr = 0;
 2543:     my $total = scalar(@nextlist)-1;
 2544: 
 2545:     foreach (sort @nextlist) {
 2546: 	my ($uname,$udom,$submitter) = split(/:/);
 2547: 	$env{'form.student'}  = $uname;
 2548: 	$env{'form.userdom'}  = $udom;
 2549: 	$env{'form.fullname'} = $$fullname{$_};
 2550: 	&submission($request,$ctr,$total);
 2551: 	$ctr++;
 2552:     }
 2553:     if ($total < 0) {
 2554: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
 2555: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
 2556: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
 2557: 	$the_end.=&show_grading_menu_form($symb);
 2558: 	$request->print($the_end);
 2559:     }
 2560:     return '';
 2561: }
 2562: 
 2563: #---- Save the score and award for each student, if changed
 2564: sub saveHandGrade {
 2565:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2566:     my @version_parts;
 2567:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2568: 					   $env{'request.course.id'});
 2569:     if (!&canmodify($usec)) { return('not_allowed'); }
 2570:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2571:     my @parts_graded;
 2572:     my %newrecord  = ();
 2573:     my ($pts,$wgt) = ('','');
 2574:     my %aggregate = ();
 2575:     my $aggregateflag = 0;
 2576:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2577:     foreach my $new_part (@parts) {
 2578: 	#collaborator ($submi may vary for different parts
 2579: 	if ($submitter && $new_part ne $part) { next; }
 2580: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2581: 	if ($dropMenu eq 'excused') {
 2582: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2583: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2584: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2585: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2586: 		}
 2587: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2588: 	    }
 2589: 	} elsif ($dropMenu eq 'reset status'
 2590: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2591: 	    foreach my $key (keys (%record)) {
 2592: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2593: 	    }
 2594: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2595: 		"$env{'user.name'}:$env{'user.domain'}";
 2596:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2597: 
 2598:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2599: 					       [$new_part]);
 2600:             my $aggtries =$totaltries;
 2601:             if ($last_resets{$new_part}) {
 2602:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2603: 					   $new_part);
 2604:             }
 2605: 
 2606:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2607:             if ($aggtries > 0) {
 2608:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2609:                 $aggregateflag = 1;
 2610:             }
 2611: 	} elsif ($dropMenu eq '') {
 2612: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2613: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2614: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2615: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2616: 		next;
 2617: 	    }
 2618: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2619: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2620: 	    my $partial= $pts/$wgt;
 2621: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2622: 		#do not update score for part if not changed.
 2623:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2624: 		next;
 2625: 	    } else {
 2626: 	        push @parts_graded, $new_part;
 2627: 	    }
 2628: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2629: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2630: 	    }
 2631: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2632: 	    if ($partial == 0) {
 2633: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2634: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2635: 		}
 2636: 	    } else {
 2637: 		if ($record{$reckey} ne 'correct_by_override') {
 2638: 		    $newrecord{$reckey} = 'correct_by_override';
 2639: 		}
 2640: 	    }	    
 2641: 	    if ($submitter && 
 2642: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2643: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2644: 	    }
 2645: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2646: 		"$env{'user.name'}:$env{'user.domain'}";
 2647: 	}
 2648: 	# unless problem has been graded, set flag to version the submitted files
 2649: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2650: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2651: 	        $dropMenu eq 'reset status')
 2652: 	   {
 2653: 	    push (@version_parts,$new_part);
 2654: 	}
 2655:     }
 2656:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2657:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2658: 
 2659:     if (%newrecord) {
 2660:         if (@version_parts) {
 2661:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2662:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2663: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2664: 	    foreach my $new_part (@version_parts) {
 2665: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2666: 				$new_part,\%newrecord);
 2667: 	    }
 2668:         }
 2669: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2670: 				$env{'request.course.id'},$domain,$stuname);
 2671: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2672: 				     $cdom,$cnum,$domain,$stuname);
 2673:     }
 2674:     if ($aggregateflag) {
 2675:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2676: 			      $cdom,$cnum);
 2677:     }
 2678:     return ('',$pts,$wgt);
 2679: }
 2680: 
 2681: sub check_and_remove_from_queue {
 2682:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2683:     my @ungraded_parts;
 2684:     foreach my $part (@{$parts}) {
 2685: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2686: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2687: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2688: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2689: 		) {
 2690: 	    push(@ungraded_parts, $part);
 2691: 	}
 2692:     }
 2693:     if ( !@ungraded_parts ) {
 2694: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2695: 					       $cnum,$domain,$stuname);
 2696:     }
 2697: }
 2698: 
 2699: sub handback_files {
 2700:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2701:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
 2702:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2703: 
 2704:     my @part_response_id = &flatten_responseType($responseType);
 2705:     foreach my $part_response_id (@part_response_id) {
 2706:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2707: 	my $part_resp = join('_',@{ $part_response_id });
 2708:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2709:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2710:                 my $file_counter = 1;
 2711: 		my $file_msg;
 2712:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2713:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2714:                     my ($directory,$answer_file) = 
 2715:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2716:                     my ($answer_name,$answer_ver,$answer_ext) =
 2717: 		        &file_name_version_ext($answer_file);
 2718: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2719: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
 2720: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2721:                     # fix file name
 2722:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2723:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2724:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2725:             	                                $save_file_name);
 2726:                     if ($result !~ m|^/uploaded/|) {
 2727:                         $request->print('<span class="LC_error">An error occurred ('.$result.
 2728:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
 2729:                     } else {
 2730:                         # mark the file as read only
 2731:                         my @files = ($save_file_name);
 2732:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2733:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2734: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2735: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2736: 			}
 2737:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2738: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2739: 
 2740:                     }
 2741:                     $request->print("<br />".$fname." will be the uploaded file name");
 2742:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2743:                     $file_counter++;
 2744:                 }
 2745: 		my $subject = "File Handed Back by Instructor ";
 2746: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2747: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2748: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2749: 		$message .= " and can be found in your portfolio space.";
 2750: 		my ($feedurl,$showsymb) = 
 2751: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2752:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2753: 		my $msgstatus = 
 2754:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2755: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2756:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2757:             }
 2758:         }
 2759:     return;
 2760: }
 2761: 
 2762: sub get_feedurl_and_symb {
 2763:     my ($symb,$uname,$udom) = @_;
 2764:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2765:     $url = &Apache::lonnet::clutter($url);
 2766:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2767: 					$symb,$udom,$uname);
 2768:     if ($encrypturl =~ /^yes$/i) {
 2769: 	&Apache::lonenc::encrypted(\$url,1);
 2770: 	&Apache::lonenc::encrypted(\$symb,1);
 2771:     }
 2772:     return ($url,$symb);
 2773: }
 2774: 
 2775: sub get_submitted_files {
 2776:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2777:     my @files;
 2778:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2779:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2780:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2781:     	    push(@files,$file_url.$file);
 2782:         }
 2783:     }
 2784:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2785:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2786:     }
 2787:     return (\@files);
 2788: }
 2789: 
 2790: # ----------- Provides number of tries since last reset.
 2791: sub get_num_tries {
 2792:     my ($record,$last_reset,$part) = @_;
 2793:     my $timestamp = '';
 2794:     my $num_tries = 0;
 2795:     if ($$record{'version'}) {
 2796:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2797:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2798:                 $timestamp = $$record{$version.':timestamp'};
 2799:                 if ($timestamp > $last_reset) {
 2800:                     $num_tries ++;
 2801:                 } else {
 2802:                     last;
 2803:                 }
 2804:             }
 2805:         }
 2806:     }
 2807:     return $num_tries;
 2808: }
 2809: 
 2810: # ----------- Determine decrements required in aggregate totals 
 2811: sub decrement_aggs {
 2812:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2813:     my %decrement = (
 2814:                         attempts => 0,
 2815:                         users => 0,
 2816:                         correct => 0
 2817:                     );
 2818:     $decrement{'attempts'} = $aggtries;
 2819:     if ($solvedstatus =~ /^correct/) {
 2820:         $decrement{'correct'} = 1;
 2821:     }
 2822:     if ($aggtries == $totaltries) {
 2823:         $decrement{'users'} = 1;
 2824:     }
 2825:     foreach my $type (keys (%decrement)) {
 2826:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2827:     }
 2828:     return;
 2829: }
 2830: 
 2831: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2832: sub get_last_resets {
 2833:     my ($symb,$courseid,$partids) =@_;
 2834:     my %last_resets;
 2835:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2836:     my $cname = $env{'course.'.$courseid.'.num'};
 2837:     my @keys;
 2838:     foreach my $part (@{$partids}) {
 2839: 	push(@keys,"$symb\0$part\0resettime");
 2840:     }
 2841:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2842: 				     $cdom,$cname);
 2843:     foreach my $part (@{$partids}) {
 2844: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2845:     }
 2846:     return %last_resets;
 2847: }
 2848: 
 2849: # ----------- Handles creating versions for portfolio files as answers
 2850: sub version_portfiles {
 2851:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2852:     my $version_parts = join('|',@$v_flag);
 2853:     my @returned_keys;
 2854:     my $parts = join('|', @$parts_graded);
 2855:     my $portfolio_root = &propath($domain,$stu_name).
 2856: 	'/userfiles/portfolio';
 2857:     foreach my $key (keys(%$record)) {
 2858:         my $new_portfiles;
 2859:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2860:             my @versioned_portfiles;
 2861:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2862:             foreach my $file (@portfiles) {
 2863:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2864:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2865: 		my ($answer_name,$answer_ver,$answer_ext) =
 2866: 		    &file_name_version_ext($answer_file);
 2867:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
 2868:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2869:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2870:                 if ($new_answer ne 'problem getting file') {
 2871:                     push(@versioned_portfiles, $directory.$new_answer);
 2872:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2873:                         [$directory.$new_answer],
 2874:                         [$symb,$env{'request.course.id'},'graded']);
 2875:                 }
 2876:             }
 2877:             $$record{$key} = join(',',@versioned_portfiles);
 2878:             push(@returned_keys,$key);
 2879:         }
 2880:     } 
 2881:     return (@returned_keys);   
 2882: }
 2883: 
 2884: sub get_next_version {
 2885:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2886:     my $version;
 2887:     foreach my $row (@$dir_list) {
 2888:         my ($file) = split(/\&/,$row,2);
 2889:         my ($file_name,$file_version,$file_ext) =
 2890: 	    &file_name_version_ext($file);
 2891:         if (($file_name eq $answer_name) && 
 2892: 	    ($file_ext eq $answer_ext)) {
 2893:                 # gets here if filename and extension match, regardless of version
 2894:                 if ($file_version ne '') {
 2895:                 # a versioned file is found  so save it for later
 2896:                 if ($file_version > $version) {
 2897: 		    $version = $file_version;
 2898: 	        }
 2899:             }
 2900:         }
 2901:     } 
 2902:     $version ++;
 2903:     return($version);
 2904: }
 2905: 
 2906: sub version_selected_portfile {
 2907:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2908:     my ($answer_name,$answer_ver,$answer_ext) =
 2909:         &file_name_version_ext($file_name);
 2910:     my $new_answer;
 2911:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2912:     if($env{'form.copy'} eq '-1') {
 2913:         $new_answer = 'problem getting file';
 2914:     } else {
 2915:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2916:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2917:                             $stu_name,$domain,'copy',
 2918: 		        '/portfolio'.$directory.$new_answer);
 2919:     }    
 2920:     return ($new_answer);
 2921: }
 2922: 
 2923: sub file_name_version_ext {
 2924:     my ($file)=@_;
 2925:     my @file_parts = split(/\./, $file);
 2926:     my ($name,$version,$ext);
 2927:     if (@file_parts > 1) {
 2928: 	$ext=pop(@file_parts);
 2929: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 2930: 	    $version=pop(@file_parts);
 2931: 	}
 2932: 	$name=join('.',@file_parts);
 2933:     } else {
 2934: 	$name=join('.',@file_parts);
 2935:     }
 2936:     return($name,$version,$ext);
 2937: }
 2938: 
 2939: #--------------------------------------------------------------------------------------
 2940: #
 2941: #-------------------------- Next few routines handles grading by section or whole class
 2942: #
 2943: #--- Javascript to handle grading by section or whole class
 2944: sub viewgrades_js {
 2945:     my ($request) = shift;
 2946: 
 2947:     $request->print(<<VIEWJAVASCRIPT);
 2948: <script type="text/javascript" language="javascript">
 2949:    function writePoint(partid,weight,point) {
 2950: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2951: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2952: 	if (point == "textval") {
 2953: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 2954: 	    if (isNaN(point) || parseFloat(point) < 0) {
 2955: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 2956: 		var resetbox = false;
 2957: 		for (var i=0; i<radioButton.length; i++) {
 2958: 		    if (radioButton[i].checked) {
 2959: 			textbox.value = i;
 2960: 			resetbox = true;
 2961: 		    }
 2962: 		}
 2963: 		if (!resetbox) {
 2964: 		    textbox.value = "";
 2965: 		}
 2966: 		return;
 2967: 	    }
 2968: 	    if (parseFloat(point) > parseFloat(weight)) {
 2969: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 2970: 				   ") greater than the weight for the part. Accept?");
 2971: 		if (resp == false) {
 2972: 		    textbox.value = "";
 2973: 		    return;
 2974: 		}
 2975: 	    }
 2976: 	    for (var i=0; i<radioButton.length; i++) {
 2977: 		radioButton[i].checked=false;
 2978: 		if (parseFloat(point) == i) {
 2979: 		    radioButton[i].checked=true;
 2980: 		}
 2981: 	    }
 2982: 
 2983: 	} else {
 2984: 	    textbox.value = parseFloat(point);
 2985: 	}
 2986: 	for (i=0;i<document.classgrade.total.value;i++) {
 2987: 	    var user = document.classgrade["ctr"+i].value;
 2988: 	    user = user.replace(new RegExp(':', 'g'),"_");
 2989: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2990: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2991: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2992: 	    if (saveval != "correct") {
 2993: 		scorename.value = point;
 2994: 		if (selname[0].selected != true) {
 2995: 		    selname[0].selected = true;
 2996: 		}
 2997: 	    }
 2998: 	}
 2999: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3000:     }
 3001: 
 3002:     function writeRadText(partid,weight) {
 3003: 	var selval   = document.classgrade["SELVAL_"+partid];
 3004: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3005:         var override = document.classgrade["FORCE_"+partid].checked;
 3006: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3007: 	if (selval[1].selected || selval[2].selected) {
 3008: 	    for (var i=0; i<radioButton.length; i++) {
 3009: 		radioButton[i].checked=false;
 3010: 
 3011: 	    }
 3012: 	    textbox.value = "";
 3013: 
 3014: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3015: 		var user = document.classgrade["ctr"+i].value;
 3016: 		user = user.replace(new RegExp(':', 'g'),"_");
 3017: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3018: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3019: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3020: 		if ((saveval != "correct") || override) {
 3021: 		    scorename.value = "";
 3022: 		    if (selval[1].selected) {
 3023: 			selname[1].selected = true;
 3024: 		    } else {
 3025: 			selname[2].selected = true;
 3026: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3027: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3028: 		    }
 3029: 		}
 3030: 	    }
 3031: 	} else {
 3032: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3033: 		var user = document.classgrade["ctr"+i].value;
 3034: 		user = user.replace(new RegExp(':', 'g'),"_");
 3035: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3036: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3037: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3038: 		if ((saveval != "correct") || override) {
 3039: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3040: 		    selname[0].selected = true;
 3041: 		}
 3042: 	    }
 3043: 	}	    
 3044:     }
 3045: 
 3046:     function changeSelect(partid,user) {
 3047: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3048: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3049: 	var point  = textbox.value;
 3050: 	var weight = document.classgrade["weight_"+partid].value;
 3051: 
 3052: 	if (isNaN(point) || parseFloat(point) < 0) {
 3053: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3054: 	    textbox.value = "";
 3055: 	    return;
 3056: 	}
 3057: 	if (parseFloat(point) > parseFloat(weight)) {
 3058: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3059: 			       ") greater than the weight of the part. Accept?");
 3060: 	    if (resp == false) {
 3061: 		textbox.value = "";
 3062: 		return;
 3063: 	    }
 3064: 	}
 3065: 	selval[0].selected = true;
 3066:     }
 3067: 
 3068:     function changeOneScore(partid,user) {
 3069: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3070: 	if (selval[1].selected || selval[2].selected) {
 3071: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3072: 	    if (selval[2].selected) {
 3073: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3074: 	    }
 3075:         }
 3076:     }
 3077: 
 3078:     function resetEntry(numpart) {
 3079: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3080: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3081: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3082: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3083: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3084: 	    for (var i=0; i<radioButton.length; i++) {
 3085: 		radioButton[i].checked=false;
 3086: 
 3087: 	    }
 3088: 	    textbox.value = "";
 3089: 	    selval[0].selected = true;
 3090: 
 3091: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3092: 		var user = document.classgrade["ctr"+i].value;
 3093: 		user = user.replace(new RegExp(':', 'g'),"_");
 3094: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3095: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3096: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3097: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3098: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3099: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3100: 		if (saveselval == "excused") {
 3101: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3102: 		} else {
 3103: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3104: 		}
 3105: 	    }
 3106: 	}
 3107:     }
 3108: 
 3109: </script>
 3110: VIEWJAVASCRIPT
 3111: }
 3112: 
 3113: #--- show scores for a section or whole class w/ option to change/update a score
 3114: sub viewgrades {
 3115:     my ($request) = shift;
 3116:     &viewgrades_js($request);
 3117: 
 3118:     my ($symb) = &get_symb($request);
 3119:     #need to make sure we have the correct data for later EXT calls, 
 3120:     #thus invalidate the cache
 3121:     &Apache::lonnet::devalidatecourseresdata(
 3122:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3123:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3124:     &Apache::lonnet::clear_EXT_cache_status();
 3125: 
 3126:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3127:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
 3128: 
 3129:     #view individual student submission form - called using Javascript viewOneStudent
 3130:     $result.=&jscriptNform($symb);
 3131: 
 3132:     #beginning of class grading form
 3133:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3134:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3135: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3136: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3137: 	&build_section_inputs().
 3138: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3139: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3140: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3141: 
 3142:     my $sectionClass;
 3143:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3144:     if ($env{'form.section'} eq 'all') {
 3145: 	$sectionClass='Class </h3>';
 3146:     } elsif ($env{'form.section'} eq 'none') {
 3147: 	$sectionClass=&mt('Students in no Section').'</h3>';
 3148:     } else {
 3149: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
 3150:     }
 3151:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
 3152:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 3153: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
 3154:     #radio buttons/text box for assigning points for a section or class.
 3155:     #handles different parts of a problem
 3156:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3157:     my %weight = ();
 3158:     my $ctsparts = 0;
 3159:     $result.='<table border="0">';
 3160:     my %seen = ();
 3161:     my @part_response_id = &flatten_responseType($responseType);
 3162:     foreach my $part_response_id (@part_response_id) {
 3163:     	my ($partid,$respid) = @{ $part_response_id };
 3164: 	my $part_resp = join('_',@{ $part_response_id });
 3165: 	next if $seen{$partid};
 3166: 	$seen{$partid}++;
 3167: 	my $handgrade=$$handgrade{$part_resp};
 3168: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3169: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3170: 
 3171: 	$result.='<input type="hidden" name="partid_'.
 3172: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3173: 	$result.='<input type="hidden" name="weight_'.
 3174: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3175: 	my $display_part=&get_display_part($partid,$symb);
 3176: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
 3177: 	$result.='<table border="0"><tr>';  
 3178: 	my $ctr = 0;
 3179: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3180: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3181: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3182: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3183: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3184: 	    $ctr++;
 3185: 	}
 3186: 	$result.='</tr></table>';
 3187: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
 3188: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3189: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3190: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3191: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
 3192: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3193: 		$weight{$partid}.')"> '.
 3194: 	    '<option selected="selected"> </option>'.
 3195: 	    '<option>excused</option>'.
 3196: 	    '<option>reset status</option></select></td>'.
 3197:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
 3198: 	$ctsparts++;
 3199:     }
 3200:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
 3201: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3202:     $result.='<input type="button" value="Revert to Default" '.
 3203: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
 3204: 
 3205:     #table listing all the students in a section/class
 3206:     #header of table
 3207:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
 3208:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 3209: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
 3210: 	'<td>'.&nameUserString('header')."</td>\n";
 3211:     my (@parts) = sort(&getpartlist($symb));
 3212:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3213:     my @partids = ();
 3214:     foreach my $part (@parts) {
 3215: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3216: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3217: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3218: 	my ($partid) = &split_part_type($part);
 3219:         push(@partids, $partid);
 3220: 	my $display_part=&get_display_part($partid,$symb);
 3221: 	if ($display =~ /^Partial Credit Factor/) {
 3222: 	    $result.='<td><b>Score Part:</b> '.$display_part.
 3223: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
 3224: 	    next;
 3225: 	} else {
 3226: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
 3227: 	}
 3228: 	$display =~ s|Problem Status|Grade Status<br />|;
 3229: 	$result.='<td><b>'.$display.'</td>'."\n";
 3230:     }
 3231:     $result.='</tr>';
 3232: 
 3233:     my %last_resets = 
 3234: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3235: 
 3236:     #get info for each student
 3237:     #list all the students - with points and grade status
 3238:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3239:     my $ctr = 0;
 3240:     foreach (sort 
 3241: 	     {
 3242: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3243: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3244: 		 }
 3245: 		 return $a cmp $b;
 3246: 	     } (keys(%$fullname))) {
 3247: 	$ctr++;
 3248: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3249: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3250:     }
 3251:     $result.='</table></td></tr></table>';
 3252:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3253:     $result.='<input type="button" value="Save" '.
 3254: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3255:     if (scalar(%$fullname) eq 0) {
 3256: 	my $colspan=3+scalar(@parts);
 3257: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3258:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3259: 	$result='<span class="LC_warning">'.
 3260: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
 3261: 	        $section_display, $stu_status).
 3262: 	    '</span>';
 3263:     }
 3264:     $result.=&show_grading_menu_form($symb);
 3265:     return $result;
 3266: }
 3267: 
 3268: #--- call by previous routine to display each student
 3269: sub viewstudentgrade {
 3270:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3271:     my ($uname,$udom) = split(/:/,$student);
 3272:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3273:     my %aggregates = (); 
 3274:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
 3275: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3276: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3277: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3278: 	'\');" target="_self">'.$fullname.'</a> '.
 3279: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3280:     $student=~s/:/_/; # colon doen't work in javascript for names
 3281:     foreach my $apart (@$parts) {
 3282: 	my ($part,$type) = &split_part_type($apart);
 3283: 	my $score=$record{"resource.$part.$type"};
 3284:         $result.='<td align="center">';
 3285:         my ($aggtries,$totaltries);
 3286:         unless (exists($aggregates{$part})) {
 3287: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3288: 
 3289: 	    $aggtries = $totaltries;
 3290:             if ($$last_resets{$part}) {  
 3291:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3292: 					   $part);
 3293:             }
 3294:             $result.='<input type="hidden" name="'.
 3295:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3296:             $result.='<input type="hidden" name="'.
 3297:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3298:             $aggregates{$part} = 1;
 3299:         }
 3300: 	if ($type eq 'awarded') {
 3301: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3302: 	    $result.='<input type="hidden" name="'.
 3303: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3304: 	    $result.='<input type="text" name="'.
 3305: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3306: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3307: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3308: 	} elsif ($type eq 'solved') {
 3309: 	    my ($status,$foo)=split(/_/,$score,2);
 3310: 	    $status = 'nothing' if ($status eq '');
 3311: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3312: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3313: 	    $result.='&nbsp;<select name="'.
 3314: 		'GD_'.$student.'_'.$part.'_solved" '.
 3315: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3316: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
 3317: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
 3318: 	    $result.='<option>reset status</option>';
 3319: 	    $result.="</select>&nbsp;</td>\n";
 3320: 	} else {
 3321: 	    $result.='<input type="hidden" name="'.
 3322: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3323: 		    "\n";
 3324: 	    $result.='<input type="text" name="'.
 3325: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3326: 		'value="'.$score.'" size="4" /></td>'."\n";
 3327: 	}
 3328:     }
 3329:     $result.='</tr>';
 3330:     return $result;
 3331: }
 3332: 
 3333: #--- change scores for all the students in a section/class
 3334: #    record does not get update if unchanged
 3335: sub editgrades {
 3336:     my ($request) = @_;
 3337: 
 3338:     my $symb=&get_symb($request);
 3339:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3340:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
 3341:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
 3342:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3343: 
 3344:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
 3345:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
 3346: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
 3347: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
 3348: 
 3349:     my %scoreptr = (
 3350: 		    'correct'  =>'correct_by_override',
 3351: 		    'incorrect'=>'incorrect_by_override',
 3352: 		    'excused'  =>'excused',
 3353: 		    'ungraded' =>'ungraded_attempted',
 3354: 		    'nothing'  => '',
 3355: 		    );
 3356:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3357: 
 3358:     my (@partid);
 3359:     my %weight = ();
 3360:     my %columns = ();
 3361:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3362: 
 3363:     my (@parts) = sort(&getpartlist($symb));
 3364:     my $header;
 3365:     while ($ctr < $env{'form.totalparts'}) {
 3366: 	my $partid = $env{'form.partid_'.$ctr};
 3367: 	push @partid,$partid;
 3368: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3369: 	$ctr++;
 3370:     }
 3371:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3372:     foreach my $partid (@partid) {
 3373: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
 3374: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
 3375: 	$columns{$partid}=2;
 3376: 	foreach my $stores (@parts) {
 3377: 	    my ($part,$type) = &split_part_type($stores);
 3378: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3379: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3380: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3381: 	    $display =~ s/\[Part: (\w)+\]//;
 3382: 	    $display =~ s/Number of Attempts/Tries/;
 3383: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
 3384: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
 3385: 	    $columns{$partid}+=2;
 3386: 	}
 3387:     }
 3388:     foreach my $partid (@partid) {
 3389: 	my $display_part=&get_display_part($partid,$symb);
 3390: 	$result .= '<td colspan="'.$columns{$partid}.
 3391: 	    '" align="center"><b>Part:</b> '.$display_part.
 3392: 	    ' (Weight = '.$weight{$partid}.')</td>';
 3393: 
 3394:     }
 3395:     $result .= '</tr><tr bgcolor="#deffff">';
 3396:     $result .= $header;
 3397:     $result .= '</tr>'."\n";
 3398:     my $noupdate;
 3399:     my ($updateCtr,$noupdateCtr) = (1,1);
 3400:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3401: 	my $line;
 3402: 	my $user = $env{'form.ctr'.$i};
 3403: 	my ($uname,$udom)=split(/:/,$user);
 3404: 	my %newrecord;
 3405: 	my $updateflag = 0;
 3406: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3407: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3408: 	if (!&canmodify($usec)) {
 3409: 	    my $numcols=scalar(@partid)*4+2;
 3410: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
 3411: 	    next;
 3412: 	}
 3413:         my %aggregate = ();
 3414:         my $aggregateflag = 0;
 3415: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3416: 	foreach (@partid) {
 3417: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3418: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3419: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3420: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3421: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3422: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3423: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3424: 	    my $score;
 3425: 	    if ($partial eq '') {
 3426: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3427: 	    } elsif ($partial > 0) {
 3428: 		$score = 'correct_by_override';
 3429: 	    } elsif ($partial == 0) {
 3430: 		$score = 'incorrect_by_override';
 3431: 	    }
 3432: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3433: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3434: 
 3435: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3436: 		"$env{'user.name'}:$env{'user.domain'}";
 3437: 	    if ($dropMenu eq 'reset status' &&
 3438: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3439: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3440: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3441: 		$newrecord{'resource.'.$_.'.award'} = '';
 3442: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3443: 		$updateflag = 1;
 3444:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3445:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3446:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3447:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3448:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3449:                     $aggregateflag = 1;
 3450:                 }
 3451: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3452: 		$updateflag = 1;
 3453: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3454: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3455: 		$rec_update++;
 3456: 	    }
 3457: 
 3458: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3459: 		'<td align="center">'.$awarded.
 3460: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3461: 
 3462: 
 3463: 	    my $partid=$_;
 3464: 	    foreach my $stores (@parts) {
 3465: 		my ($part,$type) = &split_part_type($stores);
 3466: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3467: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3468: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3469: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3470: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3471: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3472: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3473: 		    $updateflag=1;
 3474: 		}
 3475: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3476: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3477: 	    }
 3478: 	}
 3479: 	$line.='</tr>'."\n";
 3480: 
 3481: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3482: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3483: 
 3484: 	if ($updateflag) {
 3485: 	    $count++;
 3486: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3487: 				    $udom,$uname);
 3488: 
 3489: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3490: 					      $cnum,$udom,$uname)) {
 3491: 		# need to figure out if should be in queue.
 3492: 		my %record =  
 3493: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3494: 					     $udom,$uname);
 3495: 		my $all_graded = 1;
 3496: 		my $none_graded = 1;
 3497: 		foreach my $part (@parts) {
 3498: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3499: 			$all_graded = 0;
 3500: 		    } else {
 3501: 			$none_graded = 0;
 3502: 		    }
 3503: 		}
 3504: 
 3505: 		if ($all_graded || $none_graded) {
 3506: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3507: 							   $symb,$cdom,$cnum,
 3508: 							   $udom,$uname);
 3509: 		}
 3510: 	    }
 3511: 
 3512: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
 3513: 	    $updateCtr++;
 3514: 	} else {
 3515: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
 3516: 	    $noupdateCtr++;
 3517: 	}
 3518:         if ($aggregateflag) {
 3519:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3520: 				  $cdom,$cnum);
 3521:         }
 3522:     }
 3523:     if ($noupdate) {
 3524: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3525: 	my $numcols=scalar(@partid)*4+2;
 3526: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
 3527:     }
 3528:     $result .= '</table></td></tr></table>'."\n".
 3529: 	&show_grading_menu_form ($symb);
 3530:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
 3531: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
 3532: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
 3533:     return $title.$msg.$result;
 3534: }
 3535: 
 3536: sub split_part_type {
 3537:     my ($partstr) = @_;
 3538:     my ($temp,@allparts)=split(/_/,$partstr);
 3539:     my $type=pop(@allparts);
 3540:     my $part=join('_',@allparts);
 3541:     return ($part,$type);
 3542: }
 3543: 
 3544: #------------- end of section for handling grading by section/class ---------
 3545: #
 3546: #----------------------------------------------------------------------------
 3547: 
 3548: 
 3549: #----------------------------------------------------------------------------
 3550: #
 3551: #-------------------------- Next few routines handles grading by csv upload
 3552: #
 3553: #--- Javascript to handle csv upload
 3554: sub csvupload_javascript_reverse_associate {
 3555:     my $error1=&mt('You need to specify the username or ID');
 3556:     my $error2=&mt('You need to specify at least one grading field');
 3557:   return(<<ENDPICK);
 3558:   function verify(vf) {
 3559:     var foundsomething=0;
 3560:     var founduname=0;
 3561:     var foundID=0;
 3562:     for (i=0;i<=vf.nfields.value;i++) {
 3563:       tw=eval('vf.f'+i+'.selectedIndex');
 3564:       if (i==0 && tw!=0) { foundID=1; }
 3565:       if (i==1 && tw!=0) { founduname=1; }
 3566:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3567:     }
 3568:     if (founduname==0 && foundID==0) {
 3569: 	alert('$error1');
 3570: 	return;
 3571:     }
 3572:     if (foundsomething==0) {
 3573: 	alert('$error2');
 3574: 	return;
 3575:     }
 3576:     vf.submit();
 3577:   }
 3578:   function flip(vf,tf) {
 3579:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3580:     var i;
 3581:     for (i=0;i<=vf.nfields.value;i++) {
 3582:       //can not pick the same destination field for both name and domain
 3583:       if (((i ==0)||(i ==1)) && 
 3584:           ((tf==0)||(tf==1)) && 
 3585:           (i!=tf) &&
 3586:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3587:         eval('vf.f'+i+'.selectedIndex=0;')
 3588:       }
 3589:     }
 3590:   }
 3591: ENDPICK
 3592: }
 3593: 
 3594: sub csvupload_javascript_forward_associate {
 3595:     my $error1=&mt('You need to specify the username or ID');
 3596:     my $error2=&mt('You need to specify at least one grading field');
 3597:   return(<<ENDPICK);
 3598:   function verify(vf) {
 3599:     var foundsomething=0;
 3600:     var founduname=0;
 3601:     var foundID=0;
 3602:     for (i=0;i<=vf.nfields.value;i++) {
 3603:       tw=eval('vf.f'+i+'.selectedIndex');
 3604:       if (tw==1) { foundID=1; }
 3605:       if (tw==2) { founduname=1; }
 3606:       if (tw>3) { foundsomething=1; }
 3607:     }
 3608:     if (founduname==0 && foundID==0) {
 3609: 	alert('$error1');
 3610: 	return;
 3611:     }
 3612:     if (foundsomething==0) {
 3613: 	alert('$error2');
 3614: 	return;
 3615:     }
 3616:     vf.submit();
 3617:   }
 3618:   function flip(vf,tf) {
 3619:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3620:     var i;
 3621:     //can not pick the same destination field twice
 3622:     for (i=0;i<=vf.nfields.value;i++) {
 3623:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3624:         eval('vf.f'+i+'.selectedIndex=0;')
 3625:       }
 3626:     }
 3627:   }
 3628: ENDPICK
 3629: }
 3630: 
 3631: sub csvuploadmap_header {
 3632:     my ($request,$symb,$datatoken,$distotal)= @_;
 3633:     my $javascript;
 3634:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3635: 	$javascript=&csvupload_javascript_reverse_associate();
 3636:     } else {
 3637: 	$javascript=&csvupload_javascript_forward_associate();
 3638:     }
 3639: 
 3640:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3641:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3642:     my $ignore=&mt('Ignore First Line');
 3643:     $symb = &Apache::lonenc::check_encrypt($symb);
 3644:     $request->print(<<ENDPICK);
 3645: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3646: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3647: $result
 3648: <hr />
 3649: <h3>Identify fields</h3>
 3650: Total number of records found in file: $distotal <hr />
 3651: Enter as many fields as you can. The system will inform you and bring you back
 3652: to this page if the data selected is insufficient to run your class.<hr />
 3653: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3654: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3655: <input type="hidden" name="associate"  value="" />
 3656: <input type="hidden" name="phase"      value="three" />
 3657: <input type="hidden" name="datatoken"  value="$datatoken" />
 3658: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3659: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3660: <input type="hidden" name="upfile_associate" 
 3661:                                        value="$env{'form.upfile_associate'}" />
 3662: <input type="hidden" name="symb"       value="$symb" />
 3663: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3664: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3665: <input type="hidden" name="command"    value="csvuploadoptions" />
 3666: <hr />
 3667: <script type="text/javascript" language="Javascript">
 3668: $javascript
 3669: </script>
 3670: ENDPICK
 3671:     return '';
 3672: 
 3673: }
 3674: 
 3675: sub csvupload_fields {
 3676:     my ($symb) = @_;
 3677:     my (@parts) = &getpartlist($symb);
 3678:     my @fields=(['ID','Student ID'],
 3679: 		['username','Student Username'],
 3680: 		['domain','Student Domain']);
 3681:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3682:     foreach my $part (sort(@parts)) {
 3683: 	my @datum;
 3684: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3685: 	my $name=$part;
 3686: 	if  (!$display) { $display = $name; }
 3687: 	@datum=($name,$display);
 3688: 	if ($name=~/^stores_(.*)_awarded/) {
 3689: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3690: 	}
 3691: 	push(@fields,\@datum);
 3692:     }
 3693:     return (@fields);
 3694: }
 3695: 
 3696: sub csvuploadmap_footer {
 3697:     my ($request,$i,$keyfields) =@_;
 3698:     $request->print(<<ENDPICK);
 3699: </table>
 3700: <input type="hidden" name="nfields" value="$i" />
 3701: <input type="hidden" name="keyfields" value="$keyfields" />
 3702: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3703: </form>
 3704: ENDPICK
 3705: }
 3706: 
 3707: sub checkforfile_js {
 3708:     my $result =<<CSVFORMJS;
 3709: <script type="text/javascript" language="javascript">
 3710:     function checkUpload(formname) {
 3711: 	if (formname.upfile.value == "") {
 3712: 	    alert("Please use the browse button to select a file from your local directory.");
 3713: 	    return false;
 3714: 	}
 3715: 	formname.submit();
 3716:     }
 3717:     </script>
 3718: CSVFORMJS
 3719:     return $result;
 3720: }
 3721: 
 3722: sub upcsvScores_form {
 3723:     my ($request) = shift;
 3724:     my ($symb)=&get_symb($request);
 3725:     if (!$symb) {return '';}
 3726:     my $result=&checkforfile_js();
 3727:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3728:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3729:     $result.=$table;
 3730:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3731:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3732:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3733: 	'.</b></td></tr>'."\n";
 3734:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3735:     my $upload=&mt("Upload Scores");
 3736:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3737:     my $ignore=&mt('Ignore First Line');
 3738:     $symb = &Apache::lonenc::check_encrypt($symb);
 3739:     $result.=<<ENDUPFORM;
 3740: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3741: <input type="hidden" name="symb" value="$symb" />
 3742: <input type="hidden" name="command" value="csvuploadmap" />
 3743: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3744: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3745: $upfile_select
 3746: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3747: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3748: </form>
 3749: ENDUPFORM
 3750:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3751:                            &mt("How do I create a CSV file from a spreadsheet"))
 3752:     .'</td></tr></table>'."\n";
 3753:     $result.='</td></tr></table><br /><br />'."\n";
 3754:     $result.=&show_grading_menu_form($symb);
 3755:     return $result;
 3756: }
 3757: 
 3758: 
 3759: sub csvuploadmap {
 3760:     my ($request)= @_;
 3761:     my ($symb)=&get_symb($request);
 3762:     if (!$symb) {return '';}
 3763: 
 3764:     my $datatoken;
 3765:     if (!$env{'form.datatoken'}) {
 3766: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3767:     } else {
 3768: 	$datatoken=$env{'form.datatoken'};
 3769: 	&Apache::loncommon::load_tmp_file($request);
 3770:     }
 3771:     my @records=&Apache::loncommon::upfile_record_sep();
 3772:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3773:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3774:     my ($i,$keyfields);
 3775:     if (@records) {
 3776: 	my @fields=&csvupload_fields($symb);
 3777: 
 3778: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3779: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3780: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3781: 							  \@fields);
 3782: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3783: 	    chop($keyfields);
 3784: 	} else {
 3785: 	    unshift(@fields,['none','']);
 3786: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3787: 							    \@fields);
 3788:             foreach my $rec (@records) {
 3789:                 my %temp = &Apache::loncommon::record_sep($rec);
 3790:                 if (%temp) {
 3791:                     $keyfields=join(',',sort(keys(%temp)));
 3792:                     last;
 3793:                 }
 3794:             }
 3795: 	}
 3796:     }
 3797:     &csvuploadmap_footer($request,$i,$keyfields);
 3798:     $request->print(&show_grading_menu_form($symb));
 3799: 
 3800:     return '';
 3801: }
 3802: 
 3803: sub csvuploadoptions {
 3804:     my ($request)= @_;
 3805:     my ($symb)=&get_symb($request);
 3806:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3807:     my $ignore=&mt('Ignore First Line');
 3808:     $request->print(<<ENDPICK);
 3809: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3810: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3811: <input type="hidden" name="command"    value="csvuploadassign" />
 3812: <!--
 3813: <p>
 3814: <label>
 3815:    <input type="checkbox" name="show_full_results" />
 3816:    Show a table of all changes
 3817: </label>
 3818: </p>
 3819: -->
 3820: <p>
 3821: <label>
 3822:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3823:    Overwrite any existing score
 3824: </label>
 3825: </p>
 3826: ENDPICK
 3827:     my %fields=&get_fields();
 3828:     if (!defined($fields{'domain'})) {
 3829: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3830: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3831:     }
 3832:     foreach my $key (sort(keys(%env))) {
 3833: 	if ($key !~ /^form\.(.*)$/) { next; }
 3834: 	my $cleankey=$1;
 3835: 	if ($cleankey eq 'command') { next; }
 3836: 	$request->print('<input type="hidden" name="'.$cleankey.
 3837: 			'"  value="'.$env{$key}.'" />'."\n");
 3838:     }
 3839:     # FIXME do a check for any duplicated user ids...
 3840:     # FIXME do a check for any invalid user ids?...
 3841:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3842: <hr /></form>'."\n");
 3843:     $request->print(&show_grading_menu_form($symb));
 3844:     return '';
 3845: }
 3846: 
 3847: sub get_fields {
 3848:     my %fields;
 3849:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3850:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3851: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3852: 	    if ($env{'form.f'.$i} ne 'none') {
 3853: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3854: 	    }
 3855: 	} else {
 3856: 	    if ($env{'form.f'.$i} ne 'none') {
 3857: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3858: 	    }
 3859: 	}
 3860:     }
 3861:     return %fields;
 3862: }
 3863: 
 3864: sub csvuploadassign {
 3865:     my ($request)= @_;
 3866:     my ($symb)=&get_symb($request);
 3867:     if (!$symb) {return '';}
 3868:     my $error_msg = '';
 3869:     &Apache::loncommon::load_tmp_file($request);
 3870:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3871:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3872:     my %fields=&get_fields();
 3873:     $request->print('<h3>Assigning Grades</h3>');
 3874:     my $courseid=$env{'request.course.id'};
 3875:     my ($classlist) = &getclasslist('all',0);
 3876:     my @notallowed;
 3877:     my @skipped;
 3878:     my $countdone=0;
 3879:     foreach my $grade (@gradedata) {
 3880: 	my %entries=&Apache::loncommon::record_sep($grade);
 3881: 	my $domain;
 3882: 	if ($entries{$fields{'domain'}}) {
 3883: 	    $domain=$entries{$fields{'domain'}};
 3884: 	} else {
 3885: 	    $domain=$env{'form.default_domain'};
 3886: 	}
 3887: 	$domain=~s/\s//g;
 3888: 	my $username=$entries{$fields{'username'}};
 3889: 	$username=~s/\s//g;
 3890: 	if (!$username) {
 3891: 	    my $id=$entries{$fields{'ID'}};
 3892: 	    $id=~s/\s//g;
 3893: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3894: 	    $username=$ids{$id};
 3895: 	}
 3896: 	if (!exists($$classlist{"$username:$domain"})) {
 3897: 	    my $id=$entries{$fields{'ID'}};
 3898: 	    $id=~s/\s//g;
 3899: 	    if ($id) {
 3900: 		push(@skipped,"$id:$domain");
 3901: 	    } else {
 3902: 		push(@skipped,"$username:$domain");
 3903: 	    }
 3904: 	    next;
 3905: 	}
 3906: 	my $usec=$classlist->{"$username:$domain"}[5];
 3907: 	if (!&canmodify($usec)) {
 3908: 	    push(@notallowed,"$username:$domain");
 3909: 	    next;
 3910: 	}
 3911: 	my %points;
 3912: 	my %grades;
 3913: 	foreach my $dest (keys(%fields)) {
 3914: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 3915: 		$dest eq 'domain') { next; }
 3916: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 3917: 	    if ($dest=~/stores_(.*)_points/) {
 3918: 		my $part=$1;
 3919: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 3920: 					      $symb,$domain,$username);
 3921:                 if ($wgt) {
 3922:                     $entries{$fields{$dest}}=~s/\s//g;
 3923:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 3924:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 3925:                                           : 'correct_by_override';
 3926:                     $grades{"resource.$part.awarded"}=$pcr;
 3927:                     $grades{"resource.$part.solved"}=$award;
 3928:                     $points{$part}=1;
 3929:                 } else {
 3930:                     $error_msg = "<br />" .
 3931:                         &mt("Some point values were assigned"
 3932:                             ." for problems with a weight "
 3933:                             ."of zero. These values were "
 3934:                             ."ignored.");
 3935:                 }
 3936: 	    } else {
 3937: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 3938: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 3939: 		my $store_key=$dest;
 3940: 		$store_key=~s/^stores/resource/;
 3941: 		$store_key=~s/_/\./g;
 3942: 		$grades{$store_key}=$entries{$fields{$dest}};
 3943: 	    }
 3944: 	}
 3945: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
 3946: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 3947: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
 3948: 					   $env{'request.course.id'},
 3949: 					   $domain,$username);
 3950: 	if ($result eq 'ok') {
 3951: 	    $request->print('.');
 3952: 	} else {
 3953: 	    $request->print("<p>
 3954:                               <span class=\"LC_error\">
 3955:                                  Failed to save student $username:$domain.
 3956:                                  Message when trying to save was ($result)
 3957:                               </span>
 3958:                              </p>" );
 3959: 	}
 3960: 	$request->rflush();
 3961: 	$countdone++;
 3962:     }
 3963:     $request->print("<br />Saved $countdone students\n");
 3964:     if (@skipped) {
 3965: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
 3966: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 3967:     }
 3968:     if (@notallowed) {
 3969: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
 3970: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 3971:     }
 3972:     $request->print("<br />\n");
 3973:     $request->print(&show_grading_menu_form($symb));
 3974:     return $error_msg;
 3975: }
 3976: #------------- end of section for handling csv file upload ---------
 3977: #
 3978: #-------------------------------------------------------------------
 3979: #
 3980: #-------------- Next few routines handle grading by page/sequence
 3981: #
 3982: #--- Select a page/sequence and a student to grade
 3983: sub pickStudentPage {
 3984:     my ($request) = shift;
 3985: 
 3986:     $request->print(<<LISTJAVASCRIPT);
 3987: <script type="text/javascript" language="javascript">
 3988: 
 3989: function checkPickOne(formname) {
 3990:     if (radioSelection(formname.student) == null) {
 3991: 	alert("Please select the student you wish to grade.");
 3992: 	return;
 3993:     }
 3994:     ptr = pullDownSelection(formname.selectpage);
 3995:     formname.page.value = formname["page"+ptr].value;
 3996:     formname.title.value = formname["title"+ptr].value;
 3997:     formname.submit();
 3998: }
 3999: 
 4000: </script>
 4001: LISTJAVASCRIPT
 4002:     &commonJSfunctions($request);
 4003:     my ($symb) = &get_symb($request);
 4004:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4005:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4006:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4007: 
 4008:     my $result='<h3><span class="LC_info">&nbsp;'.
 4009: 	'Manual Grading by Page or Sequence</span></h3>';
 4010: 
 4011:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4012:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
 4013:     my ($titles,$symbx) = &getSymbMap();
 4014:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4015: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4016: #    my $type=($curpage =~ /\.(page|sequence)/);
 4017:     my $ctr=0;
 4018:     foreach (@$titles) {
 4019: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4020: 	$result.='<option value="'.$ctr.'" '.
 4021: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4022: 	    '>'.$showtitle.'</option>'."\n";
 4023: 	$ctr++;
 4024:     }
 4025:     $result.= '</select>'."<br />\n";
 4026:     $ctr=0;
 4027:     foreach (@$titles) {
 4028: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4029: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4030: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4031: 	$ctr++;
 4032:     }
 4033:     $result.='<input type="hidden" name="page" />'."\n".
 4034: 	'<input type="hidden" name="title" />'."\n";
 4035: 
 4036:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
 4037: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
 4038: 
 4039:     $result.='&nbsp;<b>Submission Details: </b>'.
 4040: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
 4041: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
 4042: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
 4043:     
 4044:     $result.=&build_section_inputs();
 4045:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4046:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4047: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4048: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4049: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4050: 
 4051:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
 4052: 	'<input type="text" name="CODE" value="" /><br />'."\n";
 4053: 
 4054:     $result.='&nbsp;<input type="button" '.
 4055: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
 4056: 
 4057:     $request->print($result);
 4058: 
 4059:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
 4060: 	'<table border="0"><tr><td bgcolor="#777777">'.
 4061: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4062: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 4063: 	'<td>'.&nameUserString('header').'</td>'.
 4064: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 4065: 	'<td>'.&nameUserString('header').'</td></tr>';
 4066:  
 4067:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4068:     my $ptr = 1;
 4069:     foreach my $student (sort 
 4070: 			 {
 4071: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4072: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4073: 			     }
 4074: 			     return $a cmp $b;
 4075: 			 } (keys(%$fullname))) {
 4076: 	my ($uname,$udom) = split(/:/,$student);
 4077: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
 4078: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4079: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4080: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4081: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
 4082: 	$ptr++;
 4083:     }
 4084:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
 4085:     $studentTable.='</table></td></tr></table>'."\n";
 4086:     $studentTable.='<input type="button" '.
 4087: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
 4088: 
 4089:     $studentTable.=&show_grading_menu_form($symb);
 4090:     $request->print($studentTable);
 4091: 
 4092:     return '';
 4093: }
 4094: 
 4095: sub getSymbMap {
 4096:     my $navmap = Apache::lonnavmaps::navmap->new();
 4097: 
 4098:     my %symbx = ();
 4099:     my @titles = ();
 4100:     my $minder = 0;
 4101: 
 4102:     # Gather every sequence that has problems.
 4103:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4104: 					       1,0,1);
 4105:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4106: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4107: 	    my $title = $minder.'.'.
 4108: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4109: 	    push(@titles, $title); # minder in case two titles are identical
 4110: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4111: 	    $minder++;
 4112: 	}
 4113:     }
 4114:     return \@titles,\%symbx;
 4115: }
 4116: 
 4117: #
 4118: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4119: sub displayPage {
 4120:     my ($request) = shift;
 4121: 
 4122:     my ($symb) = &get_symb($request);
 4123:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4124:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4125:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4126:     my $pageTitle = $env{'form.page'};
 4127:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4128:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4129:     my $usec=$classlist->{$env{'form.student'}}[5];
 4130: 
 4131:     #need to make sure we have the correct data for later EXT calls, 
 4132:     #thus invalidate the cache
 4133:     &Apache::lonnet::devalidatecourseresdata(
 4134:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4135:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4136:     &Apache::lonnet::clear_EXT_cache_status();
 4137: 
 4138:     if (!&canview($usec)) {
 4139: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
 4140: 	$request->print(&show_grading_menu_form($symb));
 4141: 	return;
 4142:     }
 4143:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4144:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
 4145: 	'</h3>'."\n";
 4146:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4147: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
 4148:     } else {
 4149: 	delete($env{'form.CODE'});
 4150:     }
 4151:     &sub_page_js($request);
 4152:     $request->print($result);
 4153: 
 4154:     my $navmap = Apache::lonnavmaps::navmap->new();
 4155:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4156:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4157:     if (!$map) {
 4158: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
 4159: 	$request->print(&show_grading_menu_form($symb));
 4160: 	return; 
 4161:     }
 4162:     my $iterator = $navmap->getIterator($map->map_start(),
 4163: 					$map->map_finish());
 4164: 
 4165:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4166: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4167: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4168: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4169: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4170: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4171: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4172: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4173: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4174: 
 4175:     if (defined($env{'form.CODE'})) {
 4176: 	$studentTable.=
 4177: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4178:     }
 4179:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4180: 	'" src="'.$request->dir_config('lonIconsURL').
 4181: 	'/check.gif" height="16" border="0" />';
 4182: 
 4183:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
 4184: 	' symbol.'."\n".
 4185: 	'<table border="0"><tr><td bgcolor="#777777">'.
 4186: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4187: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 4188: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
 4189: 
 4190:     &Apache::lonxml::clear_problem_counter();
 4191:     my ($depth,$question,$prob) = (1,1,1);
 4192:     $iterator->next(); # skip the first BEGIN_MAP
 4193:     my $curRes = $iterator->next(); # for "current resource"
 4194:     while ($depth > 0) {
 4195:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4196:         if($curRes == $iterator->END_MAP) { $depth--; }
 4197: 
 4198:         if (ref($curRes) && $curRes->is_problem()) {
 4199: 	    my $parts = $curRes->parts();
 4200:             my $title = $curRes->compTitle();
 4201: 	    my $symbx = $curRes->symb();
 4202: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 4203: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 4204: 	    $studentTable.='<td valign="top">';
 4205: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4206: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4207: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4208: 					     undef,'both',\%form);
 4209: 	    } else {
 4210: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4211: 		$companswer =~ s|<form(.*?)>||g;
 4212: 		$companswer =~ s|</form>||g;
 4213: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4214: #		    $companswer =~ s/$1/ /ms;
 4215: #		    $request->print('match='.$1."<br />\n");
 4216: #		}
 4217: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4218: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
 4219: 	    }
 4220: 
 4221: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4222: 
 4223: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4224: 		if ($record{'version'} eq '') {
 4225: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
 4226: 		} else {
 4227: 		    my %responseType = ();
 4228: 		    foreach my $partid (@{$parts}) {
 4229: 			my @responseIds =$curRes->responseIds($partid);
 4230: 			my @responseType =$curRes->responseType($partid);
 4231: 			my %responseIds;
 4232: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4233: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4234: 			}
 4235: 			$responseType{$partid} = \%responseIds;
 4236: 		    }
 4237: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4238: 
 4239: 		}
 4240: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4241: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4242: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4243: 									$env{'request.course.id'},
 4244: 									'','.submission');
 4245:  
 4246: 	    }
 4247: 	    if (&canmodify($usec)) {
 4248: 		foreach my $partid (@{$parts}) {
 4249: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4250: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4251: 		    $question++;
 4252: 		}
 4253: 		$prob++;
 4254: 	    }
 4255: 	    $studentTable.='</td></tr>';
 4256: 
 4257: 	}
 4258:         $curRes = $iterator->next();
 4259:     }
 4260: 
 4261:     $studentTable.='</table></td></tr></table>'."\n".
 4262: 	'<input type="button" value="Save" '.
 4263: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4264: 	'</form>'."\n";
 4265:     $studentTable.=&show_grading_menu_form($symb);
 4266:     $request->print($studentTable);
 4267: 
 4268:     return '';
 4269: }
 4270: 
 4271: sub displaySubByDates {
 4272:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4273:     my $isCODE=0;
 4274:     my $isTask = ($symb =~/\.task$/);
 4275:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4276:     my $studentTable=&Apache::loncommon::start_data_table().
 4277: 	&Apache::loncommon::start_data_table_header_row().
 4278: 	'<th>'.&mt('Date/Time').'</th>'.
 4279: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4280: 	'<th>'.&mt('Submission').'</th>'.
 4281: 	'<th>'.&mt('Status').'</th>'.
 4282: 	&Apache::loncommon::end_data_table_header_row();
 4283:     my ($version);
 4284:     my %mark;
 4285:     my %orders;
 4286:     $mark{'correct_by_student'} = $checkIcon;
 4287:     if (!exists($$record{'1:timestamp'})) {
 4288: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
 4289:     }
 4290: 
 4291:     my $interaction;
 4292:     for ($version=1;$version<=$$record{'version'};$version++) {
 4293: 	my $timestamp = 
 4294: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4295: 	if (exists($$record{$version.':resource.0.version'})) {
 4296: 	    $interaction = $$record{$version.':resource.0.version'};
 4297: 	}
 4298: 
 4299: 	my $where = ($isTask ? "$version:resource.$interaction"
 4300: 		             : "$version:resource");
 4301: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4302: 	    '<td>'.$timestamp.'</td>';
 4303: 	if ($isCODE) {
 4304: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4305: 	}
 4306: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4307: 	my @displaySub = ();
 4308: 	foreach my $partid (@{$parts}) {
 4309: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4310: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4311: 	    
 4312: 
 4313: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4314: 	    my $display_part=&get_display_part($partid,$symb);
 4315: 	    foreach my $matchKey (@matchKey) {
 4316: 		if (exists($$record{$version.':'.$matchKey}) &&
 4317: 		    $$record{$version.':'.$matchKey} ne '') {
 4318: 
 4319: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4320: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4321: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4322: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4323: 			$responseId.')</span>&nbsp;<b>';
 4324: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4325: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4326: 		    } else {
 4327: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4328: 					    $$record{"$where.$partid.tries"});
 4329: 		    }
 4330: 		    my $responseType=($isTask ? 'Task'
 4331:                                               : $responseType->{$partid}->{$responseId});
 4332: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4333: 		    if (!exists($orders{$partid}->{$responseId})) {
 4334: 			$orders{$partid}->{$responseId}=
 4335: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
 4336: 		    }
 4337: 		    $displaySub[0].='</b>&nbsp; '.
 4338: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4339: 		}
 4340: 	    }
 4341: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4342: 		$displaySub[1].='Checked in by '.
 4343: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
 4344: 		    $$record{"$where.$partid.checkedin.slot"}.
 4345: 		    '<br />';
 4346: 	    }
 4347: 	    if (exists $$record{"$where.$partid.award"}) {
 4348: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
 4349: 		    lc($$record{"$where.$partid.award"}).' '.
 4350: 		    $mark{$$record{"$where.$partid.solved"}}.
 4351: 		    '<br />';
 4352: 	    }
 4353: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4354: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4355: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4356: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4357: 		$displaySub[2].=
 4358: 		    $$record{"$version:resource.$partid.regrader"}.
 4359: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4360: 	    }
 4361: 	}
 4362: 	# needed because old essay regrader has not parts info
 4363: 	if (exists $$record{"$version:resource.regrader"}) {
 4364: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4365: 	}
 4366: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4367: 	if ($displaySub[2]) {
 4368: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4369: 	}
 4370: 	$studentTable.='&nbsp;</td>'.
 4371: 	    &Apache::loncommon::end_data_table_row();
 4372:     }
 4373:     $studentTable.=&Apache::loncommon::end_data_table();
 4374:     return $studentTable;
 4375: }
 4376: 
 4377: sub updateGradeByPage {
 4378:     my ($request) = shift;
 4379: 
 4380:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4381:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4382:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4383:     my $pageTitle = $env{'form.page'};
 4384:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4385:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4386:     my $usec=$classlist->{$env{'form.student'}}[5];
 4387:     if (!&canmodify($usec)) {
 4388: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
 4389: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4390: 	return;
 4391:     }
 4392:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4393:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4394: 	'</h3>'."\n";
 4395: 
 4396:     $request->print($result);
 4397: 
 4398:     my $navmap = Apache::lonnavmaps::navmap->new();
 4399:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4400:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4401:     if (!$map) {
 4402: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
 4403: 	my ($symb)=&get_symb($request);
 4404: 	$request->print(&show_grading_menu_form($symb));
 4405: 	return; 
 4406:     }
 4407:     my $iterator = $navmap->getIterator($map->map_start(),
 4408: 					$map->map_finish());
 4409: 
 4410:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
 4411: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4412: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 4413: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
 4414: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
 4415: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
 4416: 
 4417:     $iterator->next(); # skip the first BEGIN_MAP
 4418:     my $curRes = $iterator->next(); # for "current resource"
 4419:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4420:     while ($depth > 0) {
 4421:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4422:         if($curRes == $iterator->END_MAP) { $depth--; }
 4423: 
 4424:         if (ref($curRes) && $curRes->is_problem()) {
 4425: 	    my $parts = $curRes->parts();
 4426:             my $title = $curRes->compTitle();
 4427: 	    my $symbx = $curRes->symb();
 4428: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 4429: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 4430: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4431: 
 4432: 	    my %newrecord=();
 4433: 	    my @displayPts=();
 4434:             my %aggregate = ();
 4435:             my $aggregateflag = 0;
 4436: 	    foreach my $partid (@{$parts}) {
 4437: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4438: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4439: 
 4440: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4441: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4442: 		my $partial = $newpts/$wgt;
 4443: 		my $score;
 4444: 		if ($partial > 0) {
 4445: 		    $score = 'correct_by_override';
 4446: 		} elsif ($newpts ne '') { #empty is taken as 0
 4447: 		    $score = 'incorrect_by_override';
 4448: 		}
 4449: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4450: 		if ($dropMenu eq 'excused') {
 4451: 		    $partial = '';
 4452: 		    $score = 'excused';
 4453: 		} elsif ($dropMenu eq 'reset status'
 4454: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4455: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4456: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4457: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4458: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4459: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4460: 		    $changeflag++;
 4461: 		    $newpts = '';
 4462:                     
 4463:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4464:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4465:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4466:                     if ($aggtries > 0) {
 4467:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4468:                         $aggregateflag = 1;
 4469:                     }
 4470: 		}
 4471: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4472: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4473: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4474: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4475: 		    '&nbsp;<br />';
 4476: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4477: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4478: 		    '&nbsp;<br />';
 4479: 		$question++;
 4480: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4481: 
 4482: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4483: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4484: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4485: 		    if (scalar(keys(%newrecord)) > 0);
 4486: 
 4487: 		$changeflag++;
 4488: 	    }
 4489: 	    if (scalar(keys(%newrecord)) > 0) {
 4490: 		my %record = 
 4491: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4492: 					     $udom,$uname);
 4493: 
 4494: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4495: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4496: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4497: 		    $newrecord{'resource.CODE'} = '';
 4498: 		}
 4499: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4500: 					$udom,$uname);
 4501: 		%record = &Apache::lonnet::restore($symbx,
 4502: 						   $env{'request.course.id'},
 4503: 						   $udom,$uname);
 4504: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4505: 					     $cdom,$cnum,$udom,$uname);
 4506: 	    }
 4507: 	    
 4508:             if ($aggregateflag) {
 4509:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4510:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4511:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4512:             }
 4513: 
 4514: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4515: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4516: 		'</tr>';
 4517: 
 4518: 	    $prob++;
 4519: 	}
 4520:         $curRes = $iterator->next();
 4521:     }
 4522: 
 4523:     $studentTable.='</td></tr></table></td></tr></table>';
 4524:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4525:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
 4526: 		  'The scores were changed for '.
 4527: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
 4528:     $request->print($grademsg.$studentTable);
 4529: 
 4530:     return '';
 4531: }
 4532: 
 4533: #-------- end of section for handling grading by page/sequence ---------
 4534: #
 4535: #-------------------------------------------------------------------
 4536: 
 4537: #--------------------Scantron Grading-----------------------------------
 4538: #
 4539: #------ start of section for handling grading by page/sequence ---------
 4540: 
 4541: =pod
 4542: 
 4543: =head1 Bubble sheet grading routines
 4544: 
 4545:   For this documentation:
 4546: 
 4547:    'scanline' refers to the full line of characters
 4548:    from the file that we are parsing that represents one entire sheet
 4549: 
 4550:    'bubble line' refers to the data
 4551:    representing the line of bubbles that are on the physical bubble sheet
 4552: 
 4553: 
 4554: The overall process is that a scanned in bubble sheet data is uploaded
 4555: into a course. When a user wants to grade, they select a
 4556: sequence/folder of resources, a file of bubble sheet info, and pick
 4557: one of the predefined configurations for what each scanline looks
 4558: like.
 4559: 
 4560: Next each scanline is checked for any errors of either 'missing
 4561: bubbles' (it's an error because it may have been mis-scanned
 4562: because too light bubbling), 'double bubble' (each bubble line should
 4563: have no more that one letter picked), invalid or duplicated CODE,
 4564: invalid student ID
 4565: 
 4566: If the CODE option is used that determines the randomization of the
 4567: homework problems, either way the student ID is looked up into a
 4568: username:domain.
 4569: 
 4570: During the validation phase the instructor can choose to skip scanlines. 
 4571: 
 4572: After the validation phase, there are now 3 bubble sheet files
 4573: 
 4574:   scantron_original_filename (unmodified original file)
 4575:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4576:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4577: 
 4578: Also there is a separate hash nohist_scantrondata that contains extra
 4579: correction information that isn't representable in the bubble sheet
 4580: file (see &scantron_getfile() for more information)
 4581: 
 4582: After all scanlines are either valid, marked as valid or skipped, then
 4583: foreach line foreach problem in the picked sequence, an ssi request is
 4584: made that simulates a user submitting their selected letter(s) against
 4585: the homework problem.
 4586: 
 4587: =over 4
 4588: 
 4589: 
 4590: 
 4591: =item defaultFormData
 4592: 
 4593:   Returns html hidden inputs used to hold context/default values.
 4594: 
 4595:  Arguments:
 4596:   $symb - $symb of the current resource 
 4597: 
 4598: =cut
 4599: 
 4600: sub defaultFormData {
 4601:     my ($symb)=@_;
 4602:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4603:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4604:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4605: }
 4606: 
 4607: 
 4608: =pod 
 4609: 
 4610: =item getSequenceDropDown
 4611: 
 4612:    Return html dropdown of possible sequences to grade
 4613:  
 4614:  Arguments:
 4615:    $symb - $symb of the current resource 
 4616: 
 4617: =cut
 4618: 
 4619: sub getSequenceDropDown {
 4620:     my ($symb)=@_;
 4621:     my $result='<select name="selectpage">'."\n";
 4622:     my ($titles,$symbx) = &getSymbMap();
 4623:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4624:     my $ctr=0;
 4625:     foreach (@$titles) {
 4626: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4627: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4628: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4629: 	    '>'.$showtitle.'</option>'."\n";
 4630: 	$ctr++;
 4631:     }
 4632:     $result.= '</select>';
 4633:     return $result;
 4634: }
 4635: 
 4636: 
 4637: =pod 
 4638: 
 4639: =item scantron_filenames
 4640: 
 4641:    Returns a list of the scantron files in the current course 
 4642: 
 4643: =cut
 4644: 
 4645: sub scantron_filenames {
 4646:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4647:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4648:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4649: 				    &propath($cdom,$cname));
 4650:     my @possiblenames;
 4651:     foreach my $filename (sort(@files)) {
 4652: 	($filename)=split(/&/,$filename);
 4653: 	if ($filename!~/^scantron_orig_/) { next ; }
 4654: 	$filename=~s/^scantron_orig_//;
 4655: 	push(@possiblenames,$filename);
 4656:     }
 4657:     return @possiblenames;
 4658: }
 4659: 
 4660: =pod 
 4661: 
 4662: =item scantron_uploads
 4663: 
 4664:    Returns  html drop-down list of scantron files in current course.
 4665: 
 4666:  Arguments:
 4667:    $file2grade - filename to set as selected in the dropdown
 4668: 
 4669: =cut
 4670: 
 4671: sub scantron_uploads {
 4672:     my ($file2grade) = @_;
 4673:     my $result=	'<select name="scantron_selectfile">';
 4674:     $result.="<option></option>";
 4675:     foreach my $filename (sort(&scantron_filenames())) {
 4676: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4677:     }
 4678:     $result.="</select>";
 4679:     return $result;
 4680: }
 4681: 
 4682: =pod 
 4683: 
 4684: =item scantron_scantab
 4685: 
 4686:   Returns html drop down of the scantron formats in the scantronformat.tab
 4687:   file.
 4688: 
 4689: =cut
 4690: 
 4691: sub scantron_scantab {
 4692:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4693:     my $result='<select name="scantron_format">'."\n";
 4694:     $result.='<option></option>'."\n";
 4695:     foreach my $line (<$fh>) {
 4696: 	my ($name,$descrip)=split(/:/,$line);
 4697: 	if ($name =~ /^\#/) { next; }
 4698: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4699:     }
 4700:     $result.='</select>'."\n";
 4701: 
 4702:     return $result;
 4703: }
 4704: 
 4705: =pod 
 4706: 
 4707: =item scantron_CODElist
 4708: 
 4709:   Returns html drop down of the saved CODE lists from current course,
 4710:   generated from earlier printings.
 4711: 
 4712: =cut
 4713: 
 4714: sub scantron_CODElist {
 4715:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4716:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4717:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4718:     my $namechoice='<option></option>';
 4719:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4720: 	if ($name =~ /^error: 2 /) { next; }
 4721: 	if ($name =~ /^type\0/) { next; }
 4722: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4723:     }
 4724:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4725:     return $namechoice;
 4726: }
 4727: 
 4728: =pod 
 4729: 
 4730: =item scantron_CODEunique
 4731: 
 4732:   Returns the html for "Each CODE to be used once" radio.
 4733: 
 4734: =cut
 4735: 
 4736: sub scantron_CODEunique {
 4737:     my $result='<span style="white-space: nowrap;">
 4738:                  <label><input type="radio" name="scantron_CODEunique"
 4739:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4740:                 </span>
 4741:                 <span style="white-space: nowrap;">
 4742:                  <label><input type="radio" name="scantron_CODEunique"
 4743:                         value="no" />'.&mt('No').' </label>
 4744:                 </span>';
 4745:     return $result;
 4746: }
 4747: 
 4748: =pod 
 4749: 
 4750: =item scantron_selectphase
 4751: 
 4752:   Generates the initial screen to start the bubble sheet process.
 4753:   Allows for - starting a grading run.
 4754:              - downloading existing scan data (original, corrected
 4755:                                                 or skipped info)
 4756: 
 4757:              - uploading new scan data
 4758: 
 4759:  Arguments:
 4760:   $r          - The Apache request object
 4761:   $file2grade - name of the file that contain the scanned data to score
 4762: 
 4763: =cut
 4764: 
 4765: sub scantron_selectphase {
 4766:     my ($r,$file2grade) = @_;
 4767:     my ($symb)=&get_symb($r);
 4768:     if (!$symb) {return '';}
 4769:     my $sequence_selector=&getSequenceDropDown($symb);
 4770:     my $default_form_data=&defaultFormData($symb);
 4771:     my $grading_menu_button=&show_grading_menu_form($symb);
 4772:     my $file_selector=&scantron_uploads($file2grade);
 4773:     my $format_selector=&scantron_scantab();
 4774:     my $CODE_selector=&scantron_CODElist();
 4775:     my $CODE_unique=&scantron_CODEunique();
 4776:     my $result;
 4777: 
 4778:     # Chunk of form to prompt for a file to grade and how:
 4779: 
 4780:     $result.= <<SCANTRONFORM;
 4781:     <table width="100%" border="0">
 4782:     <tr>
 4783:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 4784:       <td bgcolor="#777777">
 4785:        <input type="hidden" name="command" value="scantron_warning" />
 4786:         $default_form_data
 4787:         <table width="100%" border="0">
 4788:           <tr bgcolor="#e6ffff">
 4789:             <td colspan="2">
 4790:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
 4791:             </td>
 4792:           </tr>
 4793:           <tr bgcolor="#ffffe6">
 4794:             <td> Sequence to grade: </td><td> $sequence_selector </td>
 4795:           </tr>
 4796:           <tr bgcolor="#ffffe6">
 4797:             <td> Filename of scoring office file: </td><td> $file_selector </td>
 4798:           </tr>
 4799:           <tr bgcolor="#ffffe6">
 4800:             <td> Format of data file: </td><td> $format_selector </td>
 4801:           </tr>
 4802:           <tr bgcolor="#ffffe6">
 4803:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
 4804:           </tr>
 4805:           <tr bgcolor="#ffffe6">
 4806:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
 4807:           </tr>
 4808:           <tr bgcolor="#ffffe6">
 4809: 	    <td> Options: </td>
 4810:             <td>
 4811: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
 4812:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
 4813:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
 4814: 	    </td>
 4815:           </tr>
 4816:           <tr bgcolor="#ffffe6">
 4817:             <td colspan="2">
 4818:               <input type="submit" value="Grading: Validate Scantron Records" />
 4819:             </td>
 4820:           </tr>
 4821:         </table>
 4822:        </td>
 4823:      </form>
 4824:     </tr>
 4825: SCANTRONFORM
 4826:    
 4827:     $r->print($result);
 4828: 
 4829:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 4830:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 4831: 
 4832: 	# Chunk of form to prompt for a scantron file upload.
 4833: 
 4834:         $r->print(<<SCANTRONFORM);
 4835:     <tr>
 4836:       <td bgcolor="#777777">
 4837:         <table width="100%" border="0">
 4838:           <tr bgcolor="#e6ffff">
 4839:             <td>
 4840:               &nbsp;<b>Specify a Scantron data file to upload.</b>
 4841:             </td>
 4842:           </tr>
 4843:           <tr bgcolor="#ffffe6">
 4844:             <td>
 4845: SCANTRONFORM
 4846:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 4847:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4848:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 4849:     $r->print(<<UPLOAD);
 4850:               <script type="text/javascript" language="javascript">
 4851:     function checkUpload(formname) {
 4852: 	if (formname.upfile.value == "") {
 4853: 	    alert("Please use the browse button to select a file from your local directory.");
 4854: 	    return false;
 4855: 	}
 4856: 	formname.submit();
 4857:     }
 4858:               </script>
 4859: 
 4860:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 4861:                 $default_form_data
 4862:                 <input name='courseid' type='hidden' value='$cnum' />
 4863:                 <input name='domainid' type='hidden' value='$cdom' />
 4864:                 <input name='command' value='scantronupload_save' type='hidden' />
 4865:                 File to upload:<input type="file" name="upfile" size="50" />
 4866:                 <br />
 4867:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 4868:               </form>
 4869: UPLOAD
 4870: 
 4871:         $r->print(<<SCANTRONFORM);
 4872:             </td>
 4873:           </tr>
 4874:         </table>
 4875:       </td>
 4876:     </tr>
 4877: SCANTRONFORM
 4878:     }
 4879: 
 4880:     # Chunk of the form that prompts to view a scoring office file,
 4881:     # corrected file, skipped records in a file.
 4882: 
 4883:     $r->print(<<SCANTRONFORM);
 4884:     <tr>
 4885:       <form action='/adm/grades' name='scantron_download'>
 4886:         <td bgcolor="#777777">
 4887: 	  $default_form_data
 4888:           <input type="hidden" name="command" value="scantron_download" />
 4889:           <table width="100%" border="0">
 4890:             <tr bgcolor="#e6ffff">
 4891:               <td colspan="2">
 4892:                 &nbsp;<b>Download a scoring office file</b>
 4893:               </td>
 4894:             </tr>
 4895:             <tr bgcolor="#ffffe6">
 4896:               <td> Filename of scoring office file: </td><td> $file_selector </td>
 4897:             </tr>
 4898:             <tr bgcolor="#ffffe6">
 4899:               <td colspan="2">
 4900:                 <input type="submit" value="Download: Show List of Associated Files" />
 4901:               </td>
 4902:             </tr>
 4903:           </table>
 4904:         </td>
 4905:       </form>
 4906:     </tr>
 4907: SCANTRONFORM
 4908: 
 4909:     $r->print('<tr><td bgcolor="#777777">');
 4910:     &Apache::lonpickcode::code_list($r,2);
 4911:     $r->print('</td></tr></table>');
 4912:     $r->print($grading_menu_button);
 4913:     return
 4914: }
 4915: 
 4916: =pod
 4917: 
 4918: =item get_scantron_config
 4919: 
 4920:    Parse and return the scantron configuration line selected as a
 4921:    hash of configuration file fields.
 4922: 
 4923:  Arguments:
 4924:     which - the name of the configuration to parse from the file.
 4925: 
 4926: 
 4927:  Returns:
 4928:             If the named configuration is not in the file, an empty
 4929:             hash is returned.
 4930:     a hash with the fields
 4931:       name         - internal name for the this configuration setup
 4932:       description  - text to display to operator that describes this config
 4933:       CODElocation - if 0 or the string 'none'
 4934:                           - no CODE exists for this config
 4935:                      if -1 || the string 'letter'
 4936:                           - a CODE exists for this config and is
 4937:                             a string of letters
 4938:                      Unsupported value (but planned for future support)
 4939:                           if a positive integer
 4940:                                - The CODE exists as the first n items from
 4941:                                  the question section of the form
 4942:                           if the string 'number'
 4943:                                - The CODE exists for this config and is
 4944:                                  a string of numbers
 4945:       CODEstart   - (only matter if a CODE exists) column in the line where
 4946:                      the CODE starts
 4947:       CODElength  - length of the CODE
 4948:       IDstart     - column where the student ID number starts
 4949:       IDlength    - length of the student ID info
 4950:       Qstart      - column where the information from the bubbled
 4951:                     'questions' start
 4952:       Qlength     - number of columns comprising a single bubble line from
 4953:                     the sheet. (usually either 1 or 10)
 4954:       Qon         - either a single character representing the character used
 4955:                     to signal a bubble was chosen in the positional setup, or
 4956:                     the string 'letter' if the letter of the chosen bubble is
 4957:                     in the final, or 'number' if a number representing the
 4958:                     chosen bubble is in the file (1->A 0->J)
 4959:       Qoff        - the character used to represent that a bubble was
 4960:                     left blank
 4961:       PaperID     - if the scanning process generates a unique number for each
 4962:                     sheet scanned the column that this ID number starts in
 4963:       PaperIDlength - number of columns that comprise the unique ID number
 4964:                       for the sheet of paper
 4965:       FirstName   - column that the first name starts in
 4966:       FirstNameLength - number of columns that the first name spans
 4967:  
 4968:       LastName    - column that the last name starts in
 4969:       LastNameLength - number of columns that the last name spans
 4970: 
 4971: =cut
 4972: 
 4973: sub get_scantron_config {
 4974:     my ($which) = @_;
 4975:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4976:     my %config;
 4977:     #FIXME probably should move to XML it has already gotten a bit much now
 4978:     foreach my $line (<$fh>) {
 4979: 	my ($name,$descrip)=split(/:/,$line);
 4980: 	if ($name ne $which ) { next; }
 4981: 	chomp($line);
 4982: 	my @config=split(/:/,$line);
 4983: 	$config{'name'}=$config[0];
 4984: 	$config{'description'}=$config[1];
 4985: 	$config{'CODElocation'}=$config[2];
 4986: 	$config{'CODEstart'}=$config[3];
 4987: 	$config{'CODElength'}=$config[4];
 4988: 	$config{'IDstart'}=$config[5];
 4989: 	$config{'IDlength'}=$config[6];
 4990: 	$config{'Qstart'}=$config[7];
 4991: 	$config{'Qlength'}=$config[8];
 4992: 	$config{'Qoff'}=$config[9];
 4993: 	$config{'Qon'}=$config[10];
 4994: 	$config{'PaperID'}=$config[11];
 4995: 	$config{'PaperIDlength'}=$config[12];
 4996: 	$config{'FirstName'}=$config[13];
 4997: 	$config{'FirstNamelength'}=$config[14];
 4998: 	$config{'LastName'}=$config[15];
 4999: 	$config{'LastNamelength'}=$config[16];
 5000: 	last;
 5001:     }
 5002:     return %config;
 5003: }
 5004: 
 5005: =pod 
 5006: 
 5007: =item username_to_idmap
 5008: 
 5009:     creates a hash keyed by student id with values of the corresponding
 5010:     student username:domain.
 5011: 
 5012:   Arguments:
 5013: 
 5014:     $classlist - reference to the class list hash. This is a hash
 5015:                  keyed by student name:domain  whose elements are references
 5016:                  to arrays containing various chunks of information
 5017:                  about the student. (See loncoursedata for more info).
 5018: 
 5019:   Returns
 5020:     %idmap - the constructed hash
 5021: 
 5022: =cut
 5023: 
 5024: sub username_to_idmap {
 5025:     my ($classlist)= @_;
 5026:     my %idmap;
 5027:     foreach my $student (keys(%$classlist)) {
 5028: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5029: 	    $student;
 5030:     }
 5031:     return %idmap;
 5032: }
 5033: 
 5034: =pod
 5035: 
 5036: =item scantron_fixup_scanline
 5037: 
 5038:    Process a requested correction to a scanline.
 5039: 
 5040:   Arguments:
 5041:     $scantron_config   - hash from &get_scantron_config()
 5042:     $scan_data         - hash of correction information 
 5043:                           (see &scantron_getfile())
 5044:     $line              - existing scanline
 5045:     $whichline         - line number of the passed in scanline
 5046:     $field             - type of change to process 
 5047:                          (either 
 5048:                           'ID'     -> correct the student ID number
 5049:                           'CODE'   -> correct the CODE
 5050:                           'answer' -> fixup the submitted answers)
 5051:     
 5052:    $args               - hash of additional info,
 5053:                           - 'ID' 
 5054:                                'newid' -> studentID to use in replacement
 5055:                                           of existing one
 5056:                           - 'CODE' 
 5057:                                'CODE_ignore_dup' - set to true if duplicates
 5058:                                                    should be ignored.
 5059: 	                       'CODE' - is new code or 'use_unfound'
 5060:                                         if the existing unfound code should
 5061:                                         be used as is
 5062:                           - 'answer'
 5063:                                'response' - new answer or 'none' if blank
 5064:                                'question' - the bubble line to change
 5065: 
 5066:   Returns:
 5067:     $line - the modified scanline
 5068: 
 5069:   Side effects: 
 5070:     $scan_data - may be updated
 5071: 
 5072: =cut
 5073: 
 5074: 
 5075: sub scantron_fixup_scanline {
 5076:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5077: 
 5078:     if ($field eq 'ID') {
 5079: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5080: 	    return ($line,1,'New value too large');
 5081: 	}
 5082: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5083: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5084: 				     $args->{'newid'});
 5085: 	}
 5086: 	substr($line,$$scantron_config{'IDstart'}-1,
 5087: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5088: 	if ($args->{'newid'}=~/^\s*$/) {
 5089: 	    &scan_data($scan_data,"$whichline.user",
 5090: 		       $args->{'username'}.':'.$args->{'domain'});
 5091: 	}
 5092:     } elsif ($field eq 'CODE') {
 5093: 	if ($args->{'CODE_ignore_dup'}) {
 5094: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5095: 	}
 5096: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5097: 	if ($args->{'CODE'} ne 'use_unfound') {
 5098: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5099: 		return ($line,1,'New CODE value too large');
 5100: 	    }
 5101: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5102: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5103: 	    }
 5104: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5105: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5106: 	}
 5107:     } elsif ($field eq 'answer') {
 5108: 	my $length=$scantron_config->{'Qlength'};
 5109: 	my $off=$scantron_config->{'Qoff'};
 5110: 	my $on=$scantron_config->{'Qon'};
 5111: 	my $answer=${off}x$length;
 5112: 	if ($args->{'response'} eq 'none') {
 5113: 	    &scan_data($scan_data,
 5114: 		       "$whichline.no_bubble.".$args->{'question'},'1');
 5115: 	} else {
 5116: 	    if ($on eq 'letter') {
 5117: 		my @alphabet=('A'..'Z');
 5118: 		$answer=$alphabet[$args->{'response'}];
 5119: 	    } elsif ($on eq 'number') {
 5120: 		$answer=$args->{'response'}+1;
 5121: 		if ($answer == 10) { $answer = '0'; }
 5122: 	    } else {
 5123: 		substr($answer,$args->{'response'},1)=$on;
 5124: 	    }
 5125: 	    &scan_data($scan_data,
 5126: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
 5127: 	}
 5128: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5129: 	substr($line,$where-1,$length)=$answer;
 5130:     }
 5131:     return $line;
 5132: }
 5133: 
 5134: =pod
 5135: 
 5136: =item scan_data
 5137: 
 5138:     Edit or look up  an item in the scan_data hash.
 5139: 
 5140:   Arguments:
 5141:     $scan_data  - The hash (see scantron_getfile)
 5142:     $key        - shorthand of the key to edit (actual key is
 5143:                   scantronfilename_key).
 5144:     $data        - New value of the hash entry.
 5145:     $delete      - If true, the entry is removed from the hash.
 5146: 
 5147:   Returns:
 5148:     The new value of the hash table field (undefined if deleted).
 5149: 
 5150: =cut
 5151: 
 5152: 
 5153: sub scan_data {
 5154:     my ($scan_data,$key,$value,$delete)=@_;
 5155:     my $filename=$env{'form.scantron_selectfile'};
 5156:     if (defined($value)) {
 5157: 	$scan_data->{$filename.'_'.$key} = $value;
 5158:     }
 5159:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5160:     return $scan_data->{$filename.'_'.$key};
 5161: }
 5162: 
 5163: =pod 
 5164: 
 5165: =item scantron_parse_scanline
 5166: 
 5167:   Decodes a scanline from the selected scantron file
 5168: 
 5169:  Arguments:
 5170:     line             - The text of the scantron file line to process
 5171:     whichline        - Line number
 5172:     scantron_config  - Hash describing the format of the scantron lines.
 5173:     scan_data        - Hash of extra information about the scanline
 5174:                        (see scantron_getfile for more information)
 5175:     just_header      - True if should not process question answers but only
 5176:                        the stuff to the left of the answers.
 5177:  Returns:
 5178:    Hash containing the result of parsing the scanline
 5179: 
 5180:    Keys are all proceeded by the string 'scantron.'
 5181: 
 5182:        CODE    - the CODE in use for this scanline
 5183:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5184:                  by the operator
 5185:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5186:                             CODEs were selected, but the usage has been
 5187:                             forced by the operator
 5188:        ID  - student ID
 5189:        PaperID - if used, the ID number printed on the sheet when the 
 5190:                  paper was scanned
 5191:        FirstName - first name from the sheet
 5192:        LastName  - last name from the sheet
 5193: 
 5194:      if just_header was not true these key may also exist
 5195: 
 5196:        missingerror - a list of bubble ranges that are considered to be answers
 5197:                       to a single question that don't have any bubbles filled in.
 5198:                       Of the form questionnumber:firstbubblenumber:count.
 5199:        doubleerror  - a list of bubble ranges that are considered to be answers
 5200:                       to a single question that have more than one bubble filled in.
 5201:                       Of the form questionnumber::firstbubblenumber:count
 5202:    
 5203:                 In the above, count is the number of bubble responses in the
 5204:                 input line needed to represent the possible answers to the question.
 5205:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5206:                 per line would have count = 2.
 5207: 
 5208:        maxquest     - the number of the last bubble line that was parsed
 5209: 
 5210:        (<number> starts at 1)
 5211:        <number>.answer - zero or more letters representing the selected
 5212:                          letters from the scanline for the bubble line 
 5213:                          <number>.
 5214:                          if blank there was either no bubble or there where
 5215:                          multiple bubbles, (consult the keys missingerror and
 5216:                          doubleerror if this is an error condition)
 5217: 
 5218: =cut
 5219: 
 5220: sub scantron_parse_scanline {
 5221:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5222:     my %record;
 5223:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5224:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5225:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5226: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5227: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5228: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5229: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5230: 	    $record{'scantron.CODE'}=substr($data,
 5231: 					    $$scantron_config{'CODEstart'}-1,
 5232: 					    $$scantron_config{'CODElength'});
 5233: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5234: 		$record{'scantron.useCODE'}=1;
 5235: 	    }
 5236: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5237: 		$record{'scantron.CODE_ignore_dup'}=1;
 5238: 	    }
 5239: 	} else {
 5240: 	    #FIXME interpret first N questions
 5241: 	}
 5242:     }
 5243:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5244: 				  $$scantron_config{'IDlength'});
 5245:     $record{'scantron.PaperID'}=
 5246: 	substr($data,$$scantron_config{'PaperID'}-1,
 5247: 	       $$scantron_config{'PaperIDlength'});
 5248:     $record{'scantron.FirstName'}=
 5249: 	substr($data,$$scantron_config{'FirstName'}-1,
 5250: 	       $$scantron_config{'FirstNamelength'});
 5251:     $record{'scantron.LastName'}=
 5252: 	substr($data,$$scantron_config{'LastName'}-1,
 5253: 	       $$scantron_config{'LastNamelength'});
 5254:     if ($just_header) { return \%record; }
 5255: 
 5256:     my @alphabet=('A'..'Z');
 5257:     my $questnum=0;
 5258:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5259: 
 5260:     while ($questions) {
 5261: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5262: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
 5263: 
 5264: 
 5265: 
 5266: 	$questnum++;
 5267: 	my $currentquest = substr($questions,0,$answer_length);
 5268: 	$questions       = substr($questions,0,$answer_length)='';
 5269: 	if (length($currentquest) < $answer_length) { next; }
 5270: 
 5271: 	# Qon letter implies for each slot in currentquest we have:
 5272: 	#    ? or * for doubles a letter in A-Z for a bubble and
 5273:         #    about anything else (esp. a value of Qoff for missing
 5274: 	#    bubbles.
 5275: 
 5276: 
 5277: 	if ($$scantron_config{'Qon'} eq 'letter') {
 5278: 
 5279: 	    if ($currentquest =~ /\?/
 5280: 		|| $currentquest =~ /\*/
 5281: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
 5282: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5283: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
 5284: 		    my $bubble = substr($currentquest, $ans, 1);
 5285: 		    if ($bubble =~ /[A-Z]/ ) {
 5286: 			$record{"scantron.$ansnum.answer"} = $bubble;
 5287: 		    } else {
 5288: 			$record{"scantron.$ansnum.answer"}='';
 5289: 		    }
 5290: 		    $ansnum++;
 5291: 		}
 5292: 
 5293: 	    } elsif (!defined($currentquest)
 5294: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
 5295: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
 5296: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5297: 		    $record{"scantron.$ansnum.answer"}='';
 5298: 		    $ansnum++;
 5299: 
 5300: 		}
 5301: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5302: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5303: 		    $ansnum += $answers_needed;
 5304: 		}
 5305: 
 5306: 	    } else {
 5307: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5308: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
 5309: 		    $ansnum++;
 5310: 		}
 5311: 	    }
 5312: 
 5313: 	# Qon 'number' implies each slot gives a digit that indexes the
 5314: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
 5315:         #    and *? for double bubbles on a line.
 5316: 	#    these answers are also stored as letters.
 5317: 
 5318: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
 5319: 	    if ($currentquest =~ /\?/
 5320: 		|| $currentquest =~ /\*/
 5321: 		|| (&occurence_count($currentquest, '\d') > 1)) {
 5322: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5323: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5324: 		    my $bubble = substr($currentquest, $ans, 1);
 5325: 		    if ($bubble =~ /\d/) {
 5326: 			$record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
 5327: 		    } else {
 5328: 			$record{"scantron.$ansnum.answer"}=' ';
 5329: 		    }
 5330: 		    $ansnum++;
 5331: 		}
 5332: 
 5333: 	    } elsif (!defined($currentquest)
 5334: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
 5335: 		     || (&occurence_count($currentquest, '\d') == 0)) {
 5336: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5337: 		    $record{"scantron.$ansnum.answer"}='';
 5338: 		    $ansnum++;
 5339: 
 5340: 		}
 5341: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5342: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5343: 		    $ansnum += $answers_needed;
 5344: 		}
 5345: 
 5346: 	    } else {
 5347: 		$currentquest = &digits_to_letters($currentquest);
 5348: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
 5349: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
 5350: 		    $ansnum++;
 5351: 		}
 5352: 	    }
 5353: 	} else {
 5354: 
 5355: 	    # Otherwise there's a positional notation;
 5356: 	    # each bubble line requires Qlength items, and there are filled in
 5357: 	    # bubbles for each case where there 'Qon' characters.
 5358: 	    #
 5359: 
 5360: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
 5361: 
 5362: 	    # If the split only  giveas us one element.. the full length of the
 5363: 	    # answser string, no bubbles are filled in:
 5364: 
 5365: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5366: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5367: 		    $record{"scantron.$ansnum.answer"}='';
 5368: 		    $ansnum++;
 5369: 
 5370: 		}
 5371: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5372: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5373: 		}
 5374: 	    } elsif (scalar(@array) lt 2) {
 5375: 
 5376: 		my $location      = length($array[0]);
 5377: 		my $line_num      = $location / $$scantron_config{'Qlength'};
 5378: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
 5379: 
 5380: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5381: 		    if ($ans eq $line_num) {
 5382: 			$record{"scantron.$ansnum.answer"} = $bubble;
 5383: 		    } else {
 5384: 			$record{"scantron.$ansnum.answer"} = ' ';
 5385: 		    }
 5386: 		    $ansnum++;
 5387: 		}
 5388: 	    }
 5389: 	    #  If there's more than one instance of a bubble character
 5390: 	    #  That's a double bubble; with positional notation we can
 5391: 	    #  record all the bubbles filled in as well as the 
 5392: 	    #  fact this response consists of multiple bubbles.
 5393: 	    #
 5394: 	    else {
 5395: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5396: 
 5397: 		my $first_answer = $ansnum;
 5398: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
 5399: 		    my $item = $first_answer+$ans;
 5400: 		    $record{"scantron.$item.answer"} = '';
 5401: 		}
 5402: 
 5403: 		my @ans=@array;
 5404: 		my $i=0;
 5405: 		my $increment = 0;
 5406: 		while ($#ans) {
 5407: 		    $i+=length($ans[0]) + $increment;
 5408: 		    my $line   = int($i/$$scantron_config{'Qlength'} + $first_answer);
 5409: 		    my $bubble = $i%$$scantron_config{'Qlength'};
 5410: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
 5411: 		    shift(@ans);
 5412: 		    $increment = 1;
 5413: 		}
 5414: 		$ansnum += $answers_needed;
 5415: 	    }
 5416: 	}
 5417:     }
 5418:     $record{'scantron.maxquest'}=$questnum;
 5419:     return \%record;
 5420: }
 5421: 
 5422: =pod
 5423: 
 5424: =item scantron_add_delay
 5425: 
 5426:    Adds an error message that occurred during the grading phase to a
 5427:    queue of messages to be shown after grading pass is complete
 5428: 
 5429:  Arguments:
 5430:    $delayqueue  - arrary ref of hash ref of error messages
 5431:    $scanline    - the scanline that caused the error
 5432:    $errormesage - the error message
 5433:    $errorcode   - a numeric code for the error
 5434: 
 5435:  Side Effects:
 5436:    updates the $delayqueue to have a new hash ref of the error
 5437: 
 5438: =cut
 5439: 
 5440: sub scantron_add_delay {
 5441:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5442:     push(@$delayqueue,
 5443: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5444: 	  'ecode' => $errorcode }
 5445: 	 );
 5446: }
 5447: 
 5448: =pod
 5449: 
 5450: =item scantron_find_student
 5451: 
 5452:    Finds the username for the current scanline
 5453: 
 5454:   Arguments:
 5455:    $scantron_record - hash result from scantron_parse_scanline
 5456:    $scan_data       - hash of correction information 
 5457:                       (see &scantron_getfile() form more information)
 5458:    $idmap           - hash from &username_to_idmap()
 5459:    $line            - number of current scanline
 5460:  
 5461:   Returns:
 5462:    Either 'username:domain' or undef if unknown
 5463: 
 5464: =cut
 5465: 
 5466: sub scantron_find_student {
 5467:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5468:     my $scanID=$$scantron_record{'scantron.ID'};
 5469:     if ($scanID =~ /^\s*$/) {
 5470:  	return &scan_data($scan_data,"$line.user");
 5471:     }
 5472:     foreach my $id (keys(%$idmap)) {
 5473:  	if (lc($id) eq lc($scanID)) {
 5474:  	    return $$idmap{$id};
 5475:  	}
 5476:     }
 5477:     return undef;
 5478: }
 5479: 
 5480: =pod
 5481: 
 5482: =item scantron_filter
 5483: 
 5484:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5485:    hidden resources was selected
 5486: 
 5487: =cut
 5488: 
 5489: sub scantron_filter {
 5490:     my ($curres)=@_;
 5491: 
 5492:     if (ref($curres) && $curres->is_problem()) {
 5493: 	# if the user has asked to not have either hidden
 5494: 	# or 'randomout' controlled resources to be graded
 5495: 	# don't include them
 5496: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5497: 	    && $curres->randomout) {
 5498: 	    return 0;
 5499: 	}
 5500: 	return 1;
 5501:     }
 5502:     return 0;
 5503: }
 5504: 
 5505: =pod
 5506: 
 5507: =item scantron_process_corrections
 5508: 
 5509:    Gets correction information out of submitted form data and corrects
 5510:    the scanline
 5511: 
 5512: =cut
 5513: 
 5514: sub scantron_process_corrections {
 5515:     my ($r) = @_;
 5516:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5517:     my ($scanlines,$scan_data)=&scantron_getfile();
 5518:     my $classlist=&Apache::loncoursedata::get_classlist();
 5519:     my $which=$env{'form.scantron_line'};
 5520:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5521:     my ($skip,$err,$errmsg);
 5522:     if ($env{'form.scantron_skip_record'}) {
 5523: 	$skip=1;
 5524:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5525: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5526: 	    $env{'form.scantron_domain'};
 5527: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5528: 	($line,$err,$errmsg)=
 5529: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5530: 				     'ID',{'newid'=>$newid,
 5531: 				    'username'=>$env{'form.scantron_username'},
 5532: 				    'domain'=>$env{'form.scantron_domain'}});
 5533:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5534: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5535: 	my $newCODE;
 5536: 	my %args;
 5537: 	if      ($resolution eq 'use_unfound') {
 5538: 	    $newCODE='use_unfound';
 5539: 	} elsif ($resolution eq 'use_found') {
 5540: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5541: 	} elsif ($resolution eq 'use_typed') {
 5542: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5543: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5544: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5545: 	}
 5546: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5547: 	    $args{'CODE_ignore_dup'}=1;
 5548: 	}
 5549: 	$args{'CODE'}=$newCODE;
 5550: 	($line,$err,$errmsg)=
 5551: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5552: 				     'CODE',\%args);
 5553:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5554: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5555: 	    ($line,$err,$errmsg)=
 5556: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5557: 					 $which,'answer',
 5558: 					 { 'question'=>$question,
 5559: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
 5560: 	    if ($err) { last; }
 5561: 	}
 5562:     }
 5563:     if ($err) {
 5564: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5565:     } else {
 5566: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5567: 	&scantron_putfile($scanlines,$scan_data);
 5568:     }
 5569: }
 5570: 
 5571: =pod
 5572: 
 5573: =item reset_skipping_status
 5574: 
 5575:    Forgets the current set of remember skipped scanlines (and thus
 5576:    reverts back to considering all lines in the
 5577:    scantron_skipped_<filename> file)
 5578: 
 5579: =cut
 5580: 
 5581: sub reset_skipping_status {
 5582:     my ($scanlines,$scan_data)=&scantron_getfile();
 5583:     &scan_data($scan_data,'remember_skipping',undef,1);
 5584:     &scantron_putfile(undef,$scan_data);
 5585: }
 5586: 
 5587: =pod
 5588: 
 5589: =item start_skipping
 5590: 
 5591:    Marks a scanline to be skipped. 
 5592: 
 5593: =cut
 5594: 
 5595: sub start_skipping {
 5596:     my ($scan_data,$i)=@_;
 5597:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5598:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5599: 	$remembered{$i}=2;
 5600:     } else {
 5601: 	$remembered{$i}=1;
 5602:     }
 5603:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5604: }
 5605: 
 5606: =pod
 5607: 
 5608: =item should_be_skipped
 5609: 
 5610:    Checks whether a scanline should be skipped.
 5611: 
 5612: =cut
 5613: 
 5614: sub should_be_skipped {
 5615:     my ($scanlines,$scan_data,$i)=@_;
 5616:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5617: 	# not redoing old skips
 5618: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5619: 	return 0;
 5620:     }
 5621:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5622: 
 5623:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5624: 	return 0;
 5625:     }
 5626:     return 1;
 5627: }
 5628: 
 5629: =pod
 5630: 
 5631: =item remember_current_skipped
 5632: 
 5633:    Discovers what scanlines are in the scantron_skipped_<filename>
 5634:    file and remembers them into scan_data for later use.
 5635: 
 5636: =cut
 5637: 
 5638: sub remember_current_skipped {
 5639:     my ($scanlines,$scan_data)=&scantron_getfile();
 5640:     my %to_remember;
 5641:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 5642: 	if ($scanlines->{'skipped'}[$i]) {
 5643: 	    $to_remember{$i}=1;
 5644: 	}
 5645:     }
 5646: 
 5647:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 5648:     &scantron_putfile(undef,$scan_data);
 5649: }
 5650: 
 5651: =pod
 5652: 
 5653: =item check_for_error
 5654: 
 5655:     Checks if there was an error when attempting to remove a specific
 5656:     scantron_.. bubble sheet data file. Prints out an error if
 5657:     something went wrong.
 5658: 
 5659: =cut
 5660: 
 5661: sub check_for_error {
 5662:     my ($r,$result)=@_;
 5663:     if ($result ne 'ok' && $result ne 'not_found' ) {
 5664: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
 5665:     }
 5666: }
 5667: 
 5668: =pod
 5669: 
 5670: =item scantron_warning_screen
 5671: 
 5672:    Interstitial screen to make sure the operator has selected the
 5673:    correct options before we start the validation phase.
 5674: 
 5675: =cut
 5676: 
 5677: sub scantron_warning_screen {
 5678:     my ($button_text)=@_;
 5679:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 5680:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5681:     my $CODElist;
 5682:     if ($scantron_config{'CODElocation'} &&
 5683: 	$scantron_config{'CODEstart'} &&
 5684: 	$scantron_config{'CODElength'}) {
 5685: 	$CODElist=$env{'form.scantron_CODElist'};
 5686: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 5687: 	$CODElist=
 5688: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
 5689: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 5690:     }
 5691:     return (<<STUFF);
 5692: <p>
 5693: <span class="LC_warning">Please double check the information
 5694:                  below before clicking on '$button_text'</span>
 5695: </p>
 5696: <table>
 5697: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
 5698: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
 5699: $CODElist
 5700: </table>
 5701: <br />
 5702: <p> If this information is correct, please click on '$button_text'.</p>
 5703: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
 5704: 
 5705: <br />
 5706: STUFF
 5707: }
 5708: 
 5709: =pod
 5710: 
 5711: =item scantron_do_warning
 5712: 
 5713:    Check if the operator has picked something for all required
 5714:    fields. Error out if something is missing.
 5715: 
 5716: =cut
 5717: 
 5718: sub scantron_do_warning {
 5719:     my ($r)=@_;
 5720:     my ($symb)=&get_symb($r);
 5721:     if (!$symb) {return '';}
 5722:     my $default_form_data=&defaultFormData($symb);
 5723:     $r->print(&scantron_form_start().$default_form_data);
 5724:     if ( $env{'form.selectpage'} eq '' ||
 5725: 	 $env{'form.scantron_selectfile'} eq '' ||
 5726: 	 $env{'form.scantron_format'} eq '' ) {
 5727: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
 5728: 	if ( $env{'form.selectpage'} eq '') {
 5729: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
 5730: 	} 
 5731: 	if ( $env{'form.scantron_selectfile'} eq '') {
 5732: 	    $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
 5733: 	} 
 5734: 	if ( $env{'form.scantron_format'} eq '') {
 5735: 	    $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
 5736: 	} 
 5737:     } else {
 5738: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 5739: 	$r->print(<<STUFF);
 5740: $warning
 5741: <input type="submit" name="submit" value="Grading: Validate Records" />
 5742: <input type="hidden" name="command" value="scantron_validate" />
 5743: STUFF
 5744:     }
 5745:     $r->print("</form><br />".&show_grading_menu_form($symb));
 5746:     return '';
 5747: }
 5748: 
 5749: =pod
 5750: 
 5751: =item scantron_form_start
 5752: 
 5753:     html hidden input for remembering all selected grading options
 5754: 
 5755: =cut
 5756: 
 5757: sub scantron_form_start {
 5758:     my ($max_bubble)=@_;
 5759:     my $result= <<SCANTRONFORM;
 5760: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 5761:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 5762:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 5763:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 5764:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 5765:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 5766:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 5767:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 5768:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 5769:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 5770: SCANTRONFORM
 5771: 
 5772:   my $line = 0;
 5773:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 5774:        my $chunk =
 5775: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 5776:        $chunk .=
 5777: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 5778:        $result .= $chunk;
 5779:        $line++;
 5780:    }
 5781:     return $result;
 5782: }
 5783: 
 5784: =pod
 5785: 
 5786: =item scantron_validate_file
 5787: 
 5788:     Dispatch routine for doing validation of a bubble sheet data file.
 5789: 
 5790:     Also processes any necessary information resets that need to
 5791:     occur before validation begins (ignore previous corrections,
 5792:     restarting the skipped records processing)
 5793: 
 5794: =cut
 5795: 
 5796: sub scantron_validate_file {
 5797:     my ($r) = @_;
 5798:     my ($symb)=&get_symb($r);
 5799:     if (!$symb) {return '';}
 5800:     my $default_form_data=&defaultFormData($symb);
 5801:     
 5802:     # do the detection of only doing skipped records first befroe we delete
 5803:     # them when doing the corrections reset
 5804:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 5805: 	&reset_skipping_status();
 5806:     }
 5807:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 5808: 	&remember_current_skipped();
 5809: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 5810:     }
 5811: 
 5812:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 5813: 	&check_for_error($r,&scantron_remove_file('corrected'));
 5814: 	&check_for_error($r,&scantron_remove_file('skipped'));
 5815: 	&check_for_error($r,&scantron_remove_scan_data());
 5816: 	$env{'form.scantron_options_ignore'}='done';
 5817:     }
 5818: 
 5819:     if ($env{'form.scantron_corrections'}) {
 5820: 	&scantron_process_corrections($r);
 5821:     }
 5822:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
 5823:     #get the student pick code ready
 5824:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 5825:     my $max_bubble=&scantron_get_maxbubble();
 5826:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 5827:     $r->print($result);
 5828:     
 5829:     my @validate_phases=( 'sequence',
 5830: 			  'ID',
 5831: 			  'CODE',
 5832: 			  'doublebubble',
 5833: 			  'missingbubbles');
 5834:     if (!$env{'form.validatepass'}) {
 5835: 	$env{'form.validatepass'} = 0;
 5836:     }
 5837:     my $currentphase=$env{'form.validatepass'};
 5838: 
 5839: 
 5840:     my $stop=0;
 5841:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 5842: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
 5843: 	$r->rflush();
 5844: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 5845: 	{
 5846: 	    no strict 'refs';
 5847: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 5848: 	}
 5849:     }
 5850:     if (!$stop) {
 5851: 	my $warning=&scantron_warning_screen('Start Grading');
 5852: 	$r->print(<<STUFF);
 5853: Validation process complete.<br />
 5854: $warning
 5855: <input type="submit" name="submit" value="Start Grading" />
 5856: <input type="hidden" name="command" value="scantron_process" />
 5857: STUFF
 5858: 
 5859:     } else {
 5860: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 5861: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 5862:     }
 5863:     if ($stop) {
 5864: 	if ($validate_phases[$currentphase] eq 'sequence') {
 5865: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
 5866: 	    $r->print(' this error <br />');
 5867: 
 5868: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
 5869: 	} else {
 5870: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
 5871: 	    $r->print(' using corrected info <br />');
 5872: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
 5873: 	    $r->print(" this scanline saving it for later.");
 5874: 	}
 5875:     }
 5876:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 5877:     return '';
 5878: }
 5879: 
 5880: 
 5881: =pod
 5882: 
 5883: =item scantron_remove_file
 5884: 
 5885:    Removes the requested bubble sheet data file, makes sure that
 5886:    scantron_original_<filename> is never removed
 5887: 
 5888: 
 5889: =cut
 5890: 
 5891: sub scantron_remove_file {
 5892:     my ($which)=@_;
 5893:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5894:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5895:     my $file='scantron_';
 5896:     if ($which eq 'corrected' || $which eq 'skipped') {
 5897: 	$file.=$which.'_';
 5898:     } else {
 5899: 	return 'refused';
 5900:     }
 5901:     $file.=$env{'form.scantron_selectfile'};
 5902:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 5903: }
 5904: 
 5905: 
 5906: =pod
 5907: 
 5908: =item scantron_remove_scan_data
 5909: 
 5910:    Removes all scan_data correction for the requested bubble sheet
 5911:    data file.  (In the case that both the are doing skipped records we need
 5912:    to remember the old skipped lines for the time being so that element
 5913:    persists for a while.)
 5914: 
 5915: =cut
 5916: 
 5917: sub scantron_remove_scan_data {
 5918:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5919:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5920:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 5921:     my @todelete;
 5922:     my $filename=$env{'form.scantron_selectfile'};
 5923:     foreach my $key (@keys) {
 5924: 	if ($key=~/^\Q$filename\E_/) {
 5925: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 5926: 		$key=~/remember_skipping/) {
 5927: 		next;
 5928: 	    }
 5929: 	    push(@todelete,$key);
 5930: 	}
 5931:     }
 5932:     my $result;
 5933:     if (@todelete) {
 5934: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
 5935:     }
 5936:     return $result;
 5937: }
 5938: 
 5939: 
 5940: =pod
 5941: 
 5942: =item scantron_getfile
 5943: 
 5944:     Fetches the requested bubble sheet data file (all 3 versions), and
 5945:     the scan_data hash
 5946:   
 5947:   Arguments:
 5948:     None
 5949: 
 5950:   Returns:
 5951:     2 hash references
 5952: 
 5953:      - first one has 
 5954:          orig      -
 5955:          corrected -
 5956:          skipped   -  each of which points to an array ref of the specified
 5957:                       file broken up into individual lines
 5958:          count     - number of scanlines
 5959:  
 5960:      - second is the scan_data hash possible keys are
 5961:        ($number refers to scanline numbered $number and thus the key affects
 5962:         only that scanline
 5963:         $bubline refers to the specific bubble line element and the aspects
 5964:         refers to that specific bubble line element)
 5965: 
 5966:        $number.user - username:domain to use
 5967:        $number.CODE_ignore_dup 
 5968:                     - ignore the duplicate CODE error 
 5969:        $number.useCODE
 5970:                     - use the CODE in the scanline as is
 5971:        $number.no_bubble.$bubline
 5972:                     - it is valid that there is no bubbled in bubble
 5973:                       at $number $bubline
 5974:        remember_skipping
 5975:                     - a frozen hash containing keys of $number and values
 5976:                       of either 
 5977:                         1 - we are on a 'do skipped records pass' and plan
 5978:                             on processing this line
 5979:                         2 - we are on a 'do skipped records pass' and this
 5980:                             scanline has been marked to skip yet again
 5981: 
 5982: =cut
 5983: 
 5984: sub scantron_getfile {
 5985:     #FIXME really would prefer a scantron directory
 5986:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5987:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5988:     my $lines;
 5989:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5990: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 5991:     my %scanlines;
 5992:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 5993:     my $temp=$scanlines{'orig'};
 5994:     $scanlines{'count'}=$#$temp;
 5995: 
 5996:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5997: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 5998:     if ($lines eq '-1') {
 5999: 	$scanlines{'corrected'}=[];
 6000:     } else {
 6001: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6002:     }
 6003:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6004: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6005:     if ($lines eq '-1') {
 6006: 	$scanlines{'skipped'}=[];
 6007:     } else {
 6008: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6009:     }
 6010:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6011:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6012:     my %scan_data = @tmp;
 6013:     return (\%scanlines,\%scan_data);
 6014: }
 6015: 
 6016: =pod
 6017: 
 6018: =item lonnet_putfile
 6019: 
 6020:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6021: 
 6022:  Arguments:
 6023:    $contents - data to store
 6024:    $filename - filename to store $contents into
 6025: 
 6026:  Returns:
 6027:    result value from &Apache::lonnet::finishuserfileupload
 6028: 
 6029: =cut
 6030: 
 6031: sub lonnet_putfile {
 6032:     my ($contents,$filename)=@_;
 6033:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6034:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6035:     $env{'form.sillywaytopassafilearound'}=$contents;
 6036:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6037: 
 6038: }
 6039: 
 6040: =pod
 6041: 
 6042: =item scantron_putfile
 6043: 
 6044:     Stores the current version of the bubble sheet data files, and the
 6045:     scan_data hash. (Does not modify the original version only the
 6046:     corrected and skipped versions.
 6047: 
 6048:  Arguments:
 6049:     $scanlines - hash ref that looks like the first return value from
 6050:                  &scantron_getfile()
 6051:     $scan_data - hash ref that looks like the second return value from
 6052:                  &scantron_getfile()
 6053: 
 6054: =cut
 6055: 
 6056: sub scantron_putfile {
 6057:     my ($scanlines,$scan_data) = @_;
 6058:     #FIXME really would prefer a scantron directory
 6059:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6060:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6061:     if ($scanlines) {
 6062: 	my $prefix='scantron_';
 6063: # no need to update orig, shouldn't change
 6064: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6065: #		    $env{'form.scantron_selectfile'});
 6066: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6067: 			$prefix.'corrected_'.
 6068: 			$env{'form.scantron_selectfile'});
 6069: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6070: 			$prefix.'skipped_'.
 6071: 			$env{'form.scantron_selectfile'});
 6072:     }
 6073:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6074: }
 6075: 
 6076: =pod
 6077: 
 6078: =item scantron_get_line
 6079: 
 6080:    Returns the correct version of the scanline
 6081: 
 6082:  Arguments:
 6083:     $scanlines - hash ref that looks like the first return value from
 6084:                  &scantron_getfile()
 6085:     $scan_data - hash ref that looks like the second return value from
 6086:                  &scantron_getfile()
 6087:     $i         - number of the requested line (starts at 0)
 6088: 
 6089:  Returns:
 6090:    A scanline, (either the original or the corrected one if it
 6091:    exists), or undef if the requested scanline should be
 6092:    skipped. (Either because it's an skipped scanline, or it's an
 6093:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6094:    pass.
 6095: 
 6096: =cut
 6097: 
 6098: sub scantron_get_line {
 6099:     my ($scanlines,$scan_data,$i)=@_;
 6100:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6101:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6102:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6103:     return $scanlines->{'orig'}[$i]; 
 6104: }
 6105: 
 6106: =pod
 6107: 
 6108: =item scantron_todo_count
 6109: 
 6110:     Counts the number of scanlines that need processing.
 6111: 
 6112:  Arguments:
 6113:     $scanlines - hash ref that looks like the first return value from
 6114:                  &scantron_getfile()
 6115:     $scan_data - hash ref that looks like the second return value from
 6116:                  &scantron_getfile()
 6117: 
 6118:  Returns:
 6119:     $count - number of scanlines to process
 6120: 
 6121: =cut
 6122: 
 6123: sub get_todo_count {
 6124:     my ($scanlines,$scan_data)=@_;
 6125:     my $count=0;
 6126:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6127: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6128: 	if ($line=~/^[\s\cz]*$/) { next; }
 6129: 	$count++;
 6130:     }
 6131:     return $count;
 6132: }
 6133: 
 6134: =pod
 6135: 
 6136: =item scantron_put_line
 6137: 
 6138:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6139:     data file.
 6140: 
 6141:  Arguments:
 6142:     $scanlines - hash ref that looks like the first return value from
 6143:                  &scantron_getfile()
 6144:     $scan_data - hash ref that looks like the second return value from
 6145:                  &scantron_getfile()
 6146:     $i         - line number to update
 6147:     $newline   - contents of the updated scanline
 6148:     $skip      - if true make the line for skipping and update the
 6149:                  'skipped' file
 6150: 
 6151: =cut
 6152: 
 6153: sub scantron_put_line {
 6154:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6155:     if ($skip) {
 6156: 	$scanlines->{'skipped'}[$i]=$newline;
 6157: 	&start_skipping($scan_data,$i);
 6158: 	return;
 6159:     }
 6160:     $scanlines->{'corrected'}[$i]=$newline;
 6161: }
 6162: 
 6163: =pod
 6164: 
 6165: =item scantron_clear_skip
 6166: 
 6167:    Remove a line from the 'skipped' file
 6168: 
 6169:  Arguments:
 6170:     $scanlines - hash ref that looks like the first return value from
 6171:                  &scantron_getfile()
 6172:     $scan_data - hash ref that looks like the second return value from
 6173:                  &scantron_getfile()
 6174:     $i         - line number to update
 6175: 
 6176: =cut
 6177: 
 6178: sub scantron_clear_skip {
 6179:     my ($scanlines,$scan_data,$i)=@_;
 6180:     if (exists($scanlines->{'skipped'}[$i])) {
 6181: 	undef($scanlines->{'skipped'}[$i]);
 6182: 	return 1;
 6183:     }
 6184:     return 0;
 6185: }
 6186: 
 6187: =pod
 6188: 
 6189: =item scantron_filter_not_exam
 6190: 
 6191:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6192:    filter out resources that are not marked as 'exam' mode
 6193: 
 6194: =cut
 6195: 
 6196: sub scantron_filter_not_exam {
 6197:     my ($curres)=@_;
 6198:     
 6199:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6200: 	# if the user has asked to not have either hidden
 6201: 	# or 'randomout' controlled resources to be graded
 6202: 	# don't include them
 6203: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6204: 	    && $curres->randomout) {
 6205: 	    return 0;
 6206: 	}
 6207: 	return 1;
 6208:     }
 6209:     return 0;
 6210: }
 6211: 
 6212: =pod
 6213: 
 6214: =item scantron_validate_sequence
 6215: 
 6216:     Validates the selected sequence, checking for resource that are
 6217:     not set to exam mode.
 6218: 
 6219: =cut
 6220: 
 6221: sub scantron_validate_sequence {
 6222:     my ($r,$currentphase) = @_;
 6223: 
 6224:     my $navmap=Apache::lonnavmaps::navmap->new();
 6225:     my (undef,undef,$sequence)=
 6226: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6227: 
 6228:     my $map=$navmap->getResourceByUrl($sequence);
 6229: 
 6230:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6231:                                     value="ignore" />');
 6232:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6233: 	my @resources=
 6234: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6235: 	if (@resources) {
 6236: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
 6237: 	    return (1,$currentphase);
 6238: 	}
 6239:     }
 6240: 
 6241:     return (0,$currentphase+1);
 6242: }
 6243: 
 6244: =pod
 6245: 
 6246: =item scantron_validate_ID
 6247: 
 6248:    Validates all scanlines in the selected file to not have any
 6249:    invalid or underspecified student IDs
 6250: 
 6251: =cut
 6252: 
 6253: sub scantron_validate_ID {
 6254:     my ($r,$currentphase) = @_;
 6255:     
 6256:     #get student info
 6257:     my $classlist=&Apache::loncoursedata::get_classlist();
 6258:     my %idmap=&username_to_idmap($classlist);
 6259: 
 6260:     #get scantron line setup
 6261:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6262:     my ($scanlines,$scan_data)=&scantron_getfile();
 6263:     
 6264:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6265: 
 6266:     my %found=('ids'=>{},'usernames'=>{});
 6267:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6268: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6269: 	if ($line=~/^[\s\cz]*$/) { next; }
 6270: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6271: 						 $scan_data);
 6272: 	my $id=$$scan_record{'scantron.ID'};
 6273: 	my $found;
 6274: 	foreach my $checkid (keys(%idmap)) {
 6275: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6276: 	}
 6277: 	if ($found) {
 6278: 	    my $username=$idmap{$found};
 6279: 	    if ($found{'ids'}{$found}) {
 6280: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6281: 					 $line,'duplicateID',$found);
 6282: 		return(1,$currentphase);
 6283: 	    } elsif ($found{'usernames'}{$username}) {
 6284: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6285: 					 $line,'duplicateID',$username);
 6286: 		return(1,$currentphase);
 6287: 	    }
 6288: 	    #FIXME store away line we previously saw the ID on to use above
 6289: 	    $found{'ids'}{$found}++;
 6290: 	    $found{'usernames'}{$username}++;
 6291: 	} else {
 6292: 	    if ($id =~ /^\s*$/) {
 6293: 		my $username=&scan_data($scan_data,"$i.user");
 6294: 		if (defined($username) && $found{'usernames'}{$username}) {
 6295: 		    &scantron_get_correction($r,$i,$scan_record,
 6296: 					     \%scantron_config,
 6297: 					     $line,'duplicateID',$username);
 6298: 		    return(1,$currentphase);
 6299: 		} elsif (!defined($username)) {
 6300: 		    &scantron_get_correction($r,$i,$scan_record,
 6301: 					     \%scantron_config,
 6302: 					     $line,'incorrectID');
 6303: 		    return(1,$currentphase);
 6304: 		}
 6305: 		$found{'usernames'}{$username}++;
 6306: 	    } else {
 6307: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6308: 					 $line,'incorrectID');
 6309: 		return(1,$currentphase);
 6310: 	    }
 6311: 	}
 6312:     }
 6313: 
 6314:     return (0,$currentphase+1);
 6315: }
 6316: 
 6317: =pod
 6318: 
 6319: =item scantron_get_correction
 6320: 
 6321:    Builds the interface screen to interact with the operator to fix a
 6322:    specific error condition in a specific scanline
 6323: 
 6324:  Arguments:
 6325:     $r           - Apache request object
 6326:     $i           - number of the current scanline
 6327:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6328:     $scan_config - hash ref as returned from &get_scantron_config()
 6329:     $line        - full contents of the current scanline
 6330:     $error       - error condition, valid values are
 6331:                    'incorrectCODE', 'duplicateCODE',
 6332:                    'doublebubble', 'missingbubble',
 6333:                    'duplicateID', 'incorrectID'
 6334:     $arg         - extra information needed
 6335:        For errors:
 6336:          - duplicateID   - paper number that this studentID was seen before on
 6337:          - duplicateCODE - array ref of the paper numbers this CODE was
 6338:                            seen on before
 6339:          - incorrectCODE - current incorrect CODE 
 6340:          - doublebubble  - array ref of the bubble lines that have double
 6341:                            bubble errors
 6342:          - missingbubble - array ref of the bubble lines that have missing
 6343:                            bubble errors
 6344: 
 6345: =cut
 6346: 
 6347: sub scantron_get_correction {
 6348:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6349: 
 6350: #FIXME in the case of a duplicated ID the previous line, probably need
 6351: #to show both the current line and the previous one and allow skipping
 6352: #the previous one or the current one
 6353: 
 6354:     $r->print("<p><b>An error was detected ($error)</b>");
 6355:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6356: 	$r->print(" for PaperID <tt>".
 6357: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
 6358:     } else {
 6359: 	$r->print(" in scanline $i <pre>".
 6360: 		  $line."</pre> \n");
 6361:     }
 6362:     my $message="<p>The ID on the form is  <tt>".
 6363: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
 6364: 	"The name on the paper is ".
 6365: 	$$scan_record{'scantron.LastName'}.",".
 6366: 	$$scan_record{'scantron.FirstName'}."</p>";
 6367: 
 6368:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6369:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6370:     if ($error =~ /ID$/) {
 6371: 	if ($error eq 'incorrectID') {
 6372: 	    $r->print("The encoded ID is not in the classlist</p>\n");
 6373: 	} elsif ($error eq 'duplicateID') {
 6374: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
 6375: 	}
 6376: 	$r->print($message);
 6377: 	$r->print("<p>How should I handle this? <br /> \n");
 6378: 	$r->print("\n<ul><li> ");
 6379: 	#FIXME it would be nice if this sent back the user ID and
 6380: 	#could do partial userID matches
 6381: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6382: 				       'scantron_username','scantron_domain'));
 6383: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6384: 	$r->print("\n@".
 6385: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6386: 
 6387: 	$r->print('</li>');
 6388:     } elsif ($error =~ /CODE$/) {
 6389: 	if ($error eq 'incorrectCODE') {
 6390: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
 6391: 	} elsif ($error eq 'duplicateCODE') {
 6392: 	    $r->print("</p><p>The encoded CODE has also been used by a previous paper ".join(', ',@{$arg}).", and CODEs are supposed to be unique</p>\n");
 6393: 	}
 6394: 	$r->print("<p>The CODE on the form is  <tt>'".
 6395: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
 6396: 	$r->print($message);
 6397: 	$r->print("<p>How should I handle this? <br /> \n");
 6398: 	$r->print("\n<br /> ");
 6399: 	my $i=0;
 6400: 	if ($error eq 'incorrectCODE' 
 6401: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6402: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6403: 	    if ($closest > 0) {
 6404: 		foreach my $testcode (@{$closest}) {
 6405: 		    my $checked='';
 6406: 		    if (!$i) { $checked=' checked="checked" '; }
 6407: 		    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked /> Use the similar CODE <b><tt>".$testcode."</tt></b> instead.</label><input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6408: 		    $r->print("\n<br />");
 6409: 		    $i++;
 6410: 		}
 6411: 	    }
 6412: 	}
 6413: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6414: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6415: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked /> Use the CODE <b><tt>".$$scan_record{'scantron.CODE'}."</tt></b> that is was on the paper, ignoring the error.</label>");
 6416: 	    $r->print("\n<br />");
 6417: 	}
 6418: 
 6419: 	$r->print(<<ENDSCRIPT);
 6420: <script type="text/javascript">
 6421: function change_radio(field) {
 6422:     var slct=document.scantronupload.scantron_CODE_resolution;
 6423:     var i;
 6424:     for (i=0;i<slct.length;i++) {
 6425:         if (slct[i].value==field) { slct[i].checked=true; }
 6426:     }
 6427: }
 6428: </script>
 6429: ENDSCRIPT
 6430: 	my $href="/adm/pickcode?".
 6431: 	   "form=".&escape("scantronupload").
 6432: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6433: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6434: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6435: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6436: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6437: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_found' /> <a target='_blank' href='$href'>Select</a> a CODE from the list of all CODEs and use it.</label> Selected CODE is <input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />");
 6438: 	    $r->print("\n<br />");
 6439: 	}
 6440: 	$r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_typed' /> Use </label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" /> as the CODE.");
 6441: 	$r->print("\n<br /><br />");
 6442:     } elsif ($error eq 'doublebubble') {
 6443: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
 6444: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6445: 		  join(',',@{$arg}).'" />');
 6446: 	$r->print($message);
 6447: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 6448: 	foreach my $question (@{$arg}) {
 6449: 	    my $selected  = &get_response_bubbles($scan_record, $question);
 6450: 	    my @select_array = split(/:/,$selected);
 6451: 	    &scantron_bubble_selector($r,$scan_config,$question,
 6452: 				      @select_array);
 6453: 	}
 6454:     } elsif ($error eq 'missingbubble') {
 6455: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
 6456: 	$r->print($message);
 6457: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 6458: 	$r->print("Some questions have no scanned bubbles\n");
 6459: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6460: 		  join(',',@{$arg}).'" />');
 6461: 	foreach my $question (@{$arg}) {
 6462: 	    my $selected = &get_response_bubbles($scan_record, $question);
 6463: 	    &scantron_bubble_selector($r,$scan_config,$question);
 6464: 	}
 6465:     } else {
 6466: 	$r->print("\n<ul>");
 6467:     }
 6468:     $r->print("\n</li></ul>");
 6469: 
 6470: }
 6471: 
 6472: =pod
 6473: 
 6474: =item scantron_bubble_selector
 6475:   
 6476:    Generates the html radiobuttons to correct a single bubble line
 6477:    possibly showing the existing the selected bubbles if known
 6478: 
 6479:  Arguments:
 6480:     $r           - Apache request object
 6481:     $scan_config - hash from &get_scantron_config()
 6482:     $quest       - number of the bubble line to make a corrector for
 6483:     $lines       - array of answer lines.
 6484: 
 6485: =cut
 6486: 
 6487: sub scantron_bubble_selector {
 6488:     my ($r,$scan_config,$quest,@lines)=@_;
 6489:     my $max=$$scan_config{'Qlength'};
 6490: 
 6491: 
 6492:     my $scmode=$$scan_config{'Qon'};
 6493: 
 6494:     my $bubble_length = scalar(@lines);
 6495: 
 6496: 
 6497:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 6498: 
 6499:     my $response = $quest-1;
 6500:     my $lines = $bubble_lines_per_response{$response};
 6501: 
 6502:     my $total_lines = $lines*2;
 6503:     my @alphabet=('A'..'Z');
 6504:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
 6505: 
 6506:     for (my $l = 0; $l < $lines; $l++) {
 6507: 	if ($l != 0) {
 6508: 	    $r->print('<tr>');
 6509: 	}
 6510: 	my @selected = split(//,$lines[$l]);
 6511: 	for (my $i=0;$i<$max;$i++) {
 6512: 	    $r->print("\n".'<td align="center">');
 6513: 	    if ($selected[0] eq $alphabet[$i]) { 
 6514: 		$r->print('X'); 
 6515: 		shift(@selected) ;
 6516: 	    } else { 
 6517: 		$r->print('&nbsp;'); 
 6518: 	    }
 6519: 	    $r->print('</td>');
 6520: 	    
 6521: 	}
 6522: 
 6523: 	if ($l == 0) {
 6524: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
 6525: 
 6526: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
 6527: 	      $quest.'" value="none" /> No bubble </label></td>');
 6528: 	
 6529: 	}
 6530: 
 6531: 	$r->print('</tr><tr>');
 6532: 
 6533: 	# FIXME: This may have to be a bit more clever for
 6534: 	#        multiline questions (different values e.g..).
 6535: 
 6536: 	for (my $i=0;$i<$max;$i++) {
 6537: 	    $r->print("\n".
 6538: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
 6539: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 6540: 	}
 6541: 	$r->print('</tr>');
 6542: 
 6543: 	    
 6544:     }
 6545:     $r->print('</table>');
 6546: }
 6547: 
 6548: =pod
 6549: 
 6550: =item num_matches
 6551: 
 6552:    Counts the number of characters that are the same between the two arguments.
 6553: 
 6554:  Arguments:
 6555:    $orig - CODE from the scanline
 6556:    $code - CODE to match against
 6557: 
 6558:  Returns:
 6559:    $count - integer count of the number of same characters between the
 6560:             two arguments
 6561: 
 6562: =cut
 6563: 
 6564: sub num_matches {
 6565:     my ($orig,$code) = @_;
 6566:     my @code=split(//,$code);
 6567:     my @orig=split(//,$orig);
 6568:     my $same=0;
 6569:     for (my $i=0;$i<scalar(@code);$i++) {
 6570: 	if ($code[$i] eq $orig[$i]) { $same++; }
 6571:     }
 6572:     return $same;
 6573: }
 6574: 
 6575: =pod
 6576: 
 6577: =item scantron_get_closely_matching_CODEs
 6578: 
 6579:    Cycles through all CODEs and finds the set that has the greatest
 6580:    number of same characters as the provided CODE
 6581: 
 6582:  Arguments:
 6583:    $allcodes - hash ref returned by &get_codes()
 6584:    $CODE     - CODE from the current scanline
 6585: 
 6586:  Returns:
 6587:    2 element list
 6588:     - first elements is number of how closely matching the best fit is 
 6589:       (5 means best set has 5 matching characters)
 6590:     - second element is an arrary ref containing the set of valid CODEs
 6591:       that best fit the passed in CODE
 6592: 
 6593: =cut
 6594: 
 6595: sub scantron_get_closely_matching_CODEs {
 6596:     my ($allcodes,$CODE)=@_;
 6597:     my @CODEs;
 6598:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 6599: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 6600:     }
 6601: 
 6602:     return ($#CODEs,$CODEs[-1]);
 6603: }
 6604: 
 6605: =pod
 6606: 
 6607: =item get_codes
 6608: 
 6609:    Builds a hash which has keys of all of the valid CODEs from the selected
 6610:    set of remembered CODEs.
 6611: 
 6612:  Arguments:
 6613:   $old_name - name of the set of remembered CODEs
 6614:   $cdom     - domain of the course
 6615:   $cnum     - internal course name
 6616: 
 6617:  Returns:
 6618:   %allcodes - keys are the valid CODEs, values are all 1
 6619: 
 6620: =cut
 6621: 
 6622: sub get_codes {
 6623:     my ($old_name, $cdom, $cnum) = @_;
 6624:     if (!$old_name) {
 6625: 	$old_name=$env{'form.scantron_CODElist'};
 6626:     }
 6627:     if (!$cdom) {
 6628: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 6629:     }
 6630:     if (!$cnum) {
 6631: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 6632:     }
 6633:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 6634: 				    $cdom,$cnum);
 6635:     my %allcodes;
 6636:     if ($result{"type\0$old_name"} eq 'number') {
 6637: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 6638:     } else {
 6639: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 6640:     }
 6641:     return %allcodes;
 6642: }
 6643: 
 6644: =pod
 6645: 
 6646: =item scantron_validate_CODE
 6647: 
 6648:    Validates all scanlines in the selected file to not have any
 6649:    invalid or underspecified CODEs and that none of the codes are
 6650:    duplicated if this was requested.
 6651: 
 6652: =cut
 6653: 
 6654: sub scantron_validate_CODE {
 6655:     my ($r,$currentphase) = @_;
 6656:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6657:     if ($scantron_config{'CODElocation'} &&
 6658: 	$scantron_config{'CODEstart'} &&
 6659: 	$scantron_config{'CODElength'}) {
 6660: 	if (!defined($env{'form.scantron_CODElist'})) {
 6661: 	    &FIXME_blow_up()
 6662: 	}
 6663:     } else {
 6664: 	return (0,$currentphase+1);
 6665:     }
 6666:     
 6667:     my %usedCODEs;
 6668: 
 6669:     my %allcodes=&get_codes();
 6670: 
 6671:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 6672: 
 6673:     my ($scanlines,$scan_data)=&scantron_getfile();
 6674:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6675: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6676: 	if ($line=~/^[\s\cz]*$/) { next; }
 6677: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6678: 						 $scan_data);
 6679: 	my $CODE=$$scan_record{'scantron.CODE'};
 6680: 	my $error=0;
 6681: 	if (!&Apache::lonnet::validCODE($CODE)) {
 6682: 	    &scantron_get_correction($r,$i,$scan_record,
 6683: 				     \%scantron_config,
 6684: 				     $line,'incorrectCODE',\%allcodes);
 6685: 	    return(1,$currentphase);
 6686: 	}
 6687: 	if (%allcodes && !exists($allcodes{$CODE}) 
 6688: 	    && !$$scan_record{'scantron.useCODE'}) {
 6689: 	    &scantron_get_correction($r,$i,$scan_record,
 6690: 				     \%scantron_config,
 6691: 				     $line,'incorrectCODE',\%allcodes);
 6692: 	    return(1,$currentphase);
 6693: 	}
 6694: 	if (exists($usedCODEs{$CODE}) 
 6695: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 6696: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 6697: 	    &scantron_get_correction($r,$i,$scan_record,
 6698: 				     \%scantron_config,
 6699: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 6700: 	    return(1,$currentphase);
 6701: 	}
 6702: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 6703:     }
 6704:     return (0,$currentphase+1);
 6705: }
 6706: 
 6707: =pod
 6708: 
 6709: =item scantron_validate_doublebubble
 6710: 
 6711:    Validates all scanlines in the selected file to not have any
 6712:    bubble lines with multiple bubbles marked.
 6713: 
 6714: =cut
 6715: 
 6716: sub scantron_validate_doublebubble {
 6717:     my ($r,$currentphase) = @_;
 6718:     #get student info
 6719:     my $classlist=&Apache::loncoursedata::get_classlist();
 6720:     my %idmap=&username_to_idmap($classlist);
 6721: 
 6722:     #get scantron line setup
 6723:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6724:     my ($scanlines,$scan_data)=&scantron_getfile();
 6725: 
 6726:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 6727: 
 6728:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6729: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6730: 	if ($line=~/^[\s\cz]*$/) { next; }
 6731: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6732: 						 $scan_data);
 6733: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 6734: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 6735: 				 'doublebubble',
 6736: 				 $$scan_record{'scantron.doubleerror'});
 6737:     	return (1,$currentphase);
 6738:     }
 6739:     return (0,$currentphase+1);
 6740: }
 6741: 
 6742: =pod
 6743: 
 6744: =item scantron_get_maxbubble
 6745: 
 6746:    Returns the maximum number of bubble lines that are expected to
 6747:    occur. Does this by walking the selected sequence rendering the
 6748:    resource and then checking &Apache::lonxml::get_problem_counter()
 6749:    for what the current value of the problem counter is.
 6750: 
 6751:    Caches the results to $env{'form.scantron_maxbubble'},
 6752:    $env{'form.scantron.bubble_lines.n'} and 
 6753:    $env{'form.scantron.first_bubble_line.n'}
 6754:    which are the total number of bubble, lines, the number of bubble
 6755:    lines for reponse n and number of the first bubble line for response n.
 6756: 
 6757: =cut
 6758: 
 6759: sub scantron_get_maxbubble {    
 6760:     if (defined($env{'form.scantron_maxbubble'}) &&
 6761: 	$env{'form.scantron_maxbubble'}) {
 6762: 	&restore_bubble_lines();
 6763: 	return $env{'form.scantron_maxbubble'};
 6764:     }
 6765: 
 6766:     my (undef, undef, $sequence) =
 6767: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6768: 
 6769:     my $navmap=Apache::lonnavmaps::navmap->new();
 6770:     my $map=$navmap->getResourceByUrl($sequence);
 6771:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 6772: 
 6773:     &Apache::lonxml::clear_problem_counter();
 6774: 
 6775:     my $uname       = $env{'form.student'};
 6776:     my $udom        = $env{'form.userdom'};
 6777:     my $cid         = $env{'request.course.id'};
 6778:     my $total_lines = 0;
 6779:     %bubble_lines_per_response = ();
 6780:     %first_bubble_line         = ();
 6781: 
 6782:   
 6783:     my $response_number = 0;
 6784:     my $bubble_line     = 0;
 6785:     foreach my $resource (@resources) {
 6786: 	my $symb = $resource->symb();
 6787: 	&Apache::lonxml::clear_bubble_lines_for_part();
 6788: 	my $result=&Apache::lonnet::ssi($resource->src(),
 6789: 					('symb' => $resource->symb()),
 6790: 					('grade_target' => 'analyze'),
 6791: 					('grade_courseid' => $cid),
 6792: 					('grade_domain' => $udom),
 6793: 					('grade_username' => $uname));
 6794: 	my (undef, $an) =
 6795: 	    split(/_HASH_REF__/,$result, 2);
 6796: 
 6797: 	my %analysis = &Apache::lonnet::str2hash($an);
 6798: 
 6799: 
 6800: 
 6801: 	foreach my $part_id (@{$analysis{'parts'}}) {
 6802: 
 6803: 
 6804: 	    my $lines = $analysis{"$part_id.bubble_lines"};;
 6805: 
 6806: 	    # TODO - make this a persistent hash not an array.
 6807: 
 6808: 
 6809: 	    $first_bubble_line{$response_number}           = $bubble_line;
 6810: 	    $bubble_lines_per_response{$response_number}   = $lines;
 6811: 	    $response_number++;
 6812: 
 6813: 	    $bubble_line +=  $lines;
 6814: 	    $total_lines +=  $lines;
 6815: 	}
 6816: 
 6817:     }
 6818:     &Apache::lonnet::delenv('scantron\.');
 6819: 
 6820:     &save_bubble_lines();
 6821:     $env{'form.scantron_maxbubble'} =
 6822: 	$total_lines;
 6823:     return $env{'form.scantron_maxbubble'};
 6824: }
 6825: 
 6826: =pod
 6827: 
 6828: =item scantron_validate_missingbubbles
 6829: 
 6830:    Validates all scanlines in the selected file to not have any
 6831:     answers that don't have bubbles that have not been verified
 6832:     to be bubble free.
 6833: 
 6834: =cut
 6835: 
 6836: sub scantron_validate_missingbubbles {
 6837:     my ($r,$currentphase) = @_;
 6838:     #get student info
 6839:     my $classlist=&Apache::loncoursedata::get_classlist();
 6840:     my %idmap=&username_to_idmap($classlist);
 6841: 
 6842:     #get scantron line setup
 6843:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6844:     my ($scanlines,$scan_data)=&scantron_getfile();
 6845:     my $max_bubble=&scantron_get_maxbubble();
 6846:     if (!$max_bubble) { $max_bubble=2**31; }
 6847:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6848: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6849: 	if ($line=~/^[\s\cz]*$/) { next; }
 6850: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6851: 						 $scan_data);
 6852: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 6853: 	my @to_correct;
 6854: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 6855: 	    if ($missing > $max_bubble) { next; }
 6856: 	    push(@to_correct,$missing);
 6857: 	}
 6858: 	if (@to_correct) {
 6859: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6860: 				     $line,'missingbubble',\@to_correct);
 6861: 	    return (1,$currentphase);
 6862: 	}
 6863: 
 6864:     }
 6865:     return (0,$currentphase+1);
 6866: }
 6867: 
 6868: =pod
 6869: 
 6870: =item scantron_process_students
 6871: 
 6872:    Routine that does the actual grading of the bubble sheet information.
 6873: 
 6874:    The parsed scanline hash is added to %env 
 6875: 
 6876:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 6877:    foreach resource , with the form data of
 6878: 
 6879: 	'submitted'     =>'scantron' 
 6880: 	'grade_target'  =>'grade',
 6881: 	'grade_username'=> username of student
 6882: 	'grade_domain'  => domain of student
 6883: 	'grade_courseid'=> of course
 6884: 	'grade_symb'    => symb of resource to grade
 6885: 
 6886:     This triggers a grading pass. The problem grading code takes care
 6887:     of converting the bubbled letter information (now in %env) into a
 6888:     valid submission.
 6889: 
 6890: =cut
 6891: 
 6892: sub scantron_process_students {
 6893:     my ($r) = @_;
 6894:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6895:     my ($symb)=&get_symb($r);
 6896:     if (!$symb) {return '';}
 6897:     my $default_form_data=&defaultFormData($symb);
 6898: 
 6899:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6900:     my ($scanlines,$scan_data)=&scantron_getfile();
 6901:     my $classlist=&Apache::loncoursedata::get_classlist();
 6902:     my %idmap=&username_to_idmap($classlist);
 6903:     my $navmap=Apache::lonnavmaps::navmap->new();
 6904:     my $map=$navmap->getResourceByUrl($sequence);
 6905:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 6906: #    $r->print("geto ".scalar(@resources)."<br />");
 6907:     my $result= <<SCANTRONFORM;
 6908: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6909:   <input type="hidden" name="command" value="scantron_configphase" />
 6910:   $default_form_data
 6911: SCANTRONFORM
 6912:     $r->print($result);
 6913: 
 6914:     my @delayqueue;
 6915:     my %completedstudents;
 6916:     
 6917:     my $count=&get_todo_count($scanlines,$scan_data);
 6918:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 6919:  				    'Scantron Progress',$count,
 6920: 				    'inline',undef,'scantronupload');
 6921:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 6922: 					  'Processing first student');
 6923:     my $start=&Time::HiRes::time();
 6924:     my $i=-1;
 6925:     my ($uname,$udom,$started);
 6926: 
 6927:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 6928: 
 6929:     while ($i<$scanlines->{'count'}) {
 6930:  	($uname,$udom)=('','');
 6931:  	$i++;
 6932:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6933:  	if ($line=~/^[\s\cz]*$/) { next; }
 6934: 	if ($started) {
 6935: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 6936: 						     'last student');
 6937: 	}
 6938: 	$started=1;
 6939:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6940:  						 $scan_data);
 6941:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 6942:  					      \%idmap,$i)) {
 6943:   	    &scantron_add_delay(\@delayqueue,$line,
 6944:  				'Unable to find a student that matches',1);
 6945:  	    next;
 6946:   	}
 6947:  	if (exists $completedstudents{$uname}) {
 6948:  	    &scantron_add_delay(\@delayqueue,$line,
 6949:  				'Student '.$uname.' has multiple sheets',2);
 6950:  	    next;
 6951:  	}
 6952:   	($uname,$udom)=split(/:/,$uname);
 6953: 
 6954: 	&Apache::lonxml::clear_problem_counter();
 6955:   	&Apache::lonnet::appenv(%$scan_record);
 6956: 
 6957: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 6958: 	    &scantron_putfile($scanlines,$scan_data);
 6959: 	}
 6960: 	
 6961: 	my $i=0;
 6962: 	foreach my $resource (@resources) {
 6963: 	    $i++;
 6964: 	    my %form=('submitted'     =>'scantron',
 6965: 		      'grade_target'  =>'grade',
 6966: 		      'grade_username'=>$uname,
 6967: 		      'grade_domain'  =>$udom,
 6968: 		      'grade_courseid'=>$env{'request.course.id'},
 6969: 		      'grade_symb'    =>$resource->symb());
 6970: 	    if (exists($scan_record->{'scantron.CODE'})
 6971: 		&& 
 6972: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
 6973: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 6974: 	    } else {
 6975: 		$form{'CODE'}='';
 6976: 	    }
 6977: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
 6978: 	    if ($result ne '') {
 6979: 	    }
 6980: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 6981: 	}
 6982: 	$completedstudents{$uname}={'line'=>$line};
 6983: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 6984:     } continue {
 6985: 	&Apache::lonxml::clear_problem_counter();
 6986: 	&Apache::lonnet::delenv('scantron\.');
 6987:     }
 6988:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 6989: #    my $lasttime = &Time::HiRes::time()-$start;
 6990: #    $r->print("<p>took $lasttime</p>");
 6991: 
 6992:     $r->print("</form>");
 6993:     $r->print(&show_grading_menu_form($symb));
 6994:     return '';
 6995: }
 6996: 
 6997: =pod
 6998: 
 6999: =item scantron_upload_scantron_data
 7000: 
 7001:     Creates the screen for adding a new bubble sheet data file to a course.
 7002: 
 7003: =cut
 7004: 
 7005: sub scantron_upload_scantron_data {
 7006:     my ($r)=@_;
 7007:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7008:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7009: 							  'domainid',
 7010: 							  'coursename');
 7011:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7012: 						   'domainid');
 7013:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7014:     $r->print(<<UPLOAD);
 7015: <script type="text/javascript" language="javascript">
 7016:     function checkUpload(formname) {
 7017: 	if (formname.upfile.value == "") {
 7018: 	    alert("Please use the browse button to select a file from your local directory.");
 7019: 	    return false;
 7020: 	}
 7021: 	formname.submit();
 7022:     }
 7023: </script>
 7024: 
 7025: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 7026: $default_form_data
 7027: <table>
 7028: <tr><td>$select_link </td></tr>
 7029: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
 7030: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
 7031: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
 7032: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
 7033: </table>
 7034: <input name='command' value='scantronupload_save' type='hidden' />
 7035: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 7036: </form>
 7037: UPLOAD
 7038:     return '';
 7039: }
 7040: 
 7041: =pod
 7042: 
 7043: =item scantron_upload_scantron_data_save
 7044: 
 7045:    Adds a provided bubble information data file to the course if user
 7046:    has the correct privileges to do so.  
 7047: 
 7048: =cut
 7049: 
 7050: sub scantron_upload_scantron_data_save {
 7051:     my($r)=@_;
 7052:     my ($symb)=&get_symb($r,1);
 7053:     my $doanotherupload=
 7054: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7055: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7056: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
 7057: 	'</form>'."\n";
 7058:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7059: 	!&Apache::lonnet::allowed('usc',
 7060: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7061: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
 7062: 	if ($symb) {
 7063: 	    $r->print(&show_grading_menu_form($symb));
 7064: 	} else {
 7065: 	    $r->print($doanotherupload);
 7066: 	}
 7067: 	return '';
 7068:     }
 7069:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7070:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
 7071:     my $fname=$env{'form.upfile.filename'};
 7072:     #FIXME
 7073:     #copied from lonnet::userfileupload()
 7074:     #make that function able to target a specified course
 7075:     # Replace Windows backslashes by forward slashes
 7076:     $fname=~s/\\/\//g;
 7077:     # Get rid of everything but the actual filename
 7078:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7079:     # Replace spaces by underscores
 7080:     $fname=~s/\s+/\_/g;
 7081:     # Replace all other weird characters by nothing
 7082:     $fname=~s/[^\w\.\-]//g;
 7083:     # See if there is anything left
 7084:     unless ($fname) { return 'error: no uploaded file'; }
 7085:     my $uploadedfile=$fname;
 7086:     $fname='scantron_orig_'.$fname;
 7087:     if (length($env{'form.upfile'}) < 2) {
 7088: 	$r->print("<span class=\"LC_error\">Error:</span> The file you attempted to upload, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>, contained no information. Please check that you entered the correct filename.");
 7089:     } else {
 7090: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7091: 	if ($result =~ m|^/uploaded/|) {
 7092: 	    $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
 7093: 	} else {
 7094: 	    $r->print("<span class=\"LC_error\">Error:</span> An error (".$result.") occurred when attempting to upload the file, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>");
 7095: 	}
 7096:     }
 7097:     if ($symb) {
 7098: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7099:     } else {
 7100: 	$r->print($doanotherupload);
 7101:     }
 7102:     return '';
 7103: }
 7104: 
 7105: =pod
 7106: 
 7107: =item valid_file
 7108: 
 7109:    Validates that the requested bubble data file exists in the course.
 7110: 
 7111: =cut
 7112: 
 7113: sub valid_file {
 7114:     my ($requested_file)=@_;
 7115:     foreach my $filename (sort(&scantron_filenames())) {
 7116: 	if ($requested_file eq $filename) { return 1; }
 7117:     }
 7118:     return 0;
 7119: }
 7120: 
 7121: =pod
 7122: 
 7123: =item scantron_download_scantron_data
 7124: 
 7125:    Shows a list of the three internal files (original, corrected,
 7126:    skipped) for a specific bubble sheet data file that exists in the
 7127:    course.
 7128: 
 7129: =cut
 7130: 
 7131: sub scantron_download_scantron_data {
 7132:     my ($r)=@_;
 7133:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7134:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7135:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7136:     my $file=$env{'form.scantron_selectfile'};
 7137:     if (! &valid_file($file)) {
 7138: 	$r->print(<<ERROR);
 7139: 	<p>
 7140: 	    The requested file name was invalid.
 7141:         </p>
 7142: ERROR
 7143: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7144: 	return;
 7145:     }
 7146:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7147:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7148:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7149:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7150:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7151:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7152:     $r->print(<<DOWNLOAD);
 7153:     <p>
 7154: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
 7155:     </p>
 7156:     <p>
 7157: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
 7158:     </p>
 7159:     <p>
 7160: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
 7161:     </p>
 7162: DOWNLOAD
 7163:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7164:     return '';
 7165: }
 7166: 
 7167: =pod
 7168: 
 7169: =back
 7170: 
 7171: =cut
 7172: 
 7173: #-------- end of section for handling grading scantron forms -------
 7174: #
 7175: #-------------------------------------------------------------------
 7176: 
 7177: #-------------------------- Menu interface -------------------------
 7178: #
 7179: #--- Show a Grading Menu button - Calls the next routine ---
 7180: sub show_grading_menu_form {
 7181:     my ($symb)=@_;
 7182:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 7183: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7184: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 7185: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 7186: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
 7187: 	'</form>'."\n";
 7188:     return $result;
 7189: }
 7190: 
 7191: # -- Retrieve choices for grading form
 7192: sub savedState {
 7193:     my %savedState = ();
 7194:     if ($env{'form.saveState'}) {
 7195: 	foreach (split(/:/,$env{'form.saveState'})) {
 7196: 	    my ($key,$value) = split(/=/,$_,2);
 7197: 	    $savedState{$key} = $value;
 7198: 	}
 7199:     }
 7200:     return \%savedState;
 7201: }
 7202: 
 7203: sub grading_menu {
 7204:     my ($request) = @_;
 7205:     my ($symb)=&get_symb($request);
 7206:     if (!$symb) {return '';}
 7207:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7208:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7209: 
 7210:     $request->print($table);
 7211:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 7212:                   'handgrade'=>$hdgrade,
 7213:                   'probTitle'=>$probTitle,
 7214:                   'command'=>'submit_options',
 7215:                   'saveState'=>"",
 7216:                   'gradingMenu'=>1,
 7217:                   'showgrading'=>"yes");
 7218:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7219:     my @menu = ({ url => $url,
 7220:                      name => &mt('Manual Grading/View Submissions'),
 7221:                      short_description => 
 7222:     &mt('Start the process of hand grading submissions.'),
 7223:                  });
 7224:     $fields{'command'} = 'csvform';
 7225:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7226:     push (@menu, { url => $url,
 7227:                    name => &mt('Upload Scores'),
 7228:                    short_description => 
 7229:             &mt('Specify a file containing the class scores for current resource.')});
 7230:     $fields{'command'} = 'processclicker';
 7231:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7232:     push (@menu, { url => $url,
 7233:                    name => &mt('Process Clicker'),
 7234:                    short_description => 
 7235:             &mt('Specify a file containing the clicker information for this resource.')});
 7236:     $fields{'command'} = 'scantron_selectphase';
 7237:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7238:     push (@menu, { url => $url,
 7239:                    name => &mt('Grade/Manage Scantron Forms'),
 7240:                    short_description => 
 7241:             &mt('')});
 7242:     $fields{'command'} = 'verify';
 7243:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7244:     push (@menu, { url => "",
 7245:                    name => &mt('Verify Receipt'),
 7246:                    short_description => 
 7247:             &mt('')});
 7248:     #
 7249:     # Create the menu
 7250:     my $Str;
 7251:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 7252:     $Str .= '<form method="post" action="" name="gradingMenu">';
 7253:     $Str .= '<input type="hidden" name="command" value="" />'.
 7254:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7255: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7256: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
 7257: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7258: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7259: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7260: 
 7261:     foreach my $menudata (@menu) {
 7262:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 7263:             $Str .='    <h3><a '.
 7264:                 $menudata->{'jscript'}.
 7265:                 ' href="'.
 7266:                 $menudata->{'url'}.'" >'.
 7267:                 $menudata->{'name'}."</a></h3>\n";
 7268:         } else {
 7269:             $Str .='    <h3><input type="button" value="Verify Receipt" '.
 7270:                 $menudata->{'jscript'}.
 7271:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 7272:                 ' /></h3>';
 7273:             $Str .= ('&nbsp;'x8).
 7274:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
 7275:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 7276:         }
 7277:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 7278:             "\n";
 7279:     }
 7280:     $Str .="</dl>\n";
 7281:     $Str .="</form>\n";
 7282:     $request->print(<<GRADINGMENUJS);
 7283: <script type="text/javascript" language="javascript">
 7284:     function checkChoice(formname,val,cmdx) {
 7285: 	if (val <= 2) {
 7286: 	    var cmd = radioSelection(formname.radioChoice);
 7287: 	    var cmdsave = cmd;
 7288: 	} else {
 7289: 	    cmd = cmdx;
 7290: 	    cmdsave = 'submission';
 7291: 	}
 7292: 	formname.command.value = cmd;
 7293: 	if (val < 5) formname.submit();
 7294: 	if (val == 5) {
 7295: 	    if (!checkReceiptNo(formname,'notOK')) { 
 7296: 	        return false;
 7297: 	    } else {
 7298: 	        formname.submit();
 7299: 	    }
 7300: 	}
 7301:     }
 7302: 
 7303:     function checkReceiptNo(formname,nospace) {
 7304: 	var receiptNo = formname.receipt.value;
 7305: 	var checkOpt = false;
 7306: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7307: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7308: 	if (checkOpt) {
 7309: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7310: 	    formname.receipt.value = "";
 7311: 	    formname.receipt.focus();
 7312: 	    return false;
 7313: 	}
 7314: 	return true;
 7315:     }
 7316: </script>
 7317: GRADINGMENUJS
 7318:     &commonJSfunctions($request);
 7319:     return $Str;    
 7320: }
 7321: 
 7322: 
 7323: #--- Displays the submissions first page -------
 7324: sub submit_options {
 7325:     my ($request) = @_;
 7326:     my ($symb)=&get_symb($request);
 7327:     if (!$symb) {return '';}
 7328:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7329: 
 7330:     $request->print(<<GRADINGMENUJS);
 7331: <script type="text/javascript" language="javascript">
 7332:     function checkChoice(formname,val,cmdx) {
 7333: 	if (val <= 2) {
 7334: 	    var cmd = radioSelection(formname.radioChoice);
 7335: 	    var cmdsave = cmd;
 7336: 	} else {
 7337: 	    cmd = cmdx;
 7338: 	    cmdsave = 'submission';
 7339: 	}
 7340: 	formname.command.value = cmd;
 7341: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 7342: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 7343: 	if (val < 5) formname.submit();
 7344: 	if (val == 5) {
 7345: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7346: 	    formname.submit();
 7347: 	}
 7348: 	if (val < 7) formname.submit();
 7349:     }
 7350: 
 7351:     function checkReceiptNo(formname,nospace) {
 7352: 	var receiptNo = formname.receipt.value;
 7353: 	var checkOpt = false;
 7354: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7355: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7356: 	if (checkOpt) {
 7357: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7358: 	    formname.receipt.value = "";
 7359: 	    formname.receipt.focus();
 7360: 	    return false;
 7361: 	}
 7362: 	return true;
 7363:     }
 7364: </script>
 7365: GRADINGMENUJS
 7366:     &commonJSfunctions($request);
 7367:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
 7368:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7369:     $result.=$table;
 7370:     my (undef,$sections) = &getclasslist('all','0');
 7371:     my $savedState = &savedState();
 7372:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 7373:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 7374:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 7375:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 7376: 
 7377:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 7378: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7379: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7380: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 7381: 	'<input type="hidden" name="command"     value="" />'."\n".
 7382: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7383: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7384: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7385: 
 7386:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
 7387: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
 7388: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
 7389: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
 7390: 
 7391:     $result.='<table width="100%" border="0">';
 7392:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
 7393:     $result.='<td><b>'.&mt('Sections').'</b></td>';
 7394:     $result.='<td><b>'.&mt('Groups').'</b></td>';
 7395:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
 7396:     $result.='<td><b>'.&mt('Submission Status').'</td>'."\n";
 7397:     $result.='</tr>';
 7398:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
 7399: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
 7400:     if (ref($sections)) {
 7401: 	foreach (sort (@$sections)) {
 7402: 	    $result.='<option value="'.$_.'" '.
 7403: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
 7404: 	}
 7405:     }
 7406:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 7407:     $result.= '</td><td>'."\n";
 7408:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
 7409:     $result.='</td><td>'."\n";
 7410:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
 7411: 
 7412:     $result.='</td>';
 7413:     $result.='<td><select name="submitonly" size="3">'.
 7414: 	'<option value="yes" '.
 7415: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
 7416: 	'<option value="queued" '.
 7417: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
 7418: 	'<option value="graded" '.
 7419: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
 7420: 	'<option value="incorrect" '.
 7421: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
 7422: 	'<option value="all" '.
 7423: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>';
 7424: 
 7425:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
 7426: 	'<input type="radio" name="radioChoice" value="submission" '.
 7427: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
 7428: 	'</label> </td></tr>'."\n";
 7429: 
 7430:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3">'.
 7431: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
 7432: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 7433: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
 7434: 
 7435:     $result.='<tr bgcolor="#ffffe6"><td colspan="3"><br />'.
 7436: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
 7437: 	'</td></tr>'."\n";
 7438: 
 7439: 
 7440:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="3">'.
 7441: 	'<br /><label><input type="radio" name="radioChoice" value="pickStudentPage" '.
 7442: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 7443: 	'The <b>complete</b> set/page/sequence/folder: For one student</label></td></tr>'."\n";
 7444: 
 7445:     $result.='<tr bgcolor="#ffffe6"><td colspan="3"><br />'.
 7446: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
 7447: 	'</td></tr></table>'."\n";
 7448: 
 7449:     $result.='</td>'; #<td valign="top">';
 7450: 
 7451: #    $result.='<table width="100%" border="0">';
 7452: #    $result.='<tr bgcolor="#ffffe6"><td>'.
 7453: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
 7454: #	' '.&mt('scores from file').' </td></tr>'."\n";
 7455: #
 7456: #    $result.='<tr bgcolor="#ffffe6"><td>'.
 7457: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
 7458: #        ' '.&mt('clicker file').' </td></tr>'."\n";
 7459: #
 7460: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7461: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
 7462: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
 7463: #
 7464: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
 7465: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 7466: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
 7467: #	    ' '.&mt('receipt').': '.
 7468: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
 7469: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
 7470: #	    '</td></tr>'."\n";
 7471: #    } 
 7472: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7473: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
 7474: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
 7475: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7476: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
 7477: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
 7478: #
 7479: #    $result.='</table>'."\n".'</td>';
 7480:     $result.= '</tr></table>'."\n".
 7481: 	'</td></tr></table></form>'."\n";
 7482:     return $result;
 7483: }
 7484: 
 7485: sub reset_perm {
 7486:     undef(%perm);
 7487: }
 7488: 
 7489: sub init_perm {
 7490:     &reset_perm();
 7491:     foreach my $test_perm ('vgr','mgr','opa') {
 7492: 
 7493: 	my $scope = $env{'request.course.id'};
 7494: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 7495: 
 7496: 	    $scope .= '/'.$env{'request.course.sec'};
 7497: 	    if ( $perm{$test_perm}=
 7498: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 7499: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 7500: 	    } else {
 7501: 		delete($perm{$test_perm});
 7502: 	    }
 7503: 	}
 7504:     }
 7505: }
 7506: 
 7507: sub gather_clicker_ids {
 7508:     my %clicker_ids;
 7509: 
 7510:     my $classlist = &Apache::loncoursedata::get_classlist();
 7511: 
 7512:     # Set up a couple variables.
 7513:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 7514:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 7515:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 7516: 
 7517:     foreach my $student (keys(%$classlist)) {
 7518:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 7519:         my $username = $classlist->{$student}->[$username_idx];
 7520:         my $domain   = $classlist->{$student}->[$domain_idx];
 7521:         my $clickers =
 7522: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 7523:         foreach my $id (split(/\,/,$clickers)) {
 7524:             $id=~s/^[\#0]+//;
 7525:             $id=~s/[\-\:]//g;
 7526:             if (exists($clicker_ids{$id})) {
 7527: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 7528:             } else {
 7529: 		$clicker_ids{$id}=$username.':'.$domain;
 7530:             }
 7531:         }
 7532:     }
 7533:     return %clicker_ids;
 7534: }
 7535: 
 7536: sub gather_adv_clicker_ids {
 7537:     my %clicker_ids;
 7538:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 7539:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7540:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 7541:     foreach my $element (sort(keys(%coursepersonnel))) {
 7542:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 7543:             my ($puname,$pudom)=split(/\:/,$person);
 7544:             my $clickers =
 7545: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 7546:             foreach my $id (split(/\,/,$clickers)) {
 7547: 		$id=~s/^[\#0]+//;
 7548:                 $id=~s/[\-\:]//g;
 7549: 		if (exists($clicker_ids{$id})) {
 7550: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 7551: 		} else {
 7552: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 7553: 		}
 7554:             }
 7555:         }
 7556:     }
 7557:     return %clicker_ids;
 7558: }
 7559: 
 7560: sub clicker_grading_parameters {
 7561:     return ('gradingmechanism' => 'scalar',
 7562:             'upfiletype' => 'scalar',
 7563:             'specificid' => 'scalar',
 7564:             'pcorrect' => 'scalar',
 7565:             'pincorrect' => 'scalar');
 7566: }
 7567: 
 7568: sub process_clicker {
 7569:     my ($r)=@_;
 7570:     my ($symb)=&get_symb($r);
 7571:     if (!$symb) {return '';}
 7572:     my $result=&checkforfile_js();
 7573:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 7574:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 7575:     $result.=$table;
 7576:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 7577:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 7578:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 7579:         '.</b></td></tr>'."\n";
 7580:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 7581: # Attempt to restore parameters from last session, set defaults if not present
 7582:     my %Saveable_Parameters=&clicker_grading_parameters();
 7583:     &Apache::loncommon::restore_course_settings('grades_clicker',
 7584:                                                  \%Saveable_Parameters);
 7585:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 7586:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 7587:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 7588:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 7589: 
 7590:     my %checked;
 7591:     foreach my $gradingmechanism ('attendance','personnel','specific') {
 7592:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 7593:           $checked{$gradingmechanism}="checked='checked'";
 7594:        }
 7595:     }
 7596: 
 7597:     my $upload=&mt("Upload File");
 7598:     my $type=&mt("Type");
 7599:     my $attendance=&mt("Award points just for participation");
 7600:     my $personnel=&mt("Correctness determined from response by course personnel");
 7601:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 7602:     my $pcorrect=&mt("Percentage points for correct solution");
 7603:     my $pincorrect=&mt("Percentage points for incorrect solution");
 7604:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 7605: 						   ('iclicker' => 'i>clicker',
 7606:                                                     'interwrite' => 'interwrite PRS'));
 7607:     $symb = &Apache::lonenc::check_encrypt($symb);
 7608:     $result.=<<ENDUPFORM;
 7609: <script type="text/javascript">
 7610: function sanitycheck() {
 7611: // Accept only integer percentages
 7612:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 7613:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 7614: // Find out grading choice
 7615:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 7616:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 7617:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 7618:       }
 7619:    }
 7620: // By default, new choice equals user selection
 7621:    newgradingchoice=gradingchoice;
 7622: // Not good to give more points for false answers than correct ones
 7623:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 7624:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 7625:    }
 7626: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 7627:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 7628:       document.forms.gradesupload.pcorrect.value=100;
 7629:       document.forms.gradesupload.pincorrect.value=100;
 7630:    }
 7631: // If the values are different, cannot be attendance only
 7632:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 7633:        (gradingchoice=='attendance')) {
 7634:        newgradingchoice='personnel';
 7635:    }
 7636: // Change grading choice to new one
 7637:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 7638:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 7639:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 7640:       } else {
 7641:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 7642:       }
 7643:    }
 7644: // Remember the old state
 7645:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 7646: }
 7647: </script>
 7648: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 7649: <input type="hidden" name="symb" value="$symb" />
 7650: <input type="hidden" name="command" value="processclickerfile" />
 7651: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 7652: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 7653: <input type="file" name="upfile" size="50" />
 7654: <br /><label>$type: $selectform</label>
 7655: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 7656: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 7657: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 7658: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 7659: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 7660: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 7661: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 7662: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 7663: </form>
 7664: ENDUPFORM
 7665:     $result.='</td></tr></table>'."\n".
 7666:              '</td></tr></table><br /><br />'."\n";
 7667:     $result.=&show_grading_menu_form($symb);
 7668:     return $result;
 7669: }
 7670: 
 7671: sub process_clicker_file {
 7672:     my ($r)=@_;
 7673:     my ($symb)=&get_symb($r);
 7674:     if (!$symb) {return '';}
 7675: 
 7676:     my %Saveable_Parameters=&clicker_grading_parameters();
 7677:     &Apache::loncommon::store_course_settings('grades_clicker',
 7678:                                               \%Saveable_Parameters);
 7679: 
 7680:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 7681:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 7682: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 7683: 	return $result.&show_grading_menu_form($symb);
 7684:     }
 7685:     my %clicker_ids=&gather_clicker_ids();
 7686:     my %correct_ids;
 7687:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 7688: 	%correct_ids=&gather_adv_clicker_ids();
 7689:     }
 7690:     if ($env{'form.gradingmechanism'} eq 'specific') {
 7691: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 7692: 	   $correct_id=~tr/a-z/A-Z/;
 7693: 	   $correct_id=~s/\s//gs;
 7694: 	   $correct_id=~s/^[\#0]+//;
 7695:            $correct_id=~s/[\-\:]//g;
 7696:            if ($correct_id) {
 7697: 	      $correct_ids{$correct_id}='specified';
 7698:            }
 7699:         }
 7700:     }
 7701:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 7702: 	$result.=&mt('Score based on attendance only');
 7703:     } else {
 7704: 	my $number=0;
 7705: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 7706: 	foreach my $id (sort(keys(%correct_ids))) {
 7707: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 7708: 	    if ($correct_ids{$id} eq 'specified') {
 7709: 		$result.=&mt('specified');
 7710: 	    } else {
 7711: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 7712: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 7713: 	    }
 7714: 	    $number++;
 7715: 	}
 7716:         $result.="</p>\n";
 7717: 	if ($number==0) {
 7718: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 7719: 	    return $result.&show_grading_menu_form($symb);
 7720: 	}
 7721:     }
 7722:     if (length($env{'form.upfile'}) < 2) {
 7723:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 7724: 		     '<span class="LC_error">',
 7725: 		     '</span>',
 7726: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 7727:         return $result.&show_grading_menu_form($symb);
 7728:     }
 7729: 
 7730: # Were able to get all the info needed, now analyze the file
 7731: 
 7732:     $result.=&Apache::loncommon::studentbrowser_javascript();
 7733:     $symb = &Apache::lonenc::check_encrypt($symb);
 7734:     my $heading=&mt('Scanning clicker file');
 7735:     $result.=(<<ENDHEADER);
 7736: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 7737: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 7738: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 7739: <form method="post" action="/adm/grades" name="clickeranalysis">
 7740: <input type="hidden" name="symb" value="$symb" />
 7741: <input type="hidden" name="command" value="assignclickergrades" />
 7742: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 7743: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 7744: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 7745: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 7746: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 7747: ENDHEADER
 7748:     my %responses;
 7749:     my @questiontitles;
 7750:     my $errormsg='';
 7751:     my $number=0;
 7752:     if ($env{'form.upfiletype'} eq 'iclicker') {
 7753: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 7754:     }
 7755:     if ($env{'form.upfiletype'} eq 'interwrite') {
 7756:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 7757:     }
 7758:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 7759:              '<input type="hidden" name="number" value="'.$number.'" />'.
 7760:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
 7761:              '<input type="hidden" name="number" value="'.$number.'" />'.
 7762:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 7763:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 7764:              '<br />';
 7765: # Remember Question Titles
 7766: # FIXME: Possibly need delimiter other than ":"
 7767:     for (my $i=0;$i<$number;$i++) {
 7768:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 7769:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 7770:     }
 7771:     my $correct_count=0;
 7772:     my $student_count=0;
 7773:     my $unknown_count=0;
 7774: # Match answers with usernames
 7775: # FIXME: Possibly need delimiter other than ":"
 7776:     foreach my $id (keys(%responses)) {
 7777:        if ($correct_ids{$id}) {
 7778:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 7779:           $correct_count++;
 7780:        } elsif ($clicker_ids{$id}) {
 7781:           if ($clicker_ids{$id}=~/\,/) {
 7782: # More than one user with the same clicker!
 7783:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 7784:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 7785:                            "<select name='multi".$id."'>";
 7786:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 7787:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 7788:              }
 7789:              $result.='</select>';
 7790:              $unknown_count++;
 7791:           } else {
 7792: # Good: found one and only one user with the right clicker
 7793:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 7794:              $student_count++;
 7795:           }
 7796:        } else {
 7797:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 7798:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 7799:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 7800:                    "\n".&mt("Domain").": ".
 7801:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 7802:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 7803:           $unknown_count++;
 7804:        }
 7805:     }
 7806:     $result.='<hr />'.
 7807:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 7808:     if ($env{'form.gradingmechanism'} ne 'attendance') {
 7809:        if ($correct_count==0) {
 7810:           $errormsg.="Found no correct answers answers for grading!";
 7811:        } elsif ($correct_count>1) {
 7812:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 7813:        }
 7814:     }
 7815:     if ($number<1) {
 7816:        $errormsg.="Found no questions.";
 7817:     }
 7818:     if ($errormsg) {
 7819:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 7820:     } else {
 7821:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 7822:     }
 7823:     $result.='</form></td></tr></table>'."\n".
 7824:              '</td></tr></table><br /><br />'."\n";
 7825:     return $result.&show_grading_menu_form($symb);
 7826: }
 7827: 
 7828: sub iclicker_eval {
 7829:     my ($questiontitles,$responses)=@_;
 7830:     my $number=0;
 7831:     my $errormsg='';
 7832:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 7833:         my %components=&Apache::loncommon::record_sep($line);
 7834:         my @entries=map {$components{$_}} (sort(keys(%components)));
 7835: 	if ($entries[0] eq 'Question') {
 7836: 	    for (my $i=3;$i<$#entries;$i+=6) {
 7837: 		$$questiontitles[$number]=$entries[$i];
 7838: 		$number++;
 7839: 	    }
 7840: 	}
 7841: 	if ($entries[0]=~/^\#/) {
 7842: 	    my $id=$entries[0];
 7843: 	    my @idresponses;
 7844: 	    $id=~s/^[\#0]+//;
 7845: 	    for (my $i=0;$i<$number;$i++) {
 7846: 		my $idx=3+$i*6;
 7847: 		push(@idresponses,$entries[$idx]);
 7848: 	    }
 7849: 	    $$responses{$id}=join(',',@idresponses);
 7850: 	}
 7851:     }
 7852:     return ($errormsg,$number);
 7853: }
 7854: 
 7855: sub interwrite_eval {
 7856:     my ($questiontitles,$responses)=@_;
 7857:     my $number=0;
 7858:     my $errormsg='';
 7859:     my $skipline=1;
 7860:     my $questionnumber=0;
 7861:     my %idresponses=();
 7862:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 7863:         my %components=&Apache::loncommon::record_sep($line);
 7864:         my @entries=map {$components{$_}} (sort(keys(%components)));
 7865:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 7866:         if ($entries[1] eq 'Response') { $skipline=1; }
 7867:         next if $skipline;
 7868:         if ($entries[0]!=$questionnumber) {
 7869:            $questionnumber=$entries[0];
 7870:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 7871:            $number++;
 7872:         }
 7873:         my $id=$entries[4];
 7874:         $id=~s/^[\#0]+//;
 7875:         $id=~s/^v\d*\://i;
 7876:         $id=~s/[\-\:]//g;
 7877:         $idresponses{$id}[$number]=$entries[6];
 7878:     }
 7879:     foreach my $id (keys %idresponses) {
 7880:        $$responses{$id}=join(',',@{$idresponses{$id}});
 7881:        $$responses{$id}=~s/^\s*\,//;
 7882:     }
 7883:     return ($errormsg,$number);
 7884: }
 7885: 
 7886: sub assign_clicker_grades {
 7887:     my ($r)=@_;
 7888:     my ($symb)=&get_symb($r);
 7889:     if (!$symb) {return '';}
 7890: # See which part we are saving to
 7891:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 7892: # FIXME: This should probably look for the first handgradeable part
 7893:     my $part=$$partlist[0];
 7894: # Start screen output
 7895:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 7896: 
 7897:     my $heading=&mt('Assigning grades based on clicker file');
 7898:     $result.=(<<ENDHEADER);
 7899: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 7900: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 7901: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 7902: ENDHEADER
 7903: # Get correct result
 7904: # FIXME: Possibly need delimiter other than ":"
 7905:     my @correct=();
 7906:     my $gradingmechanism=$env{'form.gradingmechanism'};
 7907:     my $number=$env{'form.number'};
 7908:     if ($gradingmechanism ne 'attendance') {
 7909:        foreach my $key (keys(%env)) {
 7910:           if ($key=~/^form\.correct\:/) {
 7911:              my @input=split(/\,/,$env{$key});
 7912:              for (my $i=0;$i<=$#input;$i++) {
 7913:                  if (($correct[$i]) && ($input[$i]) &&
 7914:                      ($correct[$i] ne $input[$i])) {
 7915:                     $result.='<br /><span class="LC_warning">'.
 7916:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 7917:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 7918:                  } elsif ($input[$i]) {
 7919:                     $correct[$i]=$input[$i];
 7920:                  }
 7921:              }
 7922:           }
 7923:        }
 7924:        for (my $i=0;$i<$number;$i++) {
 7925:           if (!$correct[$i]) {
 7926:              $result.='<br /><span class="LC_error">'.
 7927:                       &mt('No correct result given for question "[_1]"!',
 7928:                           $env{'form.question:'.$i}).'</span>';
 7929:           }
 7930:        }
 7931:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 7932:     }
 7933: # Start grading
 7934:     my $pcorrect=$env{'form.pcorrect'};
 7935:     my $pincorrect=$env{'form.pincorrect'};
 7936:     my $storecount=0;
 7937:     foreach my $key (keys(%env)) {
 7938:        my $user='';
 7939:        if ($key=~/^form\.student\:(.*)$/) {
 7940:           $user=$1;
 7941:        }
 7942:        if ($key=~/^form\.unknown\:(.*)$/) {
 7943:           my $id=$1;
 7944:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 7945:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 7946:           } elsif ($env{'form.multi'.$id}) {
 7947:              $user=$env{'form.multi'.$id};
 7948:           }
 7949:        }
 7950:        if ($user) { 
 7951:           my @answer=split(/\,/,$env{$key});
 7952:           my $sum=0;
 7953:           for (my $i=0;$i<$number;$i++) {
 7954:              if ($answer[$i]) {
 7955:                 if ($gradingmechanism eq 'attendance') {
 7956:                    $sum+=$pcorrect;
 7957:                 } else {
 7958:                    if ($answer[$i] eq $correct[$i]) {
 7959:                       $sum+=$pcorrect;
 7960:                    } else {
 7961:                       $sum+=$pincorrect;
 7962:                    }
 7963:                 }
 7964:              }
 7965:           }
 7966:           my $ave=$sum/(100*$number);
 7967: # Store
 7968:           my ($username,$domain)=split(/\:/,$user);
 7969:           my %grades=();
 7970:           $grades{"resource.$part.solved"}='correct_by_override';
 7971:           $grades{"resource.$part.awarded"}=$ave;
 7972:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 7973:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 7974:                                                  $env{'request.course.id'},
 7975:                                                  $domain,$username);
 7976:           if ($returncode ne 'ok') {
 7977:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 7978:           } else {
 7979:              $storecount++;
 7980:           }
 7981:        }
 7982:     }
 7983: # We are done
 7984:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 7985:              '</td></tr></table>'."\n".
 7986:              '</td></tr></table><br /><br />'."\n";
 7987:     return $result.&show_grading_menu_form($symb);
 7988: }
 7989: 
 7990: sub handler {
 7991:     my $request=$_[0];
 7992:     &reset_caches();
 7993:     if ($env{'browser.mathml'}) {
 7994: 	&Apache::loncommon::content_type($request,'text/xml');
 7995:     } else {
 7996: 	&Apache::loncommon::content_type($request,'text/html');
 7997:     }
 7998:     $request->send_http_header;
 7999:     return '' if $request->header_only;
 8000:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8001:     my $symb=&get_symb($request,1);
 8002:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8003:     my $command=$commands[0];
 8004: 
 8005:     if ($#commands > 0) {
 8006: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8007:     }
 8008: 
 8009: 
 8010:     $request->print(&Apache::loncommon::start_page('Grading'));
 8011:     if ($symb eq '' && $command eq '') {
 8012: 	if ($env{'user.adv'}) {
 8013: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8014: 		($env{'form.codethree'})) {
 8015: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8016: 		    $env{'form.codethree'};
 8017: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8018: 		    &Apache::lonnet::checkin($token);
 8019: 		if ($tsymb) {
 8020: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8021: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8022: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
 8023: 					  ('grade_username' => $tuname,
 8024: 					   'grade_domain' => $tudom,
 8025: 					   'grade_courseid' => $tcrsid,
 8026: 					   'grade_symb' => $tsymb)));
 8027: 		    } else {
 8028: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8029: 		    }
 8030: 		} else {
 8031: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8032: 		}
 8033: 	    } else {
 8034: 		$request->print(&Apache::lonxml::tokeninputfield());
 8035: 	    }
 8036: 	}
 8037:     } else {
 8038: 	&init_perm();
 8039: 	if ($command eq 'submission' && $perm{'vgr'}) {
 8040: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 8041: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 8042: 	    &pickStudentPage($request);
 8043: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 8044: 	    &displayPage($request);
 8045: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 8046: 	    &updateGradeByPage($request);
 8047: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 8048: 	    &processGroup($request);
 8049: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 8050: 	    $request->print(&grading_menu($request));
 8051: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 8052: 	    $request->print(&submit_options($request));
 8053: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 8054: 	    $request->print(&viewgrades($request));
 8055: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 8056: 	    $request->print(&processHandGrade($request));
 8057: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 8058: 	    $request->print(&editgrades($request));
 8059: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 8060: 	    $request->print(&verifyreceipt($request));
 8061:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 8062:             $request->print(&process_clicker($request));
 8063:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 8064:             $request->print(&process_clicker_file($request));
 8065:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 8066:             $request->print(&assign_clicker_grades($request));
 8067: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 8068: 	    $request->print(&upcsvScores_form($request));
 8069: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 8070: 	    $request->print(&csvupload($request));
 8071: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 8072: 	    $request->print(&csvuploadmap($request));
 8073: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 8074: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 8075: 		$request->print(&csvuploadoptions($request));
 8076: 	    } else {
 8077: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 8078: 		    $env{'form.upfile_associate'} = 'reverse';
 8079: 		} else {
 8080: 		    $env{'form.upfile_associate'} = 'forward';
 8081: 		}
 8082: 		$request->print(&csvuploadmap($request));
 8083: 	    }
 8084: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 8085: 	    $request->print(&csvuploadassign($request));
 8086: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 8087: 	    $request->print(&scantron_selectphase($request));
 8088:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 8089:  	    $request->print(&scantron_do_warning($request));
 8090: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 8091: 	    $request->print(&scantron_validate_file($request));
 8092: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 8093: 	    $request->print(&scantron_process_students($request));
 8094:  	} elsif ($command eq 'scantronupload' && 
 8095:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8096: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8097:  	    $request->print(&scantron_upload_scantron_data($request)); 
 8098:  	} elsif ($command eq 'scantronupload_save' &&
 8099:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8100: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8101:  	    $request->print(&scantron_upload_scantron_data_save($request));
 8102:  	} elsif ($command eq 'scantron_download' &&
 8103: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 8104:  	    $request->print(&scantron_download_scantron_data($request));
 8105: 	} elsif ($command) {
 8106: 	    $request->print("Access Denied ($command)");
 8107: 	}
 8108:     }
 8109:     $request->print(&Apache::loncommon::end_page());
 8110:     &reset_caches();
 8111:     return '';
 8112: }
 8113: 
 8114: 1;
 8115: 
 8116: __END__;

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