File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.450: download - view: text, annotated - select for diffs
Tue Oct 9 23:03:22 2007 UTC (16 years, 7 months ago) by banghart
Branches: MAIN
CVS tags: HEAD
	Saving work in progress. Getting close. Need to handle multiple
	groups and "none".

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.450 2007/10/09 23:03:22 banghart 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::loncoursedata;
   39: use Apache::lonmsg();
   40: use Apache::Constants qw(:common);
   41: use Apache::lonlocal;
   42: use Apache::lonenc;
   43: use String::Similarity;
   44: use LONCAPA;
   45: 
   46: use POSIX qw(floor);
   47: 
   48: 
   49: my %perm=();
   50: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
   51:                                    # index is "symb.part_id"
   52: 
   53: my %first_bubble_line = ();	# First bubble line no. for each bubble.
   54: 
   55: # Save and restore the bubble lines array to the form env.
   56: 
   57: 
   58: sub save_bubble_lines {
   59:     &Apache::lonnet::logthis("Saving bubble_lines...");
   60:     foreach my $line (keys(%bubble_lines_per_response)) {
   61: 	&Apache::lonnet::logthis("Saving form.scantron.bubblelines.$line value: $bubble_lines_per_response{$line}");
   62: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
   63: 	$env{"form.scantron.first_bubble_line.$line"} =
   64: 	    $first_bubble_line{$line};
   65:     }
   66: }
   67: 
   68: 
   69: sub restore_bubble_lines {
   70:     my $line = 0;
   71:     %bubble_lines_per_response = ();
   72:     while ($env{"form.scantron.bubblelines.$line"}) {
   73: 	my $value = $env{"form.scantron.bubblelines.$line"};
   74: 	&Apache::lonnet::logthis("Restoring form.scantron.bubblelines.$line value: $value");
   75: 	$bubble_lines_per_response{$line} = $value;
   76: 	$first_bubble_line{$line}  =
   77: 	    $env{"form.scantron.first_bubble_line.$line"};
   78: 	$line++;
   79:     }
   80: 
   81: }
   82: 
   83: #  Given the parsed scanline, get the response for 
   84: #  'answer' number n:
   85: 
   86: sub get_response_bubbles {
   87:     my ($parsed_line, $response)  = @_;
   88: 
   89:     my $bubble_line = $first_bubble_line{$response};
   90:     my $bubble_lines= $bubble_lines_per_response{$response};
   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>Answer</td>'.$toprow.'</tr>'.
  336: 	    '<tr valign="top"><td>'.$grayFont.'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>Answer</td>'.$toprow.'</tr>'.
  356: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
  357: 	    $middlerow.'</tr>'.
  358: 	    '<tr valign="top"><td>'.$grayFont.'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>true</b></td>';
  369: 		} else {
  370: 		    $toprow.='<td><i>true</i></td>';
  371: 		}
  372: 	    } else {
  373: 		$toprow.='<td>false</td>';
  374: 	    }
  375: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  376: 	}
  377: 	return '<blockquote><table border="1">'.
  378: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
  379: 	    '<tr valign="top"><td>'.$grayFont.'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: 	if (@getgroup) {
  530: 	    my $exclude = 1;
  531: 	    foreach my $grp(@getgroup) {
  532: 	        if ($group eq $grp) {
  533: 	            $exclude = 0;
  534: 	        }
  535: 	    }
  536: 	    if ($exclude) {
  537: 	        delete($classlist->{$student});
  538: 	    }
  539: 	}
  540: 	$section = ($section ne '' ? $section : 'none');
  541: 	if (&canview($section)) {
  542: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  543: 		$sections{$section}++;
  544: 		if ($classlist->{$student}) {
  545: 		    $fullnames{$student}=$fullname;
  546: 		}
  547: 	    } else {
  548: 		delete($classlist->{$student});
  549: 	    }
  550: 	} else {
  551: 	    delete($classlist->{$student});
  552: 	}
  553:     }
  554:     my %seen = ();
  555:     my @sections = sort(keys(%sections));
  556:     return ($classlist,\@sections,\%fullnames);
  557: }
  558: 
  559: sub canmodify {
  560:     my ($sec)=@_;
  561:     if ($perm{'mgr'}) {
  562: 	if (!defined($perm{'mgr_section'})) {
  563: 	    # can modify whole class
  564: 	    return 1;
  565: 	} else {
  566: 	    if ($sec eq $perm{'mgr_section'}) {
  567: 		#can modify the requested section
  568: 		return 1;
  569: 	    } else {
  570: 		# can't modify the request section
  571: 		return 0;
  572: 	    }
  573: 	}
  574:     }
  575:     #can't modify
  576:     return 0;
  577: }
  578: 
  579: sub canview {
  580:     my ($sec)=@_;
  581:     if ($perm{'vgr'}) {
  582: 	if (!defined($perm{'vgr_section'})) {
  583: 	    # can modify whole class
  584: 	    return 1;
  585: 	} else {
  586: 	    if ($sec eq $perm{'vgr_section'}) {
  587: 		#can modify the requested section
  588: 		return 1;
  589: 	    } else {
  590: 		# can't modify the request section
  591: 		return 0;
  592: 	    }
  593: 	}
  594:     }
  595:     #can't modify
  596:     return 0;
  597: }
  598: 
  599: #--- Retrieve the grade status of a student for all the parts
  600: sub student_gradeStatus {
  601:     my ($symb,$udom,$uname,$partlist) = @_;
  602:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  603:     my %partstatus = ();
  604:     foreach (@$partlist) {
  605: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  606: 	$status              = 'nothing' if ($status eq '');
  607: 	$partstatus{$_}      = $status;
  608: 	my $subkey           = "resource.$_.submitted_by";
  609: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  610:     }
  611:     return %partstatus;
  612: }
  613: 
  614: # hidden form and javascript that calls the form
  615: # Use by verifyscript and viewgrades
  616: # Shows a student's view of problem and submission
  617: sub jscriptNform {
  618:     my ($symb) = @_;
  619:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  620:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  621: 	'    function viewOneStudent(user,domain) {'."\n".
  622: 	'	document.onestudent.student.value = user;'."\n".
  623: 	'	document.onestudent.userdom.value = domain;'."\n".
  624: 	'	document.onestudent.submit();'."\n".
  625: 	'    }'."\n".
  626: 	'</script>'."\n";
  627:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  628: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  629: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  630: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  631: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  632: 	'<input type="hidden" name="command" value="submission" />'."\n".
  633: 	'<input type="hidden" name="student" value="" />'."\n".
  634: 	'<input type="hidden" name="userdom" value="" />'."\n".
  635: 	'</form>'."\n";
  636:     return $jscript;
  637: }
  638: 
  639: 
  640: 
  641: # Given the score (as a number [0-1] and the weight) what is the final
  642: # point value? This function will round to the nearest tenth, third,
  643: # or quarter if one of those is within the tolerance of .00001.
  644: sub compute_points {
  645:     my ($score, $weight) = @_;
  646:     
  647:     my $tolerance = .00001;
  648:     my $points = $score * $weight;
  649: 
  650:     # Check for nearness to 1/x.
  651:     my $check_for_nearness = sub {
  652:         my ($factor) = @_;
  653:         my $num = ($points * $factor) + $tolerance;
  654:         my $floored_num = floor($num);
  655:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  656:             return $floored_num / $factor;
  657:         }
  658:         return $points;
  659:     };
  660: 
  661:     $points = $check_for_nearness->(10);
  662:     $points = $check_for_nearness->(3);
  663:     $points = $check_for_nearness->(4);
  664:     
  665:     return $points;
  666: }
  667: 
  668: #------------------ End of general use routines --------------------
  669: 
  670: #
  671: # Find most similar essay
  672: #
  673: 
  674: sub most_similar {
  675:     my ($uname,$udom,$uessay,$old_essays)=@_;
  676: 
  677: # ignore spaces and punctuation
  678: 
  679:     $uessay=~s/\W+/ /gs;
  680: 
  681: # ignore empty submissions (occuring when only files are sent)
  682: 
  683:     unless ($uessay=~/\w+/) { return ''; }
  684: 
  685: # these will be returned. Do not care if not at least 50 percent similar
  686:     my $limit=0.6;
  687:     my $sname='';
  688:     my $sdom='';
  689:     my $scrsid='';
  690:     my $sessay='';
  691: # go through all essays ...
  692:     foreach my $tkey (keys(%$old_essays)) {
  693: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  694: # ... except the same student
  695:         next if (($tname eq $uname) && ($tdom eq $udom));
  696: 	my $tessay=$old_essays->{$tkey};
  697: 	$tessay=~s/\W+/ /gs;
  698: # String similarity gives up if not even limit
  699: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  700: # Found one
  701: 	if ($tsimilar>$limit) {
  702: 	    $limit=$tsimilar;
  703: 	    $sname=$tname;
  704: 	    $sdom=$tdom;
  705: 	    $scrsid=$tcrsid;
  706: 	    $sessay=$old_essays->{$tkey};
  707: 	}
  708:     }
  709:     if ($limit>0.6) {
  710:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  711:     } else {
  712:        return ('','','','',0);
  713:     }
  714: }
  715: 
  716: #-------------------------------------------------------------------
  717: 
  718: #------------------------------------ Receipt Verification Routines
  719: #
  720: #--- Check whether a receipt number is valid.---
  721: sub verifyreceipt {
  722:     my $request  = shift;
  723: 
  724:     my $courseid = $env{'request.course.id'};
  725:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  726: 	$env{'form.receipt'};
  727:     $receipt     =~ s/[^\-\d]//g;
  728:     my ($symb)   = &get_symb($request);
  729: 
  730:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
  731: 	$receipt.'</h3></span>'."\n".
  732: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
  733: 
  734:     my ($string,$contents,$matches) = ('','',0);
  735:     my (undef,undef,$fullname) = &getclasslist('all','0');
  736:     
  737:     my $receiptparts=0;
  738:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  739: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  740:     my $parts=['0'];
  741:     if ($receiptparts) { ($parts)=&response_type($symb); }
  742:     foreach (sort 
  743: 	     {
  744: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  745: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  746: 		 }
  747: 		 return $a cmp $b;
  748: 	     } (keys(%$fullname))) {
  749: 	my ($uname,$udom)=split(/\:/);
  750: 	foreach my $part (@$parts) {
  751: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  752: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
  753: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  754: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  755: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  756: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  757: 		if ($receiptparts) {
  758: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  759: 		}
  760: 		$contents.='</tr>'."\n";
  761: 		
  762: 		$matches++;
  763: 	    }
  764: 	}
  765:     }
  766:     if ($matches == 0) {
  767: 	$string = $title.'No match found for the above receipt.';
  768:     } else {
  769: 	$string = &jscriptNform($symb).$title.
  770: 	    'The above receipt matches the following student'.
  771: 	    ($matches <= 1 ? '.' : 's.')."\n".
  772: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
  773: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
  774: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
  775: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
  776: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
  777: 	if ($receiptparts) {
  778: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
  779: 	}
  780: 	$string.='</tr>'."\n".$contents.
  781: 	    '</table></td></tr></table>'."\n";
  782:     }
  783:     return $string.&show_grading_menu_form($symb);
  784: }
  785: 
  786: #--- This is called by a number of programs.
  787: #--- Called from the Grading Menu - View/Grade an individual student
  788: #--- Also called directly when one clicks on the subm button 
  789: #    on the problem page.
  790: sub listStudents {
  791:     my ($request) = shift;
  792: 
  793:     my ($symb) = &get_symb($request);
  794:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  795:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  796:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  797:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  798:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  799:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  800:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  801: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  802: 
  803:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
  804: 	' Submissions for a Student or a Group of Students</span></h3>';
  805: 
  806:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  807: 
  808:     $request->print(<<LISTJAVASCRIPT);
  809: <script type="text/javascript" language="javascript">
  810:     function checkSelect(checkBox) {
  811: 	var ctr=0;
  812: 	var sense="";
  813: 	if (checkBox.length > 1) {
  814: 	    for (var i=0; i<checkBox.length; i++) {
  815: 		if (checkBox[i].checked) {
  816: 		    ctr++;
  817: 		}
  818: 	    }
  819: 	    sense = "a student or group of students";
  820: 	} else {
  821: 	    if (checkBox.checked) {
  822: 		ctr = 1;
  823: 	    }
  824: 	    sense = "the student";
  825: 	}
  826: 	if (ctr == 0) {
  827: 	    alert("Please select "+sense+" before clicking on the Next button.");
  828: 	    return false;
  829: 	}
  830: 	document.gradesub.submit();
  831:     }
  832: 
  833:     function reLoadList(formname) {
  834: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  835: 	formname.command.value = 'submission';
  836: 	formname.submit();
  837:     }
  838: </script>
  839: LISTJAVASCRIPT
  840: 
  841:     &commonJSfunctions($request);
  842:     $request->print($result);
  843: 
  844:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  845:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  846:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  847: 	"\n".$table.
  848: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
  849: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
  850: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
  851: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
  852: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
  853: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
  854: 	'&nbsp;<b>Submissions: </b>'."\n";
  855:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  856: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
  857:     }
  858:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  859:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  860:     $env{'form.Status'} = $saveStatus;
  861:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
  862: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
  863: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
  864: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
  865:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
  866:         '<option value="1">Whole Points</option>'.
  867:         '<option value=".5">Half Points</option>'.
  868:         '<option value=".25">Quarter Points</option>'.
  869:         '<option value=".1">Tenths of a Point</option>'.
  870:         '</select>'.
  871:         &build_section_inputs().
  872: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  873: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  874: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  875: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  876: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  877: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  878: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  879: 
  880:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  881: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  882:     } else {
  883: 	$gradeTable.='<b>Student Status:</b> '.
  884: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
  885:     }
  886: 
  887:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
  888: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
  889: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  890: 
  891: # checkall buttons
  892:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  893:     $gradeTable.='<input type="button" '."\n".
  894: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  895: 	'value="Next->" /> <br />'."\n";
  896:     $gradeTable.=&check_buttons();
  897:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
  898:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  899:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
  900: 	'<table border="0"><tr bgcolor="#e6ffff">';
  901:     my $loop = 0;
  902:     while ($loop < 2) {
  903: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
  904: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
  905: 	if ($env{'form.showgrading'} eq 'yes' 
  906: 	    && $submitonly ne 'queued'
  907: 	    && $submitonly ne 'all') {
  908: 	    foreach (sort(@$partlist)) {
  909: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
  910: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
  911: 		    ' Status&nbsp;</b></td>';
  912: 	    }
  913: 	} elsif ($submitonly eq 'queued') {
  914: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
  915: 	}
  916: 	$loop++;
  917: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  918:     }
  919:     $gradeTable.='</tr>'."\n";
  920: 
  921:     my $ctr = 0;
  922:     foreach my $student (sort 
  923: 			 {
  924: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  925: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  926: 			     }
  927: 			     return $a cmp $b;
  928: 			 }
  929: 			 (keys(%$fullname))) {
  930: 	my ($uname,$udom) = split(/:/,$student);
  931: 
  932: 	my %status = ();
  933: 
  934: 	if ($submitonly eq 'queued') {
  935: 	    my %queue_status = 
  936: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  937: 							$udom,$uname);
  938: 	    next if (!defined($queue_status{'gradingqueue'}));
  939: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  940: 	}
  941: 
  942: 	if ($env{'form.showgrading'} eq 'yes' 
  943: 	    && $submitonly ne 'queued'
  944: 	    && $submitonly ne 'all') {
  945: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  946: 	    my $submitted = 0;
  947: 	    my $graded = 0;
  948: 	    my $incorrect = 0;
  949: 	    foreach (keys(%status)) {
  950: 		$submitted = 1 if ($status{$_} ne 'nothing');
  951: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  952: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  953: 		
  954: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  955: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  956: 		    $submitted = 0;
  957: 		    my ($part)=split(/\./,$partid);
  958: 		    $gradeTable.='<input type="hidden" name="'.
  959: 			$student.':'.$part.':submitted_by" value="'.
  960: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
  961: 		}
  962: 	    }
  963: 	    
  964: 	    next if (!$submitted && ($submitonly eq 'yes' ||
  965: 				     $submitonly eq 'incorrect' ||
  966: 				     $submitonly eq 'graded'));
  967: 	    next if (!$graded && ($submitonly eq 'graded'));
  968: 	    next if (!$incorrect && $submitonly eq 'incorrect');
  969: 	}
  970: 
  971: 	$ctr++;
  972: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  973: 
  974: 	if ( $perm{'vgr'} eq 'F' ) {
  975: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
  976: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
  977:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
  978:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
  979: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
  980: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
  981: 	       '&nbsp;'.$section.'</td>'."\n";
  982: 
  983: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
  984: 		foreach (sort keys(%status)) {
  985: 		    next if (/^resource.*?submitted_by$/);
  986: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
  987: 		}
  988: 	    }
  989: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
  990: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
  991: 	}
  992:     }
  993:     if ($ctr%2 ==1) {
  994: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
  995: 	    if ($env{'form.showgrading'} eq 'yes' 
  996: 		&& $submitonly ne 'queued'
  997: 		&& $submitonly ne 'all') {
  998: 		foreach (@$partlist) {
  999: 		    $gradeTable.='<td>&nbsp;</td>';
 1000: 		}
 1001: 	    } elsif ($submitonly eq 'queued') {
 1002: 		$gradeTable.='<td>&nbsp;</td>';
 1003: 	    }
 1004: 	$gradeTable.='</tr>';
 1005:     }
 1006: 
 1007:     $gradeTable.='</table></td></tr></table>'."\n".
 1008: 	'<input type="button" '.
 1009: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1010: 	'value="Next->" /></form>'."\n";
 1011:     if ($ctr == 0) {
 1012: 	my $num_students=(scalar(keys(%$fullname)));
 1013: 	if ($num_students eq 0) {
 1014: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
 1015: 	} else {
 1016: 	    my $submissions='submissions';
 1017: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1018: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1019: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1020: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1021: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
 1022: 		' students checked for '.$submissions.')</span><br />';
 1023: 	}
 1024:     } elsif ($ctr == 1) {
 1025: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
 1026:     }
 1027:     $gradeTable.=&show_grading_menu_form($symb);
 1028:     $request->print($gradeTable);
 1029:     return '';
 1030: }
 1031: 
 1032: #---- Called from the listStudents routine
 1033: 
 1034: sub check_script {
 1035:     my ($form, $type)=@_;
 1036:     my $chkallscript='<script type="text/javascript">
 1037:     function checkall() {
 1038:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1039:             ele = document.forms.'.$form.'.elements[i];
 1040:             if (ele.name == "'.$type.'") {
 1041:             document.forms.'.$form.'.elements[i].checked=true;
 1042:                                        }
 1043:         }
 1044:     }
 1045: 
 1046:     function checksec() {
 1047:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1048:             ele = document.forms.'.$form.'.elements[i];
 1049:            string = document.forms.'.$form.'.chksec.value;
 1050:            if
 1051:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1052:               document.forms.'.$form.'.elements[i].checked=true;
 1053:             }
 1054:         }
 1055:     }
 1056: 
 1057: 
 1058:     function uncheckall() {
 1059:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1060:             ele = document.forms.'.$form.'.elements[i];
 1061:             if (ele.name == "'.$type.'") {
 1062:             document.forms.'.$form.'.elements[i].checked=false;
 1063:                                        }
 1064:         }
 1065:     }
 1066: 
 1067: </script>'."\n";
 1068:     return $chkallscript;
 1069: }
 1070: 
 1071: sub check_buttons {
 1072:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
 1073:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
 1074:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
 1075:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1076:     return $buttons;
 1077: }
 1078: 
 1079: #     Displays the submissions for one student or a group of students
 1080: sub processGroup {
 1081:     my ($request)  = shift;
 1082:     my $ctr        = 0;
 1083:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1084:     my $total      = scalar(@stuchecked)-1;
 1085: 
 1086:     foreach my $student (@stuchecked) {
 1087: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1088: 	$env{'form.student'}        = $uname;
 1089: 	$env{'form.userdom'}        = $udom;
 1090: 	$env{'form.fullname'}       = $fullname;
 1091: 	&submission($request,$ctr,$total);
 1092: 	$ctr++;
 1093:     }
 1094:     return '';
 1095: }
 1096: 
 1097: #------------------------------------------------------------------------------------
 1098: #
 1099: #-------------------------- Next few routines handles grading by student, essentially
 1100: #                           handles essay response type problem/part
 1101: #
 1102: #--- Javascript to handle the submission page functionality ---
 1103: sub sub_page_js {
 1104:     my $request = shift;
 1105:     $request->print(<<SUBJAVASCRIPT);
 1106: <script type="text/javascript" language="javascript">
 1107:     function updateRadio(formname,id,weight) {
 1108: 	var gradeBox = formname["GD_BOX"+id];
 1109: 	var radioButton = formname["RADVAL"+id];
 1110: 	var oldpts = formname["oldpts"+id].value;
 1111: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1112: 	gradeBox.value = pts;
 1113: 	var resetbox = false;
 1114: 	if (isNaN(pts) || pts < 0) {
 1115: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1116: 	    for (var i=0; i<radioButton.length; i++) {
 1117: 		if (radioButton[i].checked) {
 1118: 		    gradeBox.value = i;
 1119: 		    resetbox = true;
 1120: 		}
 1121: 	    }
 1122: 	    if (!resetbox) {
 1123: 		formtextbox.value = "";
 1124: 	    }
 1125: 	    return;
 1126: 	}
 1127: 
 1128: 	if (pts > weight) {
 1129: 	    var resp = confirm("You entered a value ("+pts+
 1130: 			       ") greater than the weight for the part. Accept?");
 1131: 	    if (resp == false) {
 1132: 		gradeBox.value = oldpts;
 1133: 		return;
 1134: 	    }
 1135: 	}
 1136: 
 1137: 	for (var i=0; i<radioButton.length; i++) {
 1138: 	    radioButton[i].checked=false;
 1139: 	    if (pts == i && pts != "") {
 1140: 		radioButton[i].checked=true;
 1141: 	    }
 1142: 	}
 1143: 	updateSelect(formname,id);
 1144: 	formname["stores"+id].value = "0";
 1145:     }
 1146: 
 1147:     function writeBox(formname,id,pts) {
 1148: 	var gradeBox = formname["GD_BOX"+id];
 1149: 	if (checkSolved(formname,id) == 'update') {
 1150: 	    gradeBox.value = pts;
 1151: 	} else {
 1152: 	    var oldpts = formname["oldpts"+id].value;
 1153: 	    gradeBox.value = oldpts;
 1154: 	    var radioButton = formname["RADVAL"+id];
 1155: 	    for (var i=0; i<radioButton.length; i++) {
 1156: 		radioButton[i].checked=false;
 1157: 		if (i == oldpts) {
 1158: 		    radioButton[i].checked=true;
 1159: 		}
 1160: 	    }
 1161: 	}
 1162: 	formname["stores"+id].value = "0";
 1163: 	updateSelect(formname,id);
 1164: 	return;
 1165:     }
 1166: 
 1167:     function clearRadBox(formname,id) {
 1168: 	if (checkSolved(formname,id) == 'noupdate') {
 1169: 	    updateSelect(formname,id);
 1170: 	    return;
 1171: 	}
 1172: 	gradeSelect = formname["GD_SEL"+id];
 1173: 	for (var i=0; i<gradeSelect.length; i++) {
 1174: 	    if (gradeSelect[i].selected) {
 1175: 		var selectx=i;
 1176: 	    }
 1177: 	}
 1178: 	var stores = formname["stores"+id];
 1179: 	if (selectx == stores.value) { return };
 1180: 	var gradeBox = formname["GD_BOX"+id];
 1181: 	gradeBox.value = "";
 1182: 	var radioButton = formname["RADVAL"+id];
 1183: 	for (var i=0; i<radioButton.length; i++) {
 1184: 	    radioButton[i].checked=false;
 1185: 	}
 1186: 	stores.value = selectx;
 1187:     }
 1188: 
 1189:     function checkSolved(formname,id) {
 1190: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1191: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1192: 	    if (!reply) {return "noupdate";}
 1193: 	    formname.overRideScore.value = 'yes';
 1194: 	}
 1195: 	return "update";
 1196:     }
 1197: 
 1198:     function updateSelect(formname,id) {
 1199: 	formname["GD_SEL"+id][0].selected = true;
 1200: 	return;
 1201:     }
 1202: 
 1203: //=========== Check that a point is assigned for all the parts  ============
 1204:     function checksubmit(formname,val,total,parttot) {
 1205: 	formname.gradeOpt.value = val;
 1206: 	if (val == "Save & Next") {
 1207: 	    for (i=0;i<=total;i++) {
 1208: 		for (j=0;j<parttot;j++) {
 1209: 		    var partid = formname["partid"+i+"_"+j].value;
 1210: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1211: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1212: 			if (points == "") {
 1213: 			    var name = formname["name"+i].value;
 1214: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1215: 			    var resp = confirm("You did not assign a score for "+studentID+
 1216: 					       ", part "+partid+". Continue?");
 1217: 			    if (resp == false) {
 1218: 				formname["GD_BOX"+i+"_"+partid].focus();
 1219: 				return false;
 1220: 			    }
 1221: 			}
 1222: 		    }
 1223: 		    
 1224: 		}
 1225: 	    }
 1226: 	    
 1227: 	}
 1228: 	if (val == "Grade Student") {
 1229: 	    formname.showgrading.value = "yes";
 1230: 	    if (formname.Status.value == "") {
 1231: 		formname.Status.value = "Active";
 1232: 	    }
 1233: 	    formname.studentNo.value = total;
 1234: 	}
 1235: 	formname.submit();
 1236:     }
 1237: 
 1238: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1239:     function checkSubmitPage(formname,total) {
 1240: 	noscore = new Array(100);
 1241: 	var ptr = 0;
 1242: 	for (i=1;i<total;i++) {
 1243: 	    var partid = formname["q_"+i].value;
 1244: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1245: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1246: 		var status = formname["solved"+i+"_"+partid].value;
 1247: 		if (points == "" && status != "correct_by_student") {
 1248: 		    noscore[ptr] = i;
 1249: 		    ptr++;
 1250: 		}
 1251: 	    }
 1252: 	}
 1253: 	if (ptr != 0) {
 1254: 	    var sense = ptr == 1 ? ": " : "s: ";
 1255: 	    var prolist = "";
 1256: 	    if (ptr == 1) {
 1257: 		prolist = noscore[0];
 1258: 	    } else {
 1259: 		var i = 0;
 1260: 		while (i < ptr-1) {
 1261: 		    prolist += noscore[i]+", ";
 1262: 		    i++;
 1263: 		}
 1264: 		prolist += "and "+noscore[i];
 1265: 	    }
 1266: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1267: 	    if (resp == false) {
 1268: 		return false;
 1269: 	    }
 1270: 	}
 1271: 
 1272: 	formname.submit();
 1273:     }
 1274: </script>
 1275: SUBJAVASCRIPT
 1276: }
 1277: 
 1278: #--- javascript for essay type problem --
 1279: sub sub_page_kw_js {
 1280:     my $request = shift;
 1281:     my $iconpath = $request->dir_config('lonIconsURL');
 1282:     &commonJSfunctions($request);
 1283: 
 1284:     my $inner_js_msg_central=<<INNERJS;
 1285:     <script text="text/javascript">
 1286:     function checkInput() {
 1287:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1288:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1289:       var usrctr = document.msgcenter.usrctr.value;
 1290:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1291:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1292: 
 1293:       var msgchk = "";
 1294:       if (document.msgcenter.subchk.checked) {
 1295:          msgchk = "msgsub,";
 1296:       }
 1297:       var includemsg = 0;
 1298:       for (var i=1; i<=nmsg; i++) {
 1299:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1300:           var frmmsg = document.msgcenter["msg"+i];
 1301:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1302:           var showflg = opener.document.SCORE["shownOnce"+i];
 1303:           showflg.value = "1";
 1304:           var chkbox = document.msgcenter["msgn"+i];
 1305:           if (chkbox.checked) {
 1306:              msgchk += "savemsg"+i+",";
 1307:              includemsg = 1;
 1308:           }
 1309:       }
 1310:       if (document.msgcenter.newmsgchk.checked) {
 1311:          msgchk += "newmsg"+usrctr;
 1312:          includemsg = 1;
 1313:       }
 1314:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1315:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1316:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1317:       includemsg.value = msgchk;
 1318: 
 1319:       self.close()
 1320: 
 1321:     }
 1322:     </script>
 1323: INNERJS
 1324: 
 1325:     my $inner_js_highlight_central=<<INNERJS;
 1326:  <script type="text/javascript">
 1327:     function updateChoice(flag) {
 1328:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1329:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1330:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1331:       opener.document.SCORE.refresh.value = "on";
 1332:       if (opener.document.SCORE.keywords.value!=""){
 1333:          opener.document.SCORE.submit();
 1334:       }
 1335:       self.close()
 1336:     }
 1337: </script>
 1338: INNERJS
 1339: 
 1340:     my $start_page_msg_central = 
 1341:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1342: 				       {'js_ready'  => 1,
 1343: 					'only_body' => 1,
 1344: 					'bgcolor'   =>'#FFFFFF',});
 1345:     my $end_page_msg_central = 
 1346: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1347: 
 1348: 
 1349:     my $start_page_highlight_central = 
 1350:         &Apache::loncommon::start_page('Highlight Central',
 1351: 				       $inner_js_highlight_central,
 1352: 				       {'js_ready'  => 1,
 1353: 					'only_body' => 1,
 1354: 					'bgcolor'   =>'#FFFFFF',});
 1355:     my $end_page_highlight_central = 
 1356: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1357: 
 1358:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1359:     $docopen=~s/^document\.//;
 1360:     $request->print(<<SUBJAVASCRIPT);
 1361: <script type="text/javascript" language="javascript">
 1362: 
 1363: //===================== Show list of keywords ====================
 1364:   function keywords(formname) {
 1365:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1366:     if (nret==null) return;
 1367:     formname.keywords.value = nret;
 1368: 
 1369:     if (formname.keywords.value != "") {
 1370: 	formname.refresh.value = "on";
 1371: 	formname.submit();
 1372:     }
 1373:     return;
 1374:   }
 1375: 
 1376: //===================== Script to view submitted by ==================
 1377:   function viewSubmitter(submitter) {
 1378:     document.SCORE.refresh.value = "on";
 1379:     document.SCORE.NCT.value = "1";
 1380:     document.SCORE.unamedom0.value = submitter;
 1381:     document.SCORE.submit();
 1382:     return;
 1383:   }
 1384: 
 1385: //===================== Script to add keyword(s) ==================
 1386:   function getSel() {
 1387:     if (document.getSelection) txt = document.getSelection();
 1388:     else if (document.selection) txt = document.selection.createRange().text;
 1389:     else return;
 1390:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1391:     if (cleantxt=="") {
 1392: 	alert("Please select a word or group of words from document and then click this link.");
 1393: 	return;
 1394:     }
 1395:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1396:     if (nret==null) return;
 1397:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1398:     if (document.SCORE.keywords.value != "") {
 1399: 	document.SCORE.refresh.value = "on";
 1400: 	document.SCORE.submit();
 1401:     }
 1402:     return;
 1403:   }
 1404: 
 1405: //====================== Script for composing message ==============
 1406:    // preload images
 1407:    img1 = new Image();
 1408:    img1.src = "$iconpath/mailbkgrd.gif";
 1409:    img2 = new Image();
 1410:    img2.src = "$iconpath/mailto.gif";
 1411: 
 1412:   function msgCenter(msgform,usrctr,fullname) {
 1413:     var Nmsg  = msgform.savemsgN.value;
 1414:     savedMsgHeader(Nmsg,usrctr,fullname);
 1415:     var subject = msgform.msgsub.value;
 1416:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1417:     re = /msgsub/;
 1418:     var shwsel = "";
 1419:     if (re.test(msgchk)) { shwsel = "checked" }
 1420:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1421:     displaySubject(checkEntities(subject),shwsel);
 1422:     for (var i=1; i<=Nmsg; i++) {
 1423: 	var testmsg = "savemsg"+i+",";
 1424: 	re = new RegExp(testmsg,"g");
 1425: 	shwsel = "";
 1426: 	if (re.test(msgchk)) { shwsel = "checked" }
 1427: 	var message = document.SCORE["savemsg"+i].value;
 1428: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1429: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1430: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1431:     }
 1432:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1433:     shwsel = "";
 1434:     re = /newmsg/;
 1435:     if (re.test(msgchk)) { shwsel = "checked" }
 1436:     newMsg(newmsg,shwsel);
 1437:     msgTail(); 
 1438:     return;
 1439:   }
 1440: 
 1441:   function checkEntities(strx) {
 1442:     if (strx.length == 0) return strx;
 1443:     var orgStr = ["&", "<", ">", '"']; 
 1444:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1445:     var counter = 0;
 1446:     while (counter < 4) {
 1447: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1448: 	counter++;
 1449:     }
 1450:     return strx;
 1451:   }
 1452: 
 1453:   function strReplace(strx, orgStr, newStr) {
 1454:     return strx.split(orgStr).join(newStr);
 1455:   }
 1456: 
 1457:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1458:     var height = 70*Nmsg+250;
 1459:     var scrollbar = "no";
 1460:     if (height > 600) {
 1461: 	height = 600;
 1462: 	scrollbar = "yes";
 1463:     }
 1464:     var xpos = (screen.width-600)/2;
 1465:     xpos = (xpos < 0) ? '0' : xpos;
 1466:     var ypos = (screen.height-height)/2-30;
 1467:     ypos = (ypos < 0) ? '0' : ypos;
 1468: 
 1469:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1470:     pWin.focus();
 1471:     pDoc = pWin.document;
 1472:     pDoc.$docopen;
 1473:     pDoc.write('$start_page_msg_central');
 1474: 
 1475:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1476:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1477:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
 1478: 
 1479:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1480:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1481:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
 1482: }
 1483:     function displaySubject(msg,shwsel) {
 1484:     pDoc = pWin.document;
 1485:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1486:     pDoc.write("<td>Subject</td>");
 1487:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1488:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
 1489: }
 1490: 
 1491:   function displaySavedMsg(ctr,msg,shwsel) {
 1492:     pDoc = pWin.document;
 1493:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1494:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
 1495:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1496:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
 1497: }
 1498: 
 1499:   function newMsg(newmsg,shwsel) {
 1500:     pDoc = pWin.document;
 1501:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1502:     pDoc.write("<td align=\\"center\\">New</td>");
 1503:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1504:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
 1505: }
 1506: 
 1507:   function msgTail() {
 1508:     pDoc = pWin.document;
 1509:     pDoc.write("</table>");
 1510:     pDoc.write("</td></tr></table>&nbsp;");
 1511:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1512:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1513:     pDoc.write("</form>");
 1514:     pDoc.write('$end_page_msg_central');
 1515:     pDoc.close();
 1516: }
 1517: 
 1518: //====================== Script for keyword highlight options ==============
 1519:   function kwhighlight() {
 1520:     var kwclr    = document.SCORE.kwclr.value;
 1521:     var kwsize   = document.SCORE.kwsize.value;
 1522:     var kwstyle  = document.SCORE.kwstyle.value;
 1523:     var redsel = "";
 1524:     var grnsel = "";
 1525:     var blusel = "";
 1526:     if (kwclr=="red")   {var redsel="checked"};
 1527:     if (kwclr=="green") {var grnsel="checked"};
 1528:     if (kwclr=="blue")  {var blusel="checked"};
 1529:     var sznsel = "";
 1530:     var sz1sel = "";
 1531:     var sz2sel = "";
 1532:     if (kwsize=="0")  {var sznsel="checked"};
 1533:     if (kwsize=="+1") {var sz1sel="checked"};
 1534:     if (kwsize=="+2") {var sz2sel="checked"};
 1535:     var synsel = "";
 1536:     var syisel = "";
 1537:     var sybsel = "";
 1538:     if (kwstyle=="")    {var synsel="checked"};
 1539:     if (kwstyle=="<i>") {var syisel="checked"};
 1540:     if (kwstyle=="<b>") {var sybsel="checked"};
 1541:     highlightCentral();
 1542:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1543:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1544:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1545:     highlightend();
 1546:     return;
 1547:   }
 1548: 
 1549:   function highlightCentral() {
 1550: //    if (window.hwdWin) window.hwdWin.close();
 1551:     var xpos = (screen.width-400)/2;
 1552:     xpos = (xpos < 0) ? '0' : xpos;
 1553:     var ypos = (screen.height-330)/2-30;
 1554:     ypos = (ypos < 0) ? '0' : ypos;
 1555: 
 1556:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1557:     hwdWin.focus();
 1558:     var hDoc = hwdWin.document;
 1559:     hDoc.$docopen;
 1560:     hDoc.write('$start_page_highlight_central');
 1561:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1562:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
 1563: 
 1564:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1565:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1566:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
 1567:   }
 1568: 
 1569:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1570:     var hDoc = hwdWin.document;
 1571:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1572:     hDoc.write("<td align=\\"left\\">");
 1573:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
 1574:     hDoc.write("<td align=\\"left\\">");
 1575:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
 1576:     hDoc.write("<td align=\\"left\\">");
 1577:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
 1578:     hDoc.write("</tr>");
 1579:   }
 1580: 
 1581:   function highlightend() { 
 1582:     var hDoc = hwdWin.document;
 1583:     hDoc.write("</table>");
 1584:     hDoc.write("</td></tr></table>&nbsp;");
 1585:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1586:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1587:     hDoc.write("</form>");
 1588:     hDoc.write('$end_page_highlight_central');
 1589:     hDoc.close();
 1590:   }
 1591: 
 1592: </script>
 1593: SUBJAVASCRIPT
 1594: }
 1595: 
 1596: sub get_increment {
 1597:     my $increment = $env{'form.increment'};
 1598:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1599:         $increment != .1) {
 1600:         $increment = 1;
 1601:     }
 1602:     return $increment;
 1603: }
 1604: 
 1605: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1606: sub gradeBox {
 1607:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1608:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1609: 	'" src="'.$request->dir_config('lonIconsURL').
 1610: 	'/check.gif" height="16" border="0" />';
 1611:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1612:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
 1613: 		  '<span class="LC_info">problem weight assigned by computer</span>');
 1614:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1615:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1616: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1617:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1618:     my $display_part=&get_display_part($partid,$symb);
 1619:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1620: 				       [$partid]);
 1621:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1622:     if ($last_resets{$partid}) {
 1623:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1624:     }
 1625:     $result.='<table border="0"><tr><td>'.
 1626: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
 1627:     my $ctr = 0;
 1628:     my $thisweight = 0;
 1629:     my $increment = &get_increment();
 1630:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1631:     while ($thisweight<=$wgt) {
 1632: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1633: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1634: 	    $thisweight.')" value="'.$thisweight.'" '.
 1635: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1636: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1637:         $thisweight += $increment;
 1638: 	$ctr++;
 1639:     }
 1640:     $result.='</tr></table>';
 1641:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
 1642:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1643: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1644: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1645: 	$wgt.')" /></td>'."\n";
 1646:     $result.='<td>/'.$wgt.' '.$wgtmsg.
 1647: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1648: 	' </td><td>'."\n";
 1649:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1650: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1651:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1652: 	$result.='<option></option>'.
 1653: 	    '<option selected="selected">excused</option>';
 1654:     } else {
 1655: 	$result.='<option selected="selected"></option>'.
 1656: 	    '<option>excused</option>';
 1657:     }
 1658:     $result.='<option>reset status</option></select>'."\n";
 1659:     $result.="&nbsp;&nbsp;\n";
 1660:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1661: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1662: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1663: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1664:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1665:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1666:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1667:         $aggtries.'" />'."\n";
 1668:     $result.='</td></tr></table>'."\n";
 1669:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1670:     return $result;
 1671: }
 1672: 
 1673: sub handback_box {
 1674:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1675:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1676:     my (@respids);
 1677:      my @part_response_id = &flatten_responseType($responseType);
 1678:     foreach my $part_response_id (@part_response_id) {
 1679:     	my ($part,$resp) = @{ $part_response_id };
 1680:         if ($part eq $partid) {
 1681:             push(@respids,$resp);
 1682:         }
 1683:     }
 1684:     my $result;
 1685:     foreach my $respid (@respids) {
 1686: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1687: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1688: 	next if (!@$files);
 1689: 	my $file_counter = 1;
 1690: 	foreach my $file (@$files) {
 1691: 	    if ($file =~ /\/portfolio\//) {
 1692:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1693:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1694:     	        $file_disp = "$name.$ext";
 1695:     	        $file = $file_path.$file_disp;
 1696:     	        $result.=&mt('Return commented version of [_1] to student.',
 1697:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1698:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1699:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1700:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
 1701:     	        $file_counter++;
 1702: 	    }
 1703: 	}
 1704:     }
 1705:     return $result;    
 1706: }
 1707: 
 1708: sub show_problem {
 1709:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1710:     my $rendered;
 1711:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1712:     &Apache::lonxml::remember_problem_counter();
 1713:     if ($mode eq 'both' or $mode eq 'text') {
 1714: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1715: 						       $env{'request.course.id'},
 1716: 						       undef,\%form);
 1717:     }
 1718:     if ($removeform) {
 1719: 	$rendered=~s|<form(.*?)>||g;
 1720: 	$rendered=~s|</form>||g;
 1721: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1722:     }
 1723:     my $companswer;
 1724:     if ($mode eq 'both' or $mode eq 'answer') {
 1725: 	&Apache::lonxml::restore_problem_counter();
 1726: 	$companswer=
 1727: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1728: 						    $env{'request.course.id'},
 1729: 						    %form);
 1730:     }
 1731:     if ($removeform) {
 1732: 	$companswer=~s|<form(.*?)>||g;
 1733: 	$companswer=~s|</form>||g;
 1734: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1735:     }
 1736:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 1737:     $result.='<table border="0" width="100%">';
 1738:     if ($viewon) {
 1739: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
 1740: 	if ($mode eq 'both' or $mode eq 'text') {
 1741: 	    $result.='View of the problem - ';
 1742: 	} else {
 1743: 	    $result.='Correct answer: ';
 1744: 	}
 1745: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
 1746:     }
 1747:     if ($mode eq 'both') {
 1748: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
 1749: 	$result.='<b>Correct answer:</b><br />'.$companswer;
 1750:     } elsif ($mode eq 'text') {
 1751: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
 1752:     } elsif ($mode eq 'answer') {
 1753: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
 1754:     }
 1755:     $result.='</td></tr></table>';
 1756:     $result.='</td></tr></table><br />';
 1757:     return $result;
 1758: }
 1759: 
 1760: sub files_exist {
 1761:     my ($r, $symb) = @_;
 1762:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1763: 
 1764:     foreach my $student (@students) {
 1765:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1766:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1767: 					      $udom,$uname);
 1768:         my ($string,$timestamp)= &get_last_submission(\%record);
 1769:         foreach my $submission (@$string) {
 1770:             my ($partid,$respid) =
 1771: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1772:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1773: 					   \%record);
 1774:             return 1 if (@$files);
 1775:         }
 1776:     }
 1777:     return 0;
 1778: }
 1779: 
 1780: sub download_all_link {
 1781:     my ($r,$symb) = @_;
 1782:     my $all_students = 
 1783: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1784: 
 1785:     my $parts =
 1786: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1787: 
 1788:     my $identifier = &Apache::loncommon::get_cgi_id();
 1789:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
 1790:                             'cgi.'.$identifier.'.symb' => $symb,
 1791:                             'cgi.'.$identifier.'.parts' => $parts,);
 1792:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1793: 	      &mt('Download All Submitted Documents').'</a>');
 1794:     return
 1795: }
 1796: 
 1797: sub build_section_inputs {
 1798:     my $section_inputs;
 1799:     if ($env{'form.section'} eq '') {
 1800:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1801:     } else {
 1802:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1803:         foreach my $section (@sections) {
 1804:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1805:         }
 1806:     }
 1807:     return $section_inputs;
 1808: }
 1809: 
 1810: # --------------------------- show submissions of a student, option to grade 
 1811: sub submission {
 1812:     my ($request,$counter,$total) = @_;
 1813:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1814:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1815:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1816:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1817:     my $symb = &get_symb($request); 
 1818:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1819: 
 1820:     if (!&canview($usec)) {
 1821: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1822: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1823: 			$env{'request.course.id'}.')</span>');
 1824: 	$request->print(&show_grading_menu_form($symb));
 1825: 	return;
 1826:     }
 1827: 
 1828:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1829:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1830:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1831:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1832:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1833: 	'" src="'.$request->dir_config('lonIconsURL').
 1834: 	'/check.gif" height="16" border="0" />';
 1835: 
 1836:     my %old_essays;
 1837:     # header info
 1838:     if ($counter == 0) {
 1839: 	&sub_page_js($request);
 1840: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1841: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1842: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1843: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1844: 	    &download_all_link($request, $symb);
 1845: 	}
 1846: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
 1847: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
 1848: 
 1849: 	if ($env{'form.handgrade'} eq 'no') {
 1850: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
 1851: 		$checkIcon.' symbol.'."\n";
 1852: 	    $request->print($checkMark);
 1853: 	}
 1854: 
 1855: 	# option to display problem, only once else it cause problems 
 1856:         # with the form later since the problem has a form.
 1857: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1858: 	    my $mode;
 1859: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1860: 		$mode='both';
 1861: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1862: 		$mode='text';
 1863: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1864: 		$mode='answer';
 1865: 	    }
 1866: 	    &Apache::lonxml::clear_problem_counter();
 1867: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1868: 	}
 1869: 
 1870: 	# kwclr is the only variable that is guaranteed to be non blank 
 1871:         # if this subroutine has been called once.
 1872: 	my %keyhash = ();
 1873: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1874: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1875: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1876: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1877: 
 1878: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1879: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1880: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1881: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1882: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1883: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1884: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1885: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1886: 	}
 1887: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1888: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1889: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1890: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1891: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1892: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1893: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1894: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1895: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1896: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1897: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1898: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1899: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1900: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1901: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1902: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1903: 			&build_section_inputs().
 1904: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1905: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1906: 			'<input type="hidden" name="NCT"'.
 1907: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1908: 	if ($env{'form.handgrade'} eq 'yes') {
 1909: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1910: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1911: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1912: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1913: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1914: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1915: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1916: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1917: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1918: 	    }
 1919: 	}
 1920: 	
 1921: 	my ($cts,$prnmsg) = (1,'');
 1922: 	while ($cts <= $env{'form.savemsgN'}) {
 1923: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1924: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1925: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1926: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1927: 		'" />'."\n".
 1928: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1929: 	    $cts++;
 1930: 	}
 1931: 	$request->print($prnmsg);
 1932: 
 1933: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1934: #
 1935: # Print out the keyword options line
 1936: #
 1937: 	    $request->print(<<KEYWORDS);
 1938: &nbsp;<b>Keyword Options:</b>&nbsp;
 1939: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1940: <a href="#" onMouseDown="javascript:getSel(); return false"
 1941:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1942: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1943: KEYWORDS
 1944: #
 1945: # Load the other essays for similarity check
 1946: #
 1947:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1948: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1949: 	    $apath=&escape($apath);
 1950: 	    $apath=~s/\W/\_/gs;
 1951: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 1952:         }
 1953:     }
 1954: 
 1955: # This is where output for one specific student would start
 1956:     my $bgcolor='#DDEEDD';
 1957:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
 1958:     $request->print("\n\n".
 1959:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
 1960: 
 1961:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 1962: 	my $mode;
 1963: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 1964: 	    $mode='both';
 1965: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 1966: 	    $mode='text';
 1967: 	} elsif ($env{'form.vAns'} eq 'all') {
 1968: 	    $mode='answer';
 1969: 	}
 1970: 	&Apache::lonxml::clear_problem_counter();
 1971: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
 1972:     }
 1973: 
 1974:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 1975:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1976: 
 1977:     # Display student info
 1978:     $request->print(($counter == 0 ? '' : '<br />'));
 1979:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
 1980: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
 1981: 
 1982:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
 1983:     $result.='<input type="hidden" name="name'.$counter.
 1984: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 1985: 
 1986:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 1987:     my @col_fullnames;
 1988:     my ($classlist,$fullname);
 1989:     if ($env{'form.handgrade'} eq 'yes') {
 1990: 	($classlist,undef,$fullname) = &getclasslist('all','0');
 1991: 	for (keys (%$handgrade)) {
 1992: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
 1993: 					    '.maxcollaborators',
 1994:                                             $symb,$udom,$uname);
 1995: 	    next if ($ncol <= 0);
 1996:             s/\_/\./g;
 1997:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
 1998:             my @goodcollaborators = ();
 1999:             my @badcollaborators  = ();
 2000: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
 2001: 		$_ =~ s/[\$\^\(\)]//g;
 2002: 		next if ($_ eq '');
 2003: 		my ($co_name,$co_dom) = split /\@|:/,$_;
 2004: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2005: 		next if ($co_name eq $uname && $co_dom eq $udom);
 2006: 		# Doing this grep allows 'fuzzy' specification
 2007: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
 2008: 		if (! scalar(@Matches)) {
 2009: 		    push @badcollaborators,$_;
 2010: 		} else {
 2011: 		    push @goodcollaborators, @Matches;
 2012: 		}
 2013: 	    }
 2014:             if (scalar(@goodcollaborators) != 0) {
 2015:                 $result.='<b>Collaborators: </b>';
 2016:                 foreach (@goodcollaborators) {
 2017: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
 2018: 		    push @col_fullnames, $givenn.' '.$lastname;
 2019: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
 2020: 		}
 2021:                 $result.='<br />'."\n";
 2022: 		my ($part)=split(/\./,$_);
 2023: 		$result.='<input type="hidden" name="collaborator'.$counter.
 2024: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
 2025: 		    "\n";
 2026: 	    }
 2027: 	    if (scalar(@badcollaborators) > 0) {
 2028: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
 2029: 		$result.='This student has submitted ';
 2030: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
 2031: 		$result .= ': '.join(', ',@badcollaborators);
 2032: 		$result .= '</td></tr></table>';
 2033: 	    }         
 2034: 	    if (scalar(@badcollaborators > $ncol)) {
 2035: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
 2036: 		$result .= 'This student has submitted too many '.
 2037: 		    'collaborators.  Maximum is '.$ncol.'.';
 2038: 		$result .= '</td></tr></table>';
 2039: 	    }
 2040: 	}
 2041:     }
 2042:     $request->print($result."\n");
 2043: 
 2044:     # print student answer/submission
 2045:     # Options are (1) Handgaded submission only
 2046:     #             (2) Last submission, includes submission that is not handgraded 
 2047:     #                  (for multi-response type part)
 2048:     #             (3) Last submission plus the parts info
 2049:     #             (4) The whole record for this student
 2050:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2051: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2052: 	my $lastsubonly=''.
 2053: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
 2054: 	     $$timestamp)."</td></tr>\n";
 2055: 	if ($$timestamp eq '') {
 2056: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
 2057: 	} else {
 2058: 	    my %seenparts;
 2059: 	    my @part_response_id = &flatten_responseType($responseType);
 2060: 	    foreach my $part (@part_response_id) {
 2061: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2062: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2063: 
 2064: 		my ($partid,$respid) = @{ $part };
 2065: 		my $display_part=&get_display_part($partid,$symb);
 2066: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2067: 		    if (exists($seenparts{$partid})) { next; }
 2068: 		    $seenparts{$partid}=1;
 2069: 		    my $submitby='<b>Part:</b> '.$display_part.
 2070: 			' <b>Collaborative submission by:</b> '.
 2071: 			'<a href="javascript:viewSubmitter(\''.
 2072: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2073: 			'\');" target="_self">'.
 2074: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2075: 		    $request->print($submitby);
 2076: 		    next;
 2077: 		}
 2078: 		my $responsetype = $responseType->{$partid}->{$respid};
 2079: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2080: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
 2081: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2082: 			' )</span>&nbsp; &nbsp;'.
 2083: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
 2084: 		    next;
 2085: 		}
 2086: 		foreach (@$string) {
 2087: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
 2088: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2089: 		    my ($ressub,$subval) = split(/:/,$_,2);
 2090: 		    # Similarity check
 2091: 		    my $similar='';
 2092: 		    if($env{'form.checkPlag'}){
 2093: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2094: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2095: 			if ($osim) {
 2096: 			    $osim=int($osim*100.0);
 2097: 			    my %old_course_desc = 
 2098: 				&Apache::lonnet::coursedescription($ocrsid,
 2099: 								   {'one_time' => 1});
 2100: 
 2101: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2102: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2103: 				    $osim,
 2104: 				    &Apache::loncommon::plainname($oname,$odom),
 2105: 				    $oname,$odom,
 2106: 				    $old_course_desc{'description'},
 2107: 				    $old_course_desc{'num'},
 2108: 				    $old_course_desc{'domain'}).
 2109: 				'</span></h3><blockquote><i>'.
 2110: 				&keywords_highlight($oessay).
 2111: 				'</i></blockquote><hr />';
 2112: 			}
 2113: 		    }
 2114: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2115: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2116: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2117: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2118: 			my $display_part=&get_display_part($partid,$symb);
 2119: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
 2120: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2121: 			    ' )</span>&nbsp; &nbsp;';
 2122: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2123: 			if (@$files) {
 2124: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
 2125: 			    my $file_counter = 0;
 2126: 			    foreach my $file (@$files) {
 2127: 			        $file_counter ++;
 2128: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2129: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2130: 			    }
 2131: 			    $lastsubonly.='<br />';
 2132: 			}
 2133: 			$lastsubonly.='<b>Submitted Answer: </b>'.
 2134: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2135: 					 $respid,\%record,$order);
 2136: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2137: 		    }
 2138: 		}
 2139: 	    }
 2140: 	}
 2141: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
 2142: 	$request->print($lastsubonly);
 2143:     } elsif ($env{'form.lastSub'} eq 'datesub') {
 2144: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2145: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2146:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2147: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2148: 								 $env{'request.course.id'},
 2149: 								 $last,'.submission',
 2150: 								 'Apache::grades::keywords_highlight'));
 2151:     }
 2152: 
 2153:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2154: 	.$udom.'" />'."\n");
 2155:     
 2156:     # return if view submission with no grading option
 2157:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2158: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2159: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2160: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2161: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
 2162: 	if (($env{'form.command'} eq 'submission') || 
 2163: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2164: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2165: 	}
 2166: 	$request->print($toGrade);
 2167: 	return;
 2168:     } else {
 2169: 	$request->print('</td></tr></table></td></tr></table>'."\n");
 2170:     }
 2171: 
 2172:     # essay grading message center
 2173:     if ($env{'form.handgrade'} eq 'yes') {
 2174: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2175: 	my $msgfor = $givenn.' '.$lastname;
 2176: 	if (scalar(@col_fullnames) > 0) {
 2177: 	    my $lastone = pop @col_fullnames;
 2178: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
 2179: 	}
 2180: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2181: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2182: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2183: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2184: 	    ',\''.$msgfor.'\');" target="_self">'.
 2185: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2186: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2187: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2188: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2189: 	    '<br />&nbsp;('.
 2190: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
 2191: 	$request->print($result);
 2192:     }
 2193:     if ($perm{'vgr'}) {
 2194: 	$request->print('<br />'.
 2195: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2196: 						   $uname,$udom,'check'));
 2197:     }
 2198:     if ($perm{'opa'}) {
 2199: 	$request->print('<br />'.
 2200: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2201: 					 $uname,$udom,$symb,'check'));
 2202:     }
 2203: 
 2204:     my %seen = ();
 2205:     my @partlist;
 2206:     my @gradePartRespid;
 2207:     my @part_response_id = &flatten_responseType($responseType);
 2208:     foreach my $part_response_id (@part_response_id) {
 2209:     	my ($partid,$respid) = @{ $part_response_id };
 2210: 	my $part_resp = join('_',@{ $part_response_id });
 2211: 	next if ($seen{$partid} > 0);
 2212: 	$seen{$partid}++;
 2213: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2214: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2215: 	push @partlist,$partid;
 2216: 	push @gradePartRespid,$partid.'.'.$respid;
 2217: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2218:     }
 2219:     $result='<input type="hidden" name="partlist'.$counter.
 2220: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2221:     $result.='<input type="hidden" name="gradePartRespid'.
 2222: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2223:     my $ctr = 0;
 2224:     while ($ctr < scalar(@partlist)) {
 2225: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2226: 	    $partlist[$ctr].'" />'."\n";
 2227: 	$ctr++;
 2228:     }
 2229:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
 2230: 
 2231: # Done with printing info for one student
 2232: 
 2233:     $request->print('</td></tr></table></p>');
 2234: 
 2235: 
 2236:     # print end of form
 2237:     if ($counter == $total) {
 2238: 	my $endform='<table border="0"><tr><td>'."\n";
 2239: 	$endform.='<input type="button" value="Save & Next" '.
 2240: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2241: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2242: 	my $ntstu ='<select name="NTSTU">'.
 2243: 	    '<option>1</option><option>2</option>'.
 2244: 	    '<option>3</option><option>5</option>'.
 2245: 	    '<option>7</option><option>10</option></select>'."\n";
 2246: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2247: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2248: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
 2249: 	$endform.='<input type="button" value="Previous" '.
 2250: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2251: 	    '<input type="button" value="Next" '.
 2252: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2253: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
 2254:         $endform.="<input type='hidden' value='".&get_increment().
 2255:             "' name='increment' />";
 2256: 	$endform.='</td><tr></table></form>';
 2257: 	$endform.=&show_grading_menu_form($symb);
 2258: 	$request->print($endform);
 2259:     }
 2260:     return '';
 2261: }
 2262: 
 2263: #--- Retrieve the last submission for all the parts
 2264: sub get_last_submission {
 2265:     my ($returnhash)=@_;
 2266:     my (@string,$timestamp);
 2267:     if ($$returnhash{'version'}) {
 2268: 	my %lasthash=();
 2269: 	my ($version);
 2270: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2271: 	    foreach my $key (sort(split(/\:/,
 2272: 					$$returnhash{$version.':keys'}))) {
 2273: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2274: 		$timestamp = 
 2275: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
 2276: 	    }
 2277: 	}
 2278: 	foreach my $key (keys(%lasthash)) {
 2279: 	    next if ($key !~ /\.submission$/);
 2280: 
 2281: 	    my ($partid,$foo) = split(/submission$/,$key);
 2282: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2283: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2284: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2285: 	}
 2286:     }
 2287:     if (!@string) {
 2288: 	$string[0] =
 2289: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2290:     }
 2291:     return (\@string,\$timestamp);
 2292: }
 2293: 
 2294: #--- High light keywords, with style choosen by user.
 2295: sub keywords_highlight {
 2296:     my $string    = shift;
 2297:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2298:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2299:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2300:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2301:     foreach my $keyword (@keylist) {
 2302: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2303:     }
 2304:     return $string;
 2305: }
 2306: 
 2307: #--- Called from submission routine
 2308: sub processHandGrade {
 2309:     my ($request) = shift;
 2310:     my $symb   = &get_symb($request);
 2311:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2312:     my $button = $env{'form.gradeOpt'};
 2313:     my $ngrade = $env{'form.NCT'};
 2314:     my $ntstu  = $env{'form.NTSTU'};
 2315:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2316:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2317: 
 2318:     if ($button eq 'Save & Next') {
 2319: 	my $ctr = 0;
 2320: 	while ($ctr < $ngrade) {
 2321: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2322: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2323: 	    if ($errorflag eq 'no_score') {
 2324: 		$ctr++;
 2325: 		next;
 2326: 	    }
 2327: 	    if ($errorflag eq 'not_allowed') {
 2328: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2329: 		$ctr++;
 2330: 		next;
 2331: 	    }
 2332: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2333: 	    my ($subject,$message,$msgstatus) = ('','','');
 2334: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2335:             my ($feedurl,$showsymb) =
 2336: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2337: 	    my $messagetail;
 2338: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2339: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2340: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2341: 		$subject.=' ['.$restitle.']';
 2342: 		my (@msgnum) = split(/,/,$includemsg);
 2343: 		foreach (@msgnum) {
 2344: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2345: 		}
 2346: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2347: 		if ($env{'form.withgrades'.$ctr}) {
 2348: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2349: 		    $messagetail = " for <a href=\"".
 2350: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2351: 		}
 2352: 		$msgstatus = 
 2353:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2354: 						     $message.$messagetail,
 2355:                                                      undef,$feedurl,undef,
 2356:                                                      undef,undef,$showsymb,
 2357:                                                      $restitle);
 2358: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2359: 				$msgstatus);
 2360: 	    }
 2361: 	    if ($env{'form.collaborator'.$ctr}) {
 2362: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2363: 		foreach my $collabstr (@collabstrs) {
 2364: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2365: 		    foreach my $collaborator (@collaborators) {
 2366: 			my ($errorflag,$pts,$wgt) = 
 2367: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2368: 					   $env{'form.unamedom'.$ctr},$part);
 2369: 			if ($errorflag eq 'not_allowed') {
 2370: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2371: 			    next;
 2372: 			} elsif ($message ne '') {
 2373: 			    my ($baseurl,$showsymb) = 
 2374: 				&get_feedurl_and_symb($symb,$collaborator,
 2375: 						      $udom);
 2376: 			    if ($env{'form.withgrades'.$ctr}) {
 2377: 				$messagetail = " for <a href=\"".
 2378:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2379: 			    }
 2380: 			    $msgstatus = 
 2381: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2382: 			}
 2383: 		    }
 2384: 		}
 2385: 	    }
 2386: 	    $ctr++;
 2387: 	}
 2388:     }
 2389: 
 2390:     if ($env{'form.handgrade'} eq 'yes') {
 2391: 	# Keywords sorted in alphabatical order
 2392: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2393: 	my %keyhash = ();
 2394: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2395: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2396: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2397: 	$env{'form.keywords'} = join(' ',@keywords);
 2398: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2399: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2400: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2401: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2402: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2403: 
 2404: 	# message center - Order of message gets changed. Blank line is eliminated.
 2405: 	# New messages are saved in env for the next student.
 2406: 	# All messages are saved in nohist_handgrade.db
 2407: 	my ($ctr,$idx) = (1,1);
 2408: 	while ($ctr <= $env{'form.savemsgN'}) {
 2409: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2410: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2411: 		$idx++;
 2412: 	    }
 2413: 	    $ctr++;
 2414: 	}
 2415: 	$ctr = 0;
 2416: 	while ($ctr < $ngrade) {
 2417: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2418: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2419: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2420: 		$idx++;
 2421: 	    }
 2422: 	    $ctr++;
 2423: 	}
 2424: 	$env{'form.savemsgN'} = --$idx;
 2425: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2426: 	my $putresult = &Apache::lonnet::put
 2427: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2428:     }
 2429:     # Called by Save & Refresh from Highlight Attribute Window
 2430:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2431:     if ($env{'form.refresh'} eq 'on') {
 2432: 	my ($ctr,$total) = (0,0);
 2433: 	while ($ctr < $ngrade) {
 2434: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2435: 	    $ctr++;
 2436: 	}
 2437: 	$env{'form.NTSTU'}=$ngrade;
 2438: 	$ctr = 0;
 2439: 	while ($ctr < $total) {
 2440: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2441: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2442: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2443: 	    &submission($request,$ctr,$total-1);
 2444: 	    $ctr++;
 2445: 	}
 2446: 	return '';
 2447:     }
 2448: 
 2449: # Go directly to grade student - from submission or link from chart page
 2450:     if ($button eq 'Grade Student') {
 2451: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2452: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2453: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2454: 	$env{'form.fullname'} = $$fullname{$processUser};
 2455: 	&submission($request,0,0);
 2456: 	return '';
 2457:     }
 2458: 
 2459:     # Get the next/previous one or group of students
 2460:     my $firststu = $env{'form.unamedom0'};
 2461:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2462:     my $ctr = 2;
 2463:     while ($laststu eq '') {
 2464: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2465: 	$ctr++;
 2466: 	$laststu = $firststu if ($ctr > $ngrade);
 2467:     }
 2468: 
 2469:     my (@parsedlist,@nextlist);
 2470:     my ($nextflg) = 0;
 2471:     foreach (sort 
 2472: 	     {
 2473: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2474: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2475: 		 }
 2476: 		 return $a cmp $b;
 2477: 	     } (keys(%$fullname))) {
 2478: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2479: 	    push @parsedlist,$_;
 2480: 	}
 2481: 	$nextflg = 1 if ($_ eq $laststu);
 2482: 	if ($button eq 'Previous') {
 2483: 	    last if ($_ eq $firststu);
 2484: 	    push @parsedlist,$_;
 2485: 	}
 2486:     }
 2487:     $ctr = 0;
 2488:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2489:     my ($partlist) = &response_type($symb);
 2490:     foreach my $student (@parsedlist) {
 2491: 	my $submitonly=$env{'form.submitonly'};
 2492: 	my ($uname,$udom) = split(/:/,$student);
 2493: 	
 2494: 	if ($submitonly eq 'queued') {
 2495: 	    my %queue_status = 
 2496: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2497: 							$udom,$uname);
 2498: 	    next if (!defined($queue_status{'gradingqueue'}));
 2499: 	}
 2500: 
 2501: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2502: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2503: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2504: 	    my $submitted = 0;
 2505: 	    my $ungraded = 0;
 2506: 	    my $incorrect = 0;
 2507: 	    foreach (keys(%status)) {
 2508: 		$submitted = 1 if ($status{$_} ne 'nothing');
 2509: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
 2510: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 2511: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 2512: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2513: 		    $submitted = 0;
 2514: 		}
 2515: 	    }
 2516: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2517: 				     $submitonly eq 'incorrect' ||
 2518: 				     $submitonly eq 'graded'));
 2519: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2520: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2521: 	}
 2522: 	push @nextlist,$student if ($ctr < $ntstu);
 2523: 	last if ($ctr == $ntstu);
 2524: 	$ctr++;
 2525:     }
 2526: 
 2527:     $ctr = 0;
 2528:     my $total = scalar(@nextlist)-1;
 2529: 
 2530:     foreach (sort @nextlist) {
 2531: 	my ($uname,$udom,$submitter) = split(/:/);
 2532: 	$env{'form.student'}  = $uname;
 2533: 	$env{'form.userdom'}  = $udom;
 2534: 	$env{'form.fullname'} = $$fullname{$_};
 2535: 	&submission($request,$ctr,$total);
 2536: 	$ctr++;
 2537:     }
 2538:     if ($total < 0) {
 2539: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
 2540: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
 2541: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
 2542: 	$the_end.=&show_grading_menu_form($symb);
 2543: 	$request->print($the_end);
 2544:     }
 2545:     return '';
 2546: }
 2547: 
 2548: #---- Save the score and award for each student, if changed
 2549: sub saveHandGrade {
 2550:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2551:     my @version_parts;
 2552:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2553: 					   $env{'request.course.id'});
 2554:     if (!&canmodify($usec)) { return('not_allowed'); }
 2555:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2556:     my @parts_graded;
 2557:     my %newrecord  = ();
 2558:     my ($pts,$wgt) = ('','');
 2559:     my %aggregate = ();
 2560:     my $aggregateflag = 0;
 2561:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2562:     foreach my $new_part (@parts) {
 2563: 	#collaborator ($submi may vary for different parts
 2564: 	if ($submitter && $new_part ne $part) { next; }
 2565: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2566: 	if ($dropMenu eq 'excused') {
 2567: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2568: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2569: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2570: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2571: 		}
 2572: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2573: 	    }
 2574: 	} elsif ($dropMenu eq 'reset status'
 2575: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2576: 	    foreach my $key (keys (%record)) {
 2577: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2578: 	    }
 2579: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2580: 		"$env{'user.name'}:$env{'user.domain'}";
 2581:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2582: 
 2583:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2584: 					       [$new_part]);
 2585:             my $aggtries =$totaltries;
 2586:             if ($last_resets{$new_part}) {
 2587:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2588: 					   $new_part);
 2589:             }
 2590: 
 2591:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2592:             if ($aggtries > 0) {
 2593:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2594:                 $aggregateflag = 1;
 2595:             }
 2596: 	} elsif ($dropMenu eq '') {
 2597: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2598: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2599: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2600: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2601: 		next;
 2602: 	    }
 2603: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2604: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2605: 	    my $partial= $pts/$wgt;
 2606: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2607: 		#do not update score for part if not changed.
 2608:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2609: 		next;
 2610: 	    } else {
 2611: 	        push @parts_graded, $new_part;
 2612: 	    }
 2613: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2614: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2615: 	    }
 2616: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2617: 	    if ($partial == 0) {
 2618: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2619: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2620: 		}
 2621: 	    } else {
 2622: 		if ($record{$reckey} ne 'correct_by_override') {
 2623: 		    $newrecord{$reckey} = 'correct_by_override';
 2624: 		}
 2625: 	    }	    
 2626: 	    if ($submitter && 
 2627: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2628: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2629: 	    }
 2630: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2631: 		"$env{'user.name'}:$env{'user.domain'}";
 2632: 	}
 2633: 	# unless problem has been graded, set flag to version the submitted files
 2634: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2635: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2636: 	        $dropMenu eq 'reset status')
 2637: 	   {
 2638: 	    push (@version_parts,$new_part);
 2639: 	}
 2640:     }
 2641:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2642:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2643: 
 2644:     if (%newrecord) {
 2645:         if (@version_parts) {
 2646:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2647:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2648: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2649: 	    foreach my $new_part (@version_parts) {
 2650: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2651: 				$new_part,\%newrecord);
 2652: 	    }
 2653:         }
 2654: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2655: 				$env{'request.course.id'},$domain,$stuname);
 2656: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2657: 				     $cdom,$cnum,$domain,$stuname);
 2658:     }
 2659:     if ($aggregateflag) {
 2660:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2661: 			      $cdom,$cnum);
 2662:     }
 2663:     return ('',$pts,$wgt);
 2664: }
 2665: 
 2666: sub check_and_remove_from_queue {
 2667:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2668:     my @ungraded_parts;
 2669:     foreach my $part (@{$parts}) {
 2670: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2671: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2672: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2673: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2674: 		) {
 2675: 	    push(@ungraded_parts, $part);
 2676: 	}
 2677:     }
 2678:     if ( !@ungraded_parts ) {
 2679: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2680: 					       $cnum,$domain,$stuname);
 2681:     }
 2682: }
 2683: 
 2684: sub handback_files {
 2685:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2686:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
 2687:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2688: 
 2689:     my @part_response_id = &flatten_responseType($responseType);
 2690:     foreach my $part_response_id (@part_response_id) {
 2691:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2692: 	my $part_resp = join('_',@{ $part_response_id });
 2693:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2694:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2695:                 my $file_counter = 1;
 2696: 		my $file_msg;
 2697:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2698:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2699:                     my ($directory,$answer_file) = 
 2700:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2701:                     my ($answer_name,$answer_ver,$answer_ext) =
 2702: 		        &file_name_version_ext($answer_file);
 2703: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2704: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
 2705: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2706:                     # fix file name
 2707:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2708:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2709:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2710:             	                                $save_file_name);
 2711:                     if ($result !~ m|^/uploaded/|) {
 2712:                         $request->print('<span class="LC_error">An error occurred ('.$result.
 2713:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
 2714:                     } else {
 2715:                         # mark the file as read only
 2716:                         my @files = ($save_file_name);
 2717:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2718:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2719: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2720: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2721: 			}
 2722:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2723: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2724: 
 2725:                     }
 2726:                     $request->print("<br />".$fname." will be the uploaded file name");
 2727:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2728:                     $file_counter++;
 2729:                 }
 2730: 		my $subject = "File Handed Back by Instructor ";
 2731: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2732: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2733: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2734: 		$message .= " and can be found in your portfolio space.";
 2735: 		my ($feedurl,$showsymb) = 
 2736: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2737:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2738: 		my $msgstatus = 
 2739:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2740: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2741:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2742:             }
 2743:         }
 2744:     return;
 2745: }
 2746: 
 2747: sub get_feedurl_and_symb {
 2748:     my ($symb,$uname,$udom) = @_;
 2749:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2750:     $url = &Apache::lonnet::clutter($url);
 2751:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2752: 					$symb,$udom,$uname);
 2753:     if ($encrypturl =~ /^yes$/i) {
 2754: 	&Apache::lonenc::encrypted(\$url,1);
 2755: 	&Apache::lonenc::encrypted(\$symb,1);
 2756:     }
 2757:     return ($url,$symb);
 2758: }
 2759: 
 2760: sub get_submitted_files {
 2761:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2762:     my @files;
 2763:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2764:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2765:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2766:     	    push(@files,$file_url.$file);
 2767:         }
 2768:     }
 2769:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2770:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2771:     }
 2772:     return (\@files);
 2773: }
 2774: 
 2775: # ----------- Provides number of tries since last reset.
 2776: sub get_num_tries {
 2777:     my ($record,$last_reset,$part) = @_;
 2778:     my $timestamp = '';
 2779:     my $num_tries = 0;
 2780:     if ($$record{'version'}) {
 2781:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2782:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2783:                 $timestamp = $$record{$version.':timestamp'};
 2784:                 if ($timestamp > $last_reset) {
 2785:                     $num_tries ++;
 2786:                 } else {
 2787:                     last;
 2788:                 }
 2789:             }
 2790:         }
 2791:     }
 2792:     return $num_tries;
 2793: }
 2794: 
 2795: # ----------- Determine decrements required in aggregate totals 
 2796: sub decrement_aggs {
 2797:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2798:     my %decrement = (
 2799:                         attempts => 0,
 2800:                         users => 0,
 2801:                         correct => 0
 2802:                     );
 2803:     $decrement{'attempts'} = $aggtries;
 2804:     if ($solvedstatus =~ /^correct/) {
 2805:         $decrement{'correct'} = 1;
 2806:     }
 2807:     if ($aggtries == $totaltries) {
 2808:         $decrement{'users'} = 1;
 2809:     }
 2810:     foreach my $type (keys (%decrement)) {
 2811:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2812:     }
 2813:     return;
 2814: }
 2815: 
 2816: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2817: sub get_last_resets {
 2818:     my ($symb,$courseid,$partids) =@_;
 2819:     my %last_resets;
 2820:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2821:     my $cname = $env{'course.'.$courseid.'.num'};
 2822:     my @keys;
 2823:     foreach my $part (@{$partids}) {
 2824: 	push(@keys,"$symb\0$part\0resettime");
 2825:     }
 2826:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2827: 				     $cdom,$cname);
 2828:     foreach my $part (@{$partids}) {
 2829: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2830:     }
 2831:     return %last_resets;
 2832: }
 2833: 
 2834: # ----------- Handles creating versions for portfolio files as answers
 2835: sub version_portfiles {
 2836:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2837:     my $version_parts = join('|',@$v_flag);
 2838:     my @returned_keys;
 2839:     my $parts = join('|', @$parts_graded);
 2840:     my $portfolio_root = &propath($domain,$stu_name).
 2841: 	'/userfiles/portfolio';
 2842:     foreach my $key (keys(%$record)) {
 2843:         my $new_portfiles;
 2844:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2845:             my @versioned_portfiles;
 2846:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2847:             foreach my $file (@portfiles) {
 2848:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2849:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2850: 		my ($answer_name,$answer_ver,$answer_ext) =
 2851: 		    &file_name_version_ext($answer_file);
 2852:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
 2853:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2854:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2855:                 if ($new_answer ne 'problem getting file') {
 2856:                     push(@versioned_portfiles, $directory.$new_answer);
 2857:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2858:                         [$directory.$new_answer],
 2859:                         [$symb,$env{'request.course.id'},'graded']);
 2860:                 }
 2861:             }
 2862:             $$record{$key} = join(',',@versioned_portfiles);
 2863:             push(@returned_keys,$key);
 2864:         }
 2865:     } 
 2866:     return (@returned_keys);   
 2867: }
 2868: 
 2869: sub get_next_version {
 2870:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2871:     my $version;
 2872:     foreach my $row (@$dir_list) {
 2873:         my ($file) = split(/\&/,$row,2);
 2874:         my ($file_name,$file_version,$file_ext) =
 2875: 	    &file_name_version_ext($file);
 2876:         if (($file_name eq $answer_name) && 
 2877: 	    ($file_ext eq $answer_ext)) {
 2878:                 # gets here if filename and extension match, regardless of version
 2879:                 if ($file_version ne '') {
 2880:                 # a versioned file is found  so save it for later
 2881:                 if ($file_version > $version) {
 2882: 		    $version = $file_version;
 2883: 	        }
 2884:             }
 2885:         }
 2886:     } 
 2887:     $version ++;
 2888:     return($version);
 2889: }
 2890: 
 2891: sub version_selected_portfile {
 2892:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2893:     my ($answer_name,$answer_ver,$answer_ext) =
 2894:         &file_name_version_ext($file_name);
 2895:     my $new_answer;
 2896:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2897:     if($env{'form.copy'} eq '-1') {
 2898:         $new_answer = 'problem getting file';
 2899:     } else {
 2900:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2901:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2902:                             $stu_name,$domain,'copy',
 2903: 		        '/portfolio'.$directory.$new_answer);
 2904:     }    
 2905:     return ($new_answer);
 2906: }
 2907: 
 2908: sub file_name_version_ext {
 2909:     my ($file)=@_;
 2910:     my @file_parts = split(/\./, $file);
 2911:     my ($name,$version,$ext);
 2912:     if (@file_parts > 1) {
 2913: 	$ext=pop(@file_parts);
 2914: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 2915: 	    $version=pop(@file_parts);
 2916: 	}
 2917: 	$name=join('.',@file_parts);
 2918:     } else {
 2919: 	$name=join('.',@file_parts);
 2920:     }
 2921:     return($name,$version,$ext);
 2922: }
 2923: 
 2924: #--------------------------------------------------------------------------------------
 2925: #
 2926: #-------------------------- Next few routines handles grading by section or whole class
 2927: #
 2928: #--- Javascript to handle grading by section or whole class
 2929: sub viewgrades_js {
 2930:     my ($request) = shift;
 2931: 
 2932:     $request->print(<<VIEWJAVASCRIPT);
 2933: <script type="text/javascript" language="javascript">
 2934:    function writePoint(partid,weight,point) {
 2935: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2936: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2937: 	if (point == "textval") {
 2938: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 2939: 	    if (isNaN(point) || parseFloat(point) < 0) {
 2940: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 2941: 		var resetbox = false;
 2942: 		for (var i=0; i<radioButton.length; i++) {
 2943: 		    if (radioButton[i].checked) {
 2944: 			textbox.value = i;
 2945: 			resetbox = true;
 2946: 		    }
 2947: 		}
 2948: 		if (!resetbox) {
 2949: 		    textbox.value = "";
 2950: 		}
 2951: 		return;
 2952: 	    }
 2953: 	    if (parseFloat(point) > parseFloat(weight)) {
 2954: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 2955: 				   ") greater than the weight for the part. Accept?");
 2956: 		if (resp == false) {
 2957: 		    textbox.value = "";
 2958: 		    return;
 2959: 		}
 2960: 	    }
 2961: 	    for (var i=0; i<radioButton.length; i++) {
 2962: 		radioButton[i].checked=false;
 2963: 		if (parseFloat(point) == i) {
 2964: 		    radioButton[i].checked=true;
 2965: 		}
 2966: 	    }
 2967: 
 2968: 	} else {
 2969: 	    textbox.value = parseFloat(point);
 2970: 	}
 2971: 	for (i=0;i<document.classgrade.total.value;i++) {
 2972: 	    var user = document.classgrade["ctr"+i].value;
 2973: 	    user = user.replace(new RegExp(':', 'g'),"_");
 2974: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2975: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2976: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2977: 	    if (saveval != "correct") {
 2978: 		scorename.value = point;
 2979: 		if (selname[0].selected != true) {
 2980: 		    selname[0].selected = true;
 2981: 		}
 2982: 	    }
 2983: 	}
 2984: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 2985:     }
 2986: 
 2987:     function writeRadText(partid,weight) {
 2988: 	var selval   = document.classgrade["SELVAL_"+partid];
 2989: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2990:         var override = document.classgrade["FORCE_"+partid].checked;
 2991: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2992: 	if (selval[1].selected || selval[2].selected) {
 2993: 	    for (var i=0; i<radioButton.length; i++) {
 2994: 		radioButton[i].checked=false;
 2995: 
 2996: 	    }
 2997: 	    textbox.value = "";
 2998: 
 2999: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3000: 		var user = document.classgrade["ctr"+i].value;
 3001: 		user = user.replace(new RegExp(':', 'g'),"_");
 3002: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3003: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3004: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3005: 		if ((saveval != "correct") || override) {
 3006: 		    scorename.value = "";
 3007: 		    if (selval[1].selected) {
 3008: 			selname[1].selected = true;
 3009: 		    } else {
 3010: 			selname[2].selected = true;
 3011: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3012: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3013: 		    }
 3014: 		}
 3015: 	    }
 3016: 	} else {
 3017: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3018: 		var user = document.classgrade["ctr"+i].value;
 3019: 		user = user.replace(new RegExp(':', 'g'),"_");
 3020: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3021: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3022: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3023: 		if ((saveval != "correct") || override) {
 3024: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3025: 		    selname[0].selected = true;
 3026: 		}
 3027: 	    }
 3028: 	}	    
 3029:     }
 3030: 
 3031:     function changeSelect(partid,user) {
 3032: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3033: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3034: 	var point  = textbox.value;
 3035: 	var weight = document.classgrade["weight_"+partid].value;
 3036: 
 3037: 	if (isNaN(point) || parseFloat(point) < 0) {
 3038: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3039: 	    textbox.value = "";
 3040: 	    return;
 3041: 	}
 3042: 	if (parseFloat(point) > parseFloat(weight)) {
 3043: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3044: 			       ") greater than the weight of the part. Accept?");
 3045: 	    if (resp == false) {
 3046: 		textbox.value = "";
 3047: 		return;
 3048: 	    }
 3049: 	}
 3050: 	selval[0].selected = true;
 3051:     }
 3052: 
 3053:     function changeOneScore(partid,user) {
 3054: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3055: 	if (selval[1].selected || selval[2].selected) {
 3056: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3057: 	    if (selval[2].selected) {
 3058: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3059: 	    }
 3060:         }
 3061:     }
 3062: 
 3063:     function resetEntry(numpart) {
 3064: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3065: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3066: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3067: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3068: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3069: 	    for (var i=0; i<radioButton.length; i++) {
 3070: 		radioButton[i].checked=false;
 3071: 
 3072: 	    }
 3073: 	    textbox.value = "";
 3074: 	    selval[0].selected = true;
 3075: 
 3076: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3077: 		var user = document.classgrade["ctr"+i].value;
 3078: 		user = user.replace(new RegExp(':', 'g'),"_");
 3079: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3080: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3081: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3082: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3083: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3084: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3085: 		if (saveselval == "excused") {
 3086: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3087: 		} else {
 3088: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3089: 		}
 3090: 	    }
 3091: 	}
 3092:     }
 3093: 
 3094: </script>
 3095: VIEWJAVASCRIPT
 3096: }
 3097: 
 3098: #--- show scores for a section or whole class w/ option to change/update a score
 3099: sub viewgrades {
 3100:     my ($request) = shift;
 3101:     &viewgrades_js($request);
 3102: 
 3103:     my ($symb) = &get_symb($request);
 3104:     #need to make sure we have the correct data for later EXT calls, 
 3105:     #thus invalidate the cache
 3106:     &Apache::lonnet::devalidatecourseresdata(
 3107:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3108:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3109:     &Apache::lonnet::clear_EXT_cache_status();
 3110: 
 3111:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3112:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
 3113: 
 3114:     #view individual student submission form - called using Javascript viewOneStudent
 3115:     $result.=&jscriptNform($symb);
 3116: 
 3117:     #beginning of class grading form
 3118:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3119:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3120: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3121: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3122: 	&build_section_inputs().
 3123: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3124: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3125: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3126: 
 3127:     my $sectionClass;
 3128:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3129:     if ($env{'form.section'} eq 'all') {
 3130: 	$sectionClass='Class </h3>';
 3131:     } elsif ($env{'form.section'} eq 'none') {
 3132: 	$sectionClass=&mt('Students in no Section').'</h3>';
 3133:     } else {
 3134: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
 3135:     }
 3136:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
 3137:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 3138: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
 3139:     #radio buttons/text box for assigning points for a section or class.
 3140:     #handles different parts of a problem
 3141:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3142:     my %weight = ();
 3143:     my $ctsparts = 0;
 3144:     $result.='<table border="0">';
 3145:     my %seen = ();
 3146:     my @part_response_id = &flatten_responseType($responseType);
 3147:     foreach my $part_response_id (@part_response_id) {
 3148:     	my ($partid,$respid) = @{ $part_response_id };
 3149: 	my $part_resp = join('_',@{ $part_response_id });
 3150: 	next if $seen{$partid};
 3151: 	$seen{$partid}++;
 3152: 	my $handgrade=$$handgrade{$part_resp};
 3153: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3154: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3155: 
 3156: 	$result.='<input type="hidden" name="partid_'.
 3157: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3158: 	$result.='<input type="hidden" name="weight_'.
 3159: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3160: 	my $display_part=&get_display_part($partid,$symb);
 3161: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
 3162: 	$result.='<table border="0"><tr>';  
 3163: 	my $ctr = 0;
 3164: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3165: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3166: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3167: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3168: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3169: 	    $ctr++;
 3170: 	}
 3171: 	$result.='</tr></table>';
 3172: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
 3173: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3174: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3175: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3176: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
 3177: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3178: 		$weight{$partid}.')"> '.
 3179: 	    '<option selected="selected"> </option>'.
 3180: 	    '<option>excused</option>'.
 3181: 	    '<option>reset status</option></select></td>'.
 3182:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
 3183: 	$ctsparts++;
 3184:     }
 3185:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
 3186: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3187:     $result.='<input type="button" value="Revert to Default" '.
 3188: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
 3189: 
 3190:     #table listing all the students in a section/class
 3191:     #header of table
 3192:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
 3193:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 3194: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
 3195: 	'<td>'.&nameUserString('header')."</td>\n";
 3196:     my (@parts) = sort(&getpartlist($symb));
 3197:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3198:     my @partids = ();
 3199:     foreach my $part (@parts) {
 3200: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3201: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3202: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3203: 	my ($partid) = &split_part_type($part);
 3204:         push(@partids, $partid);
 3205: 	my $display_part=&get_display_part($partid,$symb);
 3206: 	if ($display =~ /^Partial Credit Factor/) {
 3207: 	    $result.='<td><b>Score Part:</b> '.$display_part.
 3208: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
 3209: 	    next;
 3210: 	} else {
 3211: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
 3212: 	}
 3213: 	$display =~ s|Problem Status|Grade Status<br />|;
 3214: 	$result.='<td><b>'.$display.'</td>'."\n";
 3215:     }
 3216:     $result.='</tr>';
 3217: 
 3218:     my %last_resets = 
 3219: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3220: 
 3221:     #get info for each student
 3222:     #list all the students - with points and grade status
 3223:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3224:     my $ctr = 0;
 3225:     foreach (sort 
 3226: 	     {
 3227: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3228: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3229: 		 }
 3230: 		 return $a cmp $b;
 3231: 	     } (keys(%$fullname))) {
 3232: 	$ctr++;
 3233: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3234: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3235:     }
 3236:     $result.='</table></td></tr></table>';
 3237:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3238:     $result.='<input type="button" value="Save" '.
 3239: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3240:     if (scalar(%$fullname) eq 0) {
 3241: 	my $colspan=3+scalar(@parts);
 3242: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3243:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3244: 	$result='<span class="LC_warning">'.
 3245: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
 3246: 	        $section_display, $stu_status).
 3247: 	    '</span>';
 3248:     }
 3249:     $result.=&show_grading_menu_form($symb);
 3250:     return $result;
 3251: }
 3252: 
 3253: #--- call by previous routine to display each student
 3254: sub viewstudentgrade {
 3255:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3256:     my ($uname,$udom) = split(/:/,$student);
 3257:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3258:     my %aggregates = (); 
 3259:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
 3260: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3261: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3262: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3263: 	'\');" target="_self">'.$fullname.'</a> '.
 3264: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3265:     $student=~s/:/_/; # colon doen't work in javascript for names
 3266:     foreach my $apart (@$parts) {
 3267: 	my ($part,$type) = &split_part_type($apart);
 3268: 	my $score=$record{"resource.$part.$type"};
 3269:         $result.='<td align="center">';
 3270:         my ($aggtries,$totaltries);
 3271:         unless (exists($aggregates{$part})) {
 3272: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3273: 
 3274: 	    $aggtries = $totaltries;
 3275:             if ($$last_resets{$part}) {  
 3276:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3277: 					   $part);
 3278:             }
 3279:             $result.='<input type="hidden" name="'.
 3280:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3281:             $result.='<input type="hidden" name="'.
 3282:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3283:             $aggregates{$part} = 1;
 3284:         }
 3285: 	if ($type eq 'awarded') {
 3286: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3287: 	    $result.='<input type="hidden" name="'.
 3288: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3289: 	    $result.='<input type="text" name="'.
 3290: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3291: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3292: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3293: 	} elsif ($type eq 'solved') {
 3294: 	    my ($status,$foo)=split(/_/,$score,2);
 3295: 	    $status = 'nothing' if ($status eq '');
 3296: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3297: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3298: 	    $result.='&nbsp;<select name="'.
 3299: 		'GD_'.$student.'_'.$part.'_solved" '.
 3300: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3301: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
 3302: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
 3303: 	    $result.='<option>reset status</option>';
 3304: 	    $result.="</select>&nbsp;</td>\n";
 3305: 	} else {
 3306: 	    $result.='<input type="hidden" name="'.
 3307: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3308: 		    "\n";
 3309: 	    $result.='<input type="text" name="'.
 3310: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3311: 		'value="'.$score.'" size="4" /></td>'."\n";
 3312: 	}
 3313:     }
 3314:     $result.='</tr>';
 3315:     return $result;
 3316: }
 3317: 
 3318: #--- change scores for all the students in a section/class
 3319: #    record does not get update if unchanged
 3320: sub editgrades {
 3321:     my ($request) = @_;
 3322: 
 3323:     my $symb=&get_symb($request);
 3324:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3325:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
 3326:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
 3327:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3328: 
 3329:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
 3330:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
 3331: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
 3332: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
 3333: 
 3334:     my %scoreptr = (
 3335: 		    'correct'  =>'correct_by_override',
 3336: 		    'incorrect'=>'incorrect_by_override',
 3337: 		    'excused'  =>'excused',
 3338: 		    'ungraded' =>'ungraded_attempted',
 3339: 		    'nothing'  => '',
 3340: 		    );
 3341:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3342: 
 3343:     my (@partid);
 3344:     my %weight = ();
 3345:     my %columns = ();
 3346:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3347: 
 3348:     my (@parts) = sort(&getpartlist($symb));
 3349:     my $header;
 3350:     while ($ctr < $env{'form.totalparts'}) {
 3351: 	my $partid = $env{'form.partid_'.$ctr};
 3352: 	push @partid,$partid;
 3353: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3354: 	$ctr++;
 3355:     }
 3356:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3357:     foreach my $partid (@partid) {
 3358: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
 3359: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
 3360: 	$columns{$partid}=2;
 3361: 	foreach my $stores (@parts) {
 3362: 	    my ($part,$type) = &split_part_type($stores);
 3363: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3364: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3365: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3366: 	    $display =~ s/\[Part: (\w)+\]//;
 3367: 	    $display =~ s/Number of Attempts/Tries/;
 3368: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
 3369: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
 3370: 	    $columns{$partid}+=2;
 3371: 	}
 3372:     }
 3373:     foreach my $partid (@partid) {
 3374: 	my $display_part=&get_display_part($partid,$symb);
 3375: 	$result .= '<td colspan="'.$columns{$partid}.
 3376: 	    '" align="center"><b>Part:</b> '.$display_part.
 3377: 	    ' (Weight = '.$weight{$partid}.')</td>';
 3378: 
 3379:     }
 3380:     $result .= '</tr><tr bgcolor="#deffff">';
 3381:     $result .= $header;
 3382:     $result .= '</tr>'."\n";
 3383:     my $noupdate;
 3384:     my ($updateCtr,$noupdateCtr) = (1,1);
 3385:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3386: 	my $line;
 3387: 	my $user = $env{'form.ctr'.$i};
 3388: 	my ($uname,$udom)=split(/:/,$user);
 3389: 	my %newrecord;
 3390: 	my $updateflag = 0;
 3391: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3392: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3393: 	if (!&canmodify($usec)) {
 3394: 	    my $numcols=scalar(@partid)*4+2;
 3395: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
 3396: 	    next;
 3397: 	}
 3398:         my %aggregate = ();
 3399:         my $aggregateflag = 0;
 3400: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3401: 	foreach (@partid) {
 3402: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3403: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3404: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3405: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3406: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3407: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3408: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3409: 	    my $score;
 3410: 	    if ($partial eq '') {
 3411: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3412: 	    } elsif ($partial > 0) {
 3413: 		$score = 'correct_by_override';
 3414: 	    } elsif ($partial == 0) {
 3415: 		$score = 'incorrect_by_override';
 3416: 	    }
 3417: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3418: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3419: 
 3420: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3421: 		"$env{'user.name'}:$env{'user.domain'}";
 3422: 	    if ($dropMenu eq 'reset status' &&
 3423: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3424: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3425: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3426: 		$newrecord{'resource.'.$_.'.award'} = '';
 3427: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3428: 		$updateflag = 1;
 3429:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3430:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3431:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3432:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3433:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3434:                     $aggregateflag = 1;
 3435:                 }
 3436: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3437: 		$updateflag = 1;
 3438: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3439: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3440: 		$rec_update++;
 3441: 	    }
 3442: 
 3443: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3444: 		'<td align="center">'.$awarded.
 3445: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3446: 
 3447: 
 3448: 	    my $partid=$_;
 3449: 	    foreach my $stores (@parts) {
 3450: 		my ($part,$type) = &split_part_type($stores);
 3451: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3452: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3453: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3454: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3455: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3456: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3457: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3458: 		    $updateflag=1;
 3459: 		}
 3460: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3461: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3462: 	    }
 3463: 	}
 3464: 	$line.='</tr>'."\n";
 3465: 
 3466: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3467: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3468: 
 3469: 	if ($updateflag) {
 3470: 	    $count++;
 3471: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3472: 				    $udom,$uname);
 3473: 
 3474: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3475: 					      $cnum,$udom,$uname)) {
 3476: 		# need to figure out if should be in queue.
 3477: 		my %record =  
 3478: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3479: 					     $udom,$uname);
 3480: 		my $all_graded = 1;
 3481: 		my $none_graded = 1;
 3482: 		foreach my $part (@parts) {
 3483: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3484: 			$all_graded = 0;
 3485: 		    } else {
 3486: 			$none_graded = 0;
 3487: 		    }
 3488: 		}
 3489: 
 3490: 		if ($all_graded || $none_graded) {
 3491: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3492: 							   $symb,$cdom,$cnum,
 3493: 							   $udom,$uname);
 3494: 		}
 3495: 	    }
 3496: 
 3497: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
 3498: 	    $updateCtr++;
 3499: 	} else {
 3500: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
 3501: 	    $noupdateCtr++;
 3502: 	}
 3503:         if ($aggregateflag) {
 3504:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3505: 				  $cdom,$cnum);
 3506:         }
 3507:     }
 3508:     if ($noupdate) {
 3509: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3510: 	my $numcols=scalar(@partid)*4+2;
 3511: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
 3512:     }
 3513:     $result .= '</table></td></tr></table>'."\n".
 3514: 	&show_grading_menu_form ($symb);
 3515:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
 3516: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
 3517: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
 3518:     return $title.$msg.$result;
 3519: }
 3520: 
 3521: sub split_part_type {
 3522:     my ($partstr) = @_;
 3523:     my ($temp,@allparts)=split(/_/,$partstr);
 3524:     my $type=pop(@allparts);
 3525:     my $part=join('_',@allparts);
 3526:     return ($part,$type);
 3527: }
 3528: 
 3529: #------------- end of section for handling grading by section/class ---------
 3530: #
 3531: #----------------------------------------------------------------------------
 3532: 
 3533: 
 3534: #----------------------------------------------------------------------------
 3535: #
 3536: #-------------------------- Next few routines handles grading by csv upload
 3537: #
 3538: #--- Javascript to handle csv upload
 3539: sub csvupload_javascript_reverse_associate {
 3540:     my $error1=&mt('You need to specify the username or ID');
 3541:     my $error2=&mt('You need to specify at least one grading field');
 3542:   return(<<ENDPICK);
 3543:   function verify(vf) {
 3544:     var foundsomething=0;
 3545:     var founduname=0;
 3546:     var foundID=0;
 3547:     for (i=0;i<=vf.nfields.value;i++) {
 3548:       tw=eval('vf.f'+i+'.selectedIndex');
 3549:       if (i==0 && tw!=0) { foundID=1; }
 3550:       if (i==1 && tw!=0) { founduname=1; }
 3551:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3552:     }
 3553:     if (founduname==0 && foundID==0) {
 3554: 	alert('$error1');
 3555: 	return;
 3556:     }
 3557:     if (foundsomething==0) {
 3558: 	alert('$error2');
 3559: 	return;
 3560:     }
 3561:     vf.submit();
 3562:   }
 3563:   function flip(vf,tf) {
 3564:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3565:     var i;
 3566:     for (i=0;i<=vf.nfields.value;i++) {
 3567:       //can not pick the same destination field for both name and domain
 3568:       if (((i ==0)||(i ==1)) && 
 3569:           ((tf==0)||(tf==1)) && 
 3570:           (i!=tf) &&
 3571:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3572:         eval('vf.f'+i+'.selectedIndex=0;')
 3573:       }
 3574:     }
 3575:   }
 3576: ENDPICK
 3577: }
 3578: 
 3579: sub csvupload_javascript_forward_associate {
 3580:     my $error1=&mt('You need to specify the username or ID');
 3581:     my $error2=&mt('You need to specify at least one grading field');
 3582:   return(<<ENDPICK);
 3583:   function verify(vf) {
 3584:     var foundsomething=0;
 3585:     var founduname=0;
 3586:     var foundID=0;
 3587:     for (i=0;i<=vf.nfields.value;i++) {
 3588:       tw=eval('vf.f'+i+'.selectedIndex');
 3589:       if (tw==1) { foundID=1; }
 3590:       if (tw==2) { founduname=1; }
 3591:       if (tw>3) { foundsomething=1; }
 3592:     }
 3593:     if (founduname==0 && foundID==0) {
 3594: 	alert('$error1');
 3595: 	return;
 3596:     }
 3597:     if (foundsomething==0) {
 3598: 	alert('$error2');
 3599: 	return;
 3600:     }
 3601:     vf.submit();
 3602:   }
 3603:   function flip(vf,tf) {
 3604:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3605:     var i;
 3606:     //can not pick the same destination field twice
 3607:     for (i=0;i<=vf.nfields.value;i++) {
 3608:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3609:         eval('vf.f'+i+'.selectedIndex=0;')
 3610:       }
 3611:     }
 3612:   }
 3613: ENDPICK
 3614: }
 3615: 
 3616: sub csvuploadmap_header {
 3617:     my ($request,$symb,$datatoken,$distotal)= @_;
 3618:     my $javascript;
 3619:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3620: 	$javascript=&csvupload_javascript_reverse_associate();
 3621:     } else {
 3622: 	$javascript=&csvupload_javascript_forward_associate();
 3623:     }
 3624: 
 3625:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3626:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3627:     my $ignore=&mt('Ignore First Line');
 3628:     $symb = &Apache::lonenc::check_encrypt($symb);
 3629:     $request->print(<<ENDPICK);
 3630: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3631: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3632: $result
 3633: <hr />
 3634: <h3>Identify fields</h3>
 3635: Total number of records found in file: $distotal <hr />
 3636: Enter as many fields as you can. The system will inform you and bring you back
 3637: to this page if the data selected is insufficient to run your class.<hr />
 3638: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3639: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3640: <input type="hidden" name="associate"  value="" />
 3641: <input type="hidden" name="phase"      value="three" />
 3642: <input type="hidden" name="datatoken"  value="$datatoken" />
 3643: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3644: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3645: <input type="hidden" name="upfile_associate" 
 3646:                                        value="$env{'form.upfile_associate'}" />
 3647: <input type="hidden" name="symb"       value="$symb" />
 3648: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3649: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3650: <input type="hidden" name="command"    value="csvuploadoptions" />
 3651: <hr />
 3652: <script type="text/javascript" language="Javascript">
 3653: $javascript
 3654: </script>
 3655: ENDPICK
 3656:     return '';
 3657: 
 3658: }
 3659: 
 3660: sub csvupload_fields {
 3661:     my ($symb) = @_;
 3662:     my (@parts) = &getpartlist($symb);
 3663:     my @fields=(['ID','Student ID'],
 3664: 		['username','Student Username'],
 3665: 		['domain','Student Domain']);
 3666:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3667:     foreach my $part (sort(@parts)) {
 3668: 	my @datum;
 3669: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3670: 	my $name=$part;
 3671: 	if  (!$display) { $display = $name; }
 3672: 	@datum=($name,$display);
 3673: 	if ($name=~/^stores_(.*)_awarded/) {
 3674: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3675: 	}
 3676: 	push(@fields,\@datum);
 3677:     }
 3678:     return (@fields);
 3679: }
 3680: 
 3681: sub csvuploadmap_footer {
 3682:     my ($request,$i,$keyfields) =@_;
 3683:     $request->print(<<ENDPICK);
 3684: </table>
 3685: <input type="hidden" name="nfields" value="$i" />
 3686: <input type="hidden" name="keyfields" value="$keyfields" />
 3687: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3688: </form>
 3689: ENDPICK
 3690: }
 3691: 
 3692: sub checkforfile_js {
 3693:     my $result =<<CSVFORMJS;
 3694: <script type="text/javascript" language="javascript">
 3695:     function checkUpload(formname) {
 3696: 	if (formname.upfile.value == "") {
 3697: 	    alert("Please use the browse button to select a file from your local directory.");
 3698: 	    return false;
 3699: 	}
 3700: 	formname.submit();
 3701:     }
 3702:     </script>
 3703: CSVFORMJS
 3704:     return $result;
 3705: }
 3706: 
 3707: sub upcsvScores_form {
 3708:     my ($request) = shift;
 3709:     my ($symb)=&get_symb($request);
 3710:     if (!$symb) {return '';}
 3711:     my $result=&checkforfile_js();
 3712:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3713:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3714:     $result.=$table;
 3715:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3716:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3717:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3718: 	'.</b></td></tr>'."\n";
 3719:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3720:     my $upload=&mt("Upload Scores");
 3721:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3722:     my $ignore=&mt('Ignore First Line');
 3723:     $symb = &Apache::lonenc::check_encrypt($symb);
 3724:     $result.=<<ENDUPFORM;
 3725: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3726: <input type="hidden" name="symb" value="$symb" />
 3727: <input type="hidden" name="command" value="csvuploadmap" />
 3728: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3729: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3730: $upfile_select
 3731: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3732: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3733: </form>
 3734: ENDUPFORM
 3735:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3736:                            &mt("How do I create a CSV file from a spreadsheet"))
 3737:     .'</td></tr></table>'."\n";
 3738:     $result.='</td></tr></table><br /><br />'."\n";
 3739:     $result.=&show_grading_menu_form($symb);
 3740:     return $result;
 3741: }
 3742: 
 3743: 
 3744: sub csvuploadmap {
 3745:     my ($request)= @_;
 3746:     my ($symb)=&get_symb($request);
 3747:     if (!$symb) {return '';}
 3748: 
 3749:     my $datatoken;
 3750:     if (!$env{'form.datatoken'}) {
 3751: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3752:     } else {
 3753: 	$datatoken=$env{'form.datatoken'};
 3754: 	&Apache::loncommon::load_tmp_file($request);
 3755:     }
 3756:     my @records=&Apache::loncommon::upfile_record_sep();
 3757:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3758:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3759:     my ($i,$keyfields);
 3760:     if (@records) {
 3761: 	my @fields=&csvupload_fields($symb);
 3762: 
 3763: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3764: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3765: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3766: 							  \@fields);
 3767: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3768: 	    chop($keyfields);
 3769: 	} else {
 3770: 	    unshift(@fields,['none','']);
 3771: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3772: 							    \@fields);
 3773:             foreach my $rec (@records) {
 3774:                 my %temp = &Apache::loncommon::record_sep($rec);
 3775:                 if (%temp) {
 3776:                     $keyfields=join(',',sort(keys(%temp)));
 3777:                     last;
 3778:                 }
 3779:             }
 3780: 	}
 3781:     }
 3782:     &csvuploadmap_footer($request,$i,$keyfields);
 3783:     $request->print(&show_grading_menu_form($symb));
 3784: 
 3785:     return '';
 3786: }
 3787: 
 3788: sub csvuploadoptions {
 3789:     my ($request)= @_;
 3790:     my ($symb)=&get_symb($request);
 3791:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3792:     my $ignore=&mt('Ignore First Line');
 3793:     $request->print(<<ENDPICK);
 3794: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3795: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3796: <input type="hidden" name="command"    value="csvuploadassign" />
 3797: <!--
 3798: <p>
 3799: <label>
 3800:    <input type="checkbox" name="show_full_results" />
 3801:    Show a table of all changes
 3802: </label>
 3803: </p>
 3804: -->
 3805: <p>
 3806: <label>
 3807:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3808:    Overwrite any existing score
 3809: </label>
 3810: </p>
 3811: ENDPICK
 3812:     my %fields=&get_fields();
 3813:     if (!defined($fields{'domain'})) {
 3814: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3815: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3816:     }
 3817:     foreach my $key (sort(keys(%env))) {
 3818: 	if ($key !~ /^form\.(.*)$/) { next; }
 3819: 	my $cleankey=$1;
 3820: 	if ($cleankey eq 'command') { next; }
 3821: 	$request->print('<input type="hidden" name="'.$cleankey.
 3822: 			'"  value="'.$env{$key}.'" />'."\n");
 3823:     }
 3824:     # FIXME do a check for any duplicated user ids...
 3825:     # FIXME do a check for any invalid user ids?...
 3826:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3827: <hr /></form>'."\n");
 3828:     $request->print(&show_grading_menu_form($symb));
 3829:     return '';
 3830: }
 3831: 
 3832: sub get_fields {
 3833:     my %fields;
 3834:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3835:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3836: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3837: 	    if ($env{'form.f'.$i} ne 'none') {
 3838: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3839: 	    }
 3840: 	} else {
 3841: 	    if ($env{'form.f'.$i} ne 'none') {
 3842: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3843: 	    }
 3844: 	}
 3845:     }
 3846:     return %fields;
 3847: }
 3848: 
 3849: sub csvuploadassign {
 3850:     my ($request)= @_;
 3851:     my ($symb)=&get_symb($request);
 3852:     if (!$symb) {return '';}
 3853:     my $error_msg = '';
 3854:     &Apache::loncommon::load_tmp_file($request);
 3855:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3856:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3857:     my %fields=&get_fields();
 3858:     $request->print('<h3>Assigning Grades</h3>');
 3859:     my $courseid=$env{'request.course.id'};
 3860:     my ($classlist) = &getclasslist('all',0);
 3861:     my @notallowed;
 3862:     my @skipped;
 3863:     my $countdone=0;
 3864:     foreach my $grade (@gradedata) {
 3865: 	my %entries=&Apache::loncommon::record_sep($grade);
 3866: 	my $domain;
 3867: 	if ($entries{$fields{'domain'}}) {
 3868: 	    $domain=$entries{$fields{'domain'}};
 3869: 	} else {
 3870: 	    $domain=$env{'form.default_domain'};
 3871: 	}
 3872: 	$domain=~s/\s//g;
 3873: 	my $username=$entries{$fields{'username'}};
 3874: 	$username=~s/\s//g;
 3875: 	if (!$username) {
 3876: 	    my $id=$entries{$fields{'ID'}};
 3877: 	    $id=~s/\s//g;
 3878: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3879: 	    $username=$ids{$id};
 3880: 	}
 3881: 	if (!exists($$classlist{"$username:$domain"})) {
 3882: 	    my $id=$entries{$fields{'ID'}};
 3883: 	    $id=~s/\s//g;
 3884: 	    if ($id) {
 3885: 		push(@skipped,"$id:$domain");
 3886: 	    } else {
 3887: 		push(@skipped,"$username:$domain");
 3888: 	    }
 3889: 	    next;
 3890: 	}
 3891: 	my $usec=$classlist->{"$username:$domain"}[5];
 3892: 	if (!&canmodify($usec)) {
 3893: 	    push(@notallowed,"$username:$domain");
 3894: 	    next;
 3895: 	}
 3896: 	my %points;
 3897: 	my %grades;
 3898: 	foreach my $dest (keys(%fields)) {
 3899: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 3900: 		$dest eq 'domain') { next; }
 3901: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 3902: 	    if ($dest=~/stores_(.*)_points/) {
 3903: 		my $part=$1;
 3904: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 3905: 					      $symb,$domain,$username);
 3906:                 if ($wgt) {
 3907:                     $entries{$fields{$dest}}=~s/\s//g;
 3908:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 3909:                     my $award='correct_by_override';
 3910:                     $grades{"resource.$part.awarded"}=$pcr;
 3911:                     $grades{"resource.$part.solved"}=$award;
 3912:                     $points{$part}=1;
 3913:                 } else {
 3914:                     $error_msg = "<br />" .
 3915:                         &mt("Some point values were assigned"
 3916:                             ." for problems with a weight "
 3917:                             ."of zero. These values were "
 3918:                             ."ignored.");
 3919:                 }
 3920: 	    } else {
 3921: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 3922: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 3923: 		my $store_key=$dest;
 3924: 		$store_key=~s/^stores/resource/;
 3925: 		$store_key=~s/_/\./g;
 3926: 		$grades{$store_key}=$entries{$fields{$dest}};
 3927: 	    }
 3928: 	}
 3929: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
 3930: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 3931: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
 3932: 					   $env{'request.course.id'},
 3933: 					   $domain,$username);
 3934: 	if ($result eq 'ok') {
 3935: 	    $request->print('.');
 3936: 	} else {
 3937: 	    $request->print("<p>
 3938:                               <span class=\"LC_error\">
 3939:                                  Failed to save student $username:$domain.
 3940:                                  Message when trying to save was ($result)
 3941:                               </span>
 3942:                              </p>" );
 3943: 	}
 3944: 	$request->rflush();
 3945: 	$countdone++;
 3946:     }
 3947:     $request->print("<br />Saved $countdone students\n");
 3948:     if (@skipped) {
 3949: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
 3950: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 3951:     }
 3952:     if (@notallowed) {
 3953: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
 3954: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 3955:     }
 3956:     $request->print("<br />\n");
 3957:     $request->print(&show_grading_menu_form($symb));
 3958:     return $error_msg;
 3959: }
 3960: #------------- end of section for handling csv file upload ---------
 3961: #
 3962: #-------------------------------------------------------------------
 3963: #
 3964: #-------------- Next few routines handle grading by page/sequence
 3965: #
 3966: #--- Select a page/sequence and a student to grade
 3967: sub pickStudentPage {
 3968:     my ($request) = shift;
 3969: 
 3970:     $request->print(<<LISTJAVASCRIPT);
 3971: <script type="text/javascript" language="javascript">
 3972: 
 3973: function checkPickOne(formname) {
 3974:     if (radioSelection(formname.student) == null) {
 3975: 	alert("Please select the student you wish to grade.");
 3976: 	return;
 3977:     }
 3978:     ptr = pullDownSelection(formname.selectpage);
 3979:     formname.page.value = formname["page"+ptr].value;
 3980:     formname.title.value = formname["title"+ptr].value;
 3981:     formname.submit();
 3982: }
 3983: 
 3984: </script>
 3985: LISTJAVASCRIPT
 3986:     &commonJSfunctions($request);
 3987:     my ($symb) = &get_symb($request);
 3988:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 3989:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 3990:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 3991: 
 3992:     my $result='<h3><span class="LC_info">&nbsp;'.
 3993: 	'Manual Grading by Page or Sequence</span></h3>';
 3994: 
 3995:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 3996:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
 3997:     my ($titles,$symbx) = &getSymbMap();
 3998:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 3999: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4000: #    my $type=($curpage =~ /\.(page|sequence)/);
 4001:     my $ctr=0;
 4002:     foreach (@$titles) {
 4003: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4004: 	$result.='<option value="'.$ctr.'" '.
 4005: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4006: 	    '>'.$showtitle.'</option>'."\n";
 4007: 	$ctr++;
 4008:     }
 4009:     $result.= '</select>'."<br />\n";
 4010:     $ctr=0;
 4011:     foreach (@$titles) {
 4012: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4013: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4014: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4015: 	$ctr++;
 4016:     }
 4017:     $result.='<input type="hidden" name="page" />'."\n".
 4018: 	'<input type="hidden" name="title" />'."\n";
 4019: 
 4020:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
 4021: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
 4022: 
 4023:     $result.='&nbsp;<b>Submission Details: </b>'.
 4024: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
 4025: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
 4026: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
 4027:     
 4028:     $result.=&build_section_inputs();
 4029:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4030:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4031: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4032: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4033: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4034: 
 4035:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
 4036: 	'<input type="text" name="CODE" value="" /><br />'."\n";
 4037: 
 4038:     $result.='&nbsp;<input type="button" '.
 4039: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
 4040: 
 4041:     $request->print($result);
 4042: 
 4043:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
 4044: 	'<table border="0"><tr><td bgcolor="#777777">'.
 4045: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4046: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 4047: 	'<td>'.&nameUserString('header').'</td>'.
 4048: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 4049: 	'<td>'.&nameUserString('header').'</td></tr>';
 4050:  
 4051:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4052:     my $ptr = 1;
 4053:     foreach my $student (sort 
 4054: 			 {
 4055: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4056: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4057: 			     }
 4058: 			     return $a cmp $b;
 4059: 			 } (keys(%$fullname))) {
 4060: 	my ($uname,$udom) = split(/:/,$student);
 4061: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
 4062: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4063: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4064: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4065: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
 4066: 	$ptr++;
 4067:     }
 4068:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
 4069:     $studentTable.='</table></td></tr></table>'."\n";
 4070:     $studentTable.='<input type="button" '.
 4071: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
 4072: 
 4073:     $studentTable.=&show_grading_menu_form($symb);
 4074:     $request->print($studentTable);
 4075: 
 4076:     return '';
 4077: }
 4078: 
 4079: sub getSymbMap {
 4080:     my $navmap = Apache::lonnavmaps::navmap->new();
 4081: 
 4082:     my %symbx = ();
 4083:     my @titles = ();
 4084:     my $minder = 0;
 4085: 
 4086:     # Gather every sequence that has problems.
 4087:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4088: 					       1,0,1);
 4089:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4090: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4091: 	    my $title = $minder.'.'.
 4092: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4093: 	    push(@titles, $title); # minder in case two titles are identical
 4094: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4095: 	    $minder++;
 4096: 	}
 4097:     }
 4098:     return \@titles,\%symbx;
 4099: }
 4100: 
 4101: #
 4102: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4103: sub displayPage {
 4104:     my ($request) = shift;
 4105: 
 4106:     my ($symb) = &get_symb($request);
 4107:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4108:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4109:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4110:     my $pageTitle = $env{'form.page'};
 4111:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4112:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4113:     my $usec=$classlist->{$env{'form.student'}}[5];
 4114: 
 4115:     #need to make sure we have the correct data for later EXT calls, 
 4116:     #thus invalidate the cache
 4117:     &Apache::lonnet::devalidatecourseresdata(
 4118:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4119:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4120:     &Apache::lonnet::clear_EXT_cache_status();
 4121: 
 4122:     if (!&canview($usec)) {
 4123: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
 4124: 	$request->print(&show_grading_menu_form($symb));
 4125: 	return;
 4126:     }
 4127:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4128:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
 4129: 	'</h3>'."\n";
 4130:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4131: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
 4132:     } else {
 4133: 	delete($env{'form.CODE'});
 4134:     }
 4135:     &sub_page_js($request);
 4136:     $request->print($result);
 4137: 
 4138:     my $navmap = Apache::lonnavmaps::navmap->new();
 4139:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4140:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4141:     if (!$map) {
 4142: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
 4143: 	$request->print(&show_grading_menu_form($symb));
 4144: 	return; 
 4145:     }
 4146:     my $iterator = $navmap->getIterator($map->map_start(),
 4147: 					$map->map_finish());
 4148: 
 4149:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4150: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4151: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4152: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4153: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4154: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4155: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4156: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4157: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4158: 
 4159:     if (defined($env{'form.CODE'})) {
 4160: 	$studentTable.=
 4161: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4162:     }
 4163:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4164: 	'" src="'.$request->dir_config('lonIconsURL').
 4165: 	'/check.gif" height="16" border="0" />';
 4166: 
 4167:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
 4168: 	' symbol.'."\n".
 4169: 	'<table border="0"><tr><td bgcolor="#777777">'.
 4170: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4171: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 4172: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
 4173: 
 4174:     &Apache::lonxml::clear_problem_counter();
 4175:     my ($depth,$question,$prob) = (1,1,1);
 4176:     $iterator->next(); # skip the first BEGIN_MAP
 4177:     my $curRes = $iterator->next(); # for "current resource"
 4178:     while ($depth > 0) {
 4179:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4180:         if($curRes == $iterator->END_MAP) { $depth--; }
 4181: 
 4182:         if (ref($curRes) && $curRes->is_problem()) {
 4183: 	    my $parts = $curRes->parts();
 4184:             my $title = $curRes->compTitle();
 4185: 	    my $symbx = $curRes->symb();
 4186: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 4187: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 4188: 	    $studentTable.='<td valign="top">';
 4189: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4190: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4191: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4192: 					     undef,'both',\%form);
 4193: 	    } else {
 4194: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4195: 		$companswer =~ s|<form(.*?)>||g;
 4196: 		$companswer =~ s|</form>||g;
 4197: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4198: #		    $companswer =~ s/$1/ /ms;
 4199: #		    $request->print('match='.$1."<br />\n");
 4200: #		}
 4201: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4202: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
 4203: 	    }
 4204: 
 4205: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4206: 
 4207: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4208: 		if ($record{'version'} eq '') {
 4209: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
 4210: 		} else {
 4211: 		    my %responseType = ();
 4212: 		    foreach my $partid (@{$parts}) {
 4213: 			my @responseIds =$curRes->responseIds($partid);
 4214: 			my @responseType =$curRes->responseType($partid);
 4215: 			my %responseIds;
 4216: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4217: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4218: 			}
 4219: 			$responseType{$partid} = \%responseIds;
 4220: 		    }
 4221: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4222: 
 4223: 		}
 4224: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4225: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4226: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4227: 									$env{'request.course.id'},
 4228: 									'','.submission');
 4229:  
 4230: 	    }
 4231: 	    if (&canmodify($usec)) {
 4232: 		foreach my $partid (@{$parts}) {
 4233: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4234: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4235: 		    $question++;
 4236: 		}
 4237: 		$prob++;
 4238: 	    }
 4239: 	    $studentTable.='</td></tr>';
 4240: 
 4241: 	}
 4242:         $curRes = $iterator->next();
 4243:     }
 4244: 
 4245:     $studentTable.='</table></td></tr></table>'."\n".
 4246: 	'<input type="button" value="Save" '.
 4247: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4248: 	'</form>'."\n";
 4249:     $studentTable.=&show_grading_menu_form($symb);
 4250:     $request->print($studentTable);
 4251: 
 4252:     return '';
 4253: }
 4254: 
 4255: sub displaySubByDates {
 4256:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4257:     my $isCODE=0;
 4258:     my $isTask = ($symb =~/\.task$/);
 4259:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4260:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
 4261: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
 4262: 	'<td><b>Date/Time</b></td>'.
 4263: 	($isCODE?'<td><b>CODE</b></td>':'').
 4264: 	'<td><b>Submission</b></td>'.
 4265: 	'<td><b>Status&nbsp;</b></td></tr>';
 4266:     my ($version);
 4267:     my %mark;
 4268:     my %orders;
 4269:     $mark{'correct_by_student'} = $checkIcon;
 4270:     if (!exists($$record{'1:timestamp'})) {
 4271: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
 4272:     }
 4273: 
 4274:     my $interaction;
 4275:     for ($version=1;$version<=$$record{'version'};$version++) {
 4276: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
 4277: 	if (exists($$record{$version.':resource.0.version'})) {
 4278: 	    $interaction = $$record{$version.':resource.0.version'};
 4279: 	}
 4280: 
 4281: 	my $where = ($isTask ? "$version:resource.$interaction"
 4282: 		             : "$version:resource");
 4283: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
 4284: 	if ($isCODE) {
 4285: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4286: 	}
 4287: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4288: 	my @displaySub = ();
 4289: 	foreach my $partid (@{$parts}) {
 4290: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4291: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4292: 	    
 4293: 
 4294: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4295: 	    my $display_part=&get_display_part($partid,$symb);
 4296: 	    foreach my $matchKey (@matchKey) {
 4297: 		if (exists($$record{$version.':'.$matchKey}) &&
 4298: 		    $$record{$version.':'.$matchKey} ne '') {
 4299: 
 4300: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4301: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4302: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
 4303: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
 4304: 			$responseId.')</span>&nbsp;<b>';
 4305: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4306: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
 4307: 		    } else {
 4308: 			$displaySub[0].='Trial&nbsp;'.
 4309: 			    $$record{"$where.$partid.tries"};
 4310: 		    }
 4311: 		    my $responseType=($isTask ? 'Task'
 4312:                                               : $responseType->{$partid}->{$responseId});
 4313: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4314: 		    if (!exists($orders{$partid}->{$responseId})) {
 4315: 			$orders{$partid}->{$responseId}=
 4316: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
 4317: 		    }
 4318: 		    $displaySub[0].='</b>&nbsp; '.
 4319: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4320: 		}
 4321: 	    }
 4322: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4323: 		$displaySub[1].='Checked in by '.
 4324: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
 4325: 		    $$record{"$where.$partid.checkedin.slot"}.
 4326: 		    '<br />';
 4327: 	    }
 4328: 	    if (exists $$record{"$where.$partid.award"}) {
 4329: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
 4330: 		    lc($$record{"$where.$partid.award"}).' '.
 4331: 		    $mark{$$record{"$where.$partid.solved"}}.
 4332: 		    '<br />';
 4333: 	    }
 4334: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4335: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4336: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4337: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4338: 		$displaySub[2].=
 4339: 		    $$record{"$version:resource.$partid.regrader"}.
 4340: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4341: 	    }
 4342: 	}
 4343: 	# needed because old essay regrader has not parts info
 4344: 	if (exists $$record{"$version:resource.regrader"}) {
 4345: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4346: 	}
 4347: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4348: 	if ($displaySub[2]) {
 4349: 	    $studentTable.='Manually graded by '.$displaySub[2];
 4350: 	}
 4351: 	$studentTable.='&nbsp;</td></tr>';
 4352:     
 4353:     }
 4354:     $studentTable.='</table></td></tr></table>';
 4355:     return $studentTable;
 4356: }
 4357: 
 4358: sub updateGradeByPage {
 4359:     my ($request) = shift;
 4360: 
 4361:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4362:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4363:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4364:     my $pageTitle = $env{'form.page'};
 4365:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4366:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4367:     my $usec=$classlist->{$env{'form.student'}}[5];
 4368:     if (!&canmodify($usec)) {
 4369: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
 4370: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4371: 	return;
 4372:     }
 4373:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4374:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4375: 	'</h3>'."\n";
 4376: 
 4377:     $request->print($result);
 4378: 
 4379:     my $navmap = Apache::lonnavmaps::navmap->new();
 4380:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4381:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4382:     if (!$map) {
 4383: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
 4384: 	my ($symb)=&get_symb($request);
 4385: 	$request->print(&show_grading_menu_form($symb));
 4386: 	return; 
 4387:     }
 4388:     my $iterator = $navmap->getIterator($map->map_start(),
 4389: 					$map->map_finish());
 4390: 
 4391:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
 4392: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4393: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 4394: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
 4395: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
 4396: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
 4397: 
 4398:     $iterator->next(); # skip the first BEGIN_MAP
 4399:     my $curRes = $iterator->next(); # for "current resource"
 4400:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4401:     while ($depth > 0) {
 4402:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4403:         if($curRes == $iterator->END_MAP) { $depth--; }
 4404: 
 4405:         if (ref($curRes) && $curRes->is_problem()) {
 4406: 	    my $parts = $curRes->parts();
 4407:             my $title = $curRes->compTitle();
 4408: 	    my $symbx = $curRes->symb();
 4409: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 4410: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 4411: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4412: 
 4413: 	    my %newrecord=();
 4414: 	    my @displayPts=();
 4415:             my %aggregate = ();
 4416:             my $aggregateflag = 0;
 4417: 	    foreach my $partid (@{$parts}) {
 4418: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4419: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4420: 
 4421: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4422: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4423: 		my $partial = $newpts/$wgt;
 4424: 		my $score;
 4425: 		if ($partial > 0) {
 4426: 		    $score = 'correct_by_override';
 4427: 		} elsif ($newpts ne '') { #empty is taken as 0
 4428: 		    $score = 'incorrect_by_override';
 4429: 		}
 4430: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4431: 		if ($dropMenu eq 'excused') {
 4432: 		    $partial = '';
 4433: 		    $score = 'excused';
 4434: 		} elsif ($dropMenu eq 'reset status'
 4435: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4436: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4437: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4438: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4439: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4440: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4441: 		    $changeflag++;
 4442: 		    $newpts = '';
 4443:                     
 4444:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4445:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4446:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4447:                     if ($aggtries > 0) {
 4448:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4449:                         $aggregateflag = 1;
 4450:                     }
 4451: 		}
 4452: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4453: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4454: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4455: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4456: 		    '&nbsp;<br />';
 4457: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4458: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4459: 		    '&nbsp;<br />';
 4460: 		$question++;
 4461: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4462: 
 4463: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4464: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4465: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4466: 		    if (scalar(keys(%newrecord)) > 0);
 4467: 
 4468: 		$changeflag++;
 4469: 	    }
 4470: 	    if (scalar(keys(%newrecord)) > 0) {
 4471: 		my %record = 
 4472: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4473: 					     $udom,$uname);
 4474: 
 4475: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4476: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4477: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4478: 		    $newrecord{'resource.CODE'} = '';
 4479: 		}
 4480: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4481: 					$udom,$uname);
 4482: 		%record = &Apache::lonnet::restore($symbx,
 4483: 						   $env{'request.course.id'},
 4484: 						   $udom,$uname);
 4485: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4486: 					     $cdom,$cnum,$udom,$uname);
 4487: 	    }
 4488: 	    
 4489:             if ($aggregateflag) {
 4490:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4491:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4492:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4493:             }
 4494: 
 4495: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4496: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4497: 		'</tr>';
 4498: 
 4499: 	    $prob++;
 4500: 	}
 4501:         $curRes = $iterator->next();
 4502:     }
 4503: 
 4504:     $studentTable.='</td></tr></table></td></tr></table>';
 4505:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4506:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
 4507: 		  'The scores were changed for '.
 4508: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
 4509:     $request->print($grademsg.$studentTable);
 4510: 
 4511:     return '';
 4512: }
 4513: 
 4514: #-------- end of section for handling grading by page/sequence ---------
 4515: #
 4516: #-------------------------------------------------------------------
 4517: 
 4518: #--------------------Scantron Grading-----------------------------------
 4519: #
 4520: #------ start of section for handling grading by page/sequence ---------
 4521: 
 4522: =pod
 4523: 
 4524: =head1 Bubble sheet grading routines
 4525: 
 4526:   For this documentation:
 4527: 
 4528:    'scanline' refers to the full line of characters
 4529:    from the file that we are parsing that represents one entire sheet
 4530: 
 4531:    'bubble line' refers to the data
 4532:    representing the line of bubbles that are on the physical bubble sheet
 4533: 
 4534: 
 4535: The overall process is that a scanned in bubble sheet data is uploaded
 4536: into a course. When a user wants to grade, they select a
 4537: sequence/folder of resources, a file of bubble sheet info, and pick
 4538: one of the predefined configurations for what each scanline looks
 4539: like.
 4540: 
 4541: Next each scanline is checked for any errors of either 'missing
 4542: bubbles' (it's an error because it may have been mis-scanned
 4543: because too light bubbling), 'double bubble' (each bubble line should
 4544: have no more that one letter picked), invalid or duplicated CODE,
 4545: invalid student ID
 4546: 
 4547: If the CODE option is used that determines the randomization of the
 4548: homework problems, either way the student ID is looked up into a
 4549: username:domain.
 4550: 
 4551: During the validation phase the instructor can choose to skip scanlines. 
 4552: 
 4553: After the validation phase, there are now 3 bubble sheet files
 4554: 
 4555:   scantron_original_filename (unmodified original file)
 4556:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4557:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4558: 
 4559: Also there is a separate hash nohist_scantrondata that contains extra
 4560: correction information that isn't representable in the bubble sheet
 4561: file (see &scantron_getfile() for more information)
 4562: 
 4563: After all scanlines are either valid, marked as valid or skipped, then
 4564: foreach line foreach problem in the picked sequence, an ssi request is
 4565: made that simulates a user submitting their selected letter(s) against
 4566: the homework problem.
 4567: 
 4568: =over 4
 4569: 
 4570: 
 4571: 
 4572: =item defaultFormData
 4573: 
 4574:   Returns html hidden inputs used to hold context/default values.
 4575: 
 4576:  Arguments:
 4577:   $symb - $symb of the current resource 
 4578: 
 4579: =cut
 4580: 
 4581: sub defaultFormData {
 4582:     my ($symb)=@_;
 4583:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4584:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4585:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4586: }
 4587: 
 4588: 
 4589: =pod 
 4590: 
 4591: =item getSequenceDropDown
 4592: 
 4593:    Return html dropdown of possible sequences to grade
 4594:  
 4595:  Arguments:
 4596:    $symb - $symb of the current resource 
 4597: 
 4598: =cut
 4599: 
 4600: sub getSequenceDropDown {
 4601:     my ($symb)=@_;
 4602:     my $result='<select name="selectpage">'."\n";
 4603:     my ($titles,$symbx) = &getSymbMap();
 4604:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4605:     my $ctr=0;
 4606:     foreach (@$titles) {
 4607: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4608: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4609: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4610: 	    '>'.$showtitle.'</option>'."\n";
 4611: 	$ctr++;
 4612:     }
 4613:     $result.= '</select>';
 4614:     return $result;
 4615: }
 4616: 
 4617: 
 4618: =pod 
 4619: 
 4620: =item scantron_filenames
 4621: 
 4622:    Returns a list of the scantron files in the current course 
 4623: 
 4624: =cut
 4625: 
 4626: sub scantron_filenames {
 4627:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4628:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4629:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4630: 				    &propath($cdom,$cname));
 4631:     my @possiblenames;
 4632:     foreach my $filename (sort(@files)) {
 4633: 	($filename)=split(/&/,$filename);
 4634: 	if ($filename!~/^scantron_orig_/) { next ; }
 4635: 	$filename=~s/^scantron_orig_//;
 4636: 	push(@possiblenames,$filename);
 4637:     }
 4638:     return @possiblenames;
 4639: }
 4640: 
 4641: =pod 
 4642: 
 4643: =item scantron_uploads
 4644: 
 4645:    Returns  html drop-down list of scantron files in current course.
 4646: 
 4647:  Arguments:
 4648:    $file2grade - filename to set as selected in the dropdown
 4649: 
 4650: =cut
 4651: 
 4652: sub scantron_uploads {
 4653:     my ($file2grade) = @_;
 4654:     my $result=	'<select name="scantron_selectfile">';
 4655:     $result.="<option></option>";
 4656:     foreach my $filename (sort(&scantron_filenames())) {
 4657: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4658:     }
 4659:     $result.="</select>";
 4660:     return $result;
 4661: }
 4662: 
 4663: =pod 
 4664: 
 4665: =item scantron_scantab
 4666: 
 4667:   Returns html drop down of the scantron formats in the scantronformat.tab
 4668:   file.
 4669: 
 4670: =cut
 4671: 
 4672: sub scantron_scantab {
 4673:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4674:     my $result='<select name="scantron_format">'."\n";
 4675:     $result.='<option></option>'."\n";
 4676:     foreach my $line (<$fh>) {
 4677: 	my ($name,$descrip)=split(/:/,$line);
 4678: 	if ($name =~ /^\#/) { next; }
 4679: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4680:     }
 4681:     $result.='</select>'."\n";
 4682: 
 4683:     return $result;
 4684: }
 4685: 
 4686: =pod 
 4687: 
 4688: =item scantron_CODElist
 4689: 
 4690:   Returns html drop down of the saved CODE lists from current course,
 4691:   generated from earlier printings.
 4692: 
 4693: =cut
 4694: 
 4695: sub scantron_CODElist {
 4696:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4697:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4698:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4699:     my $namechoice='<option></option>';
 4700:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4701: 	if ($name =~ /^error: 2 /) { next; }
 4702: 	if ($name =~ /^type\0/) { next; }
 4703: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4704:     }
 4705:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4706:     return $namechoice;
 4707: }
 4708: 
 4709: =pod 
 4710: 
 4711: =item scantron_CODEunique
 4712: 
 4713:   Returns the html for "Each CODE to be used once" radio.
 4714: 
 4715: =cut
 4716: 
 4717: sub scantron_CODEunique {
 4718:     my $result='<span style="white-space: nowrap;">
 4719:                  <label><input type="radio" name="scantron_CODEunique"
 4720:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4721:                 </span>
 4722:                 <span style="white-space: nowrap;">
 4723:                  <label><input type="radio" name="scantron_CODEunique"
 4724:                         value="no" />'.&mt('No').' </label>
 4725:                 </span>';
 4726:     return $result;
 4727: }
 4728: 
 4729: =pod 
 4730: 
 4731: =item scantron_selectphase
 4732: 
 4733:   Generates the initial screen to start the bubble sheet process.
 4734:   Allows for - starting a grading run.
 4735:              - downloading existing scan data (original, corrected
 4736:                                                 or skipped info)
 4737: 
 4738:              - uploading new scan data
 4739: 
 4740:  Arguments:
 4741:   $r          - The Apache request object
 4742:   $file2grade - name of the file that contain the scanned data to score
 4743: 
 4744: =cut
 4745: 
 4746: sub scantron_selectphase {
 4747:     my ($r,$file2grade) = @_;
 4748:     my ($symb)=&get_symb($r);
 4749:     if (!$symb) {return '';}
 4750:     my $sequence_selector=&getSequenceDropDown($symb);
 4751:     my $default_form_data=&defaultFormData($symb);
 4752:     my $grading_menu_button=&show_grading_menu_form($symb);
 4753:     my $file_selector=&scantron_uploads($file2grade);
 4754:     my $format_selector=&scantron_scantab();
 4755:     my $CODE_selector=&scantron_CODElist();
 4756:     my $CODE_unique=&scantron_CODEunique();
 4757:     my $result;
 4758: 
 4759:     # Chunk of form to prompt for a file to grade and how:
 4760: 
 4761:     $result.= <<SCANTRONFORM;
 4762:     <table width="100%" border="0">
 4763:     <tr>
 4764:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 4765:       <td bgcolor="#777777">
 4766:        <input type="hidden" name="command" value="scantron_warning" />
 4767:         $default_form_data
 4768:         <table width="100%" border="0">
 4769:           <tr bgcolor="#e6ffff">
 4770:             <td colspan="2">
 4771:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
 4772:             </td>
 4773:           </tr>
 4774:           <tr bgcolor="#ffffe6">
 4775:             <td> Sequence to grade: </td><td> $sequence_selector </td>
 4776:           </tr>
 4777:           <tr bgcolor="#ffffe6">
 4778:             <td> Filename of scoring office file: </td><td> $file_selector </td>
 4779:           </tr>
 4780:           <tr bgcolor="#ffffe6">
 4781:             <td> Format of data file: </td><td> $format_selector </td>
 4782:           </tr>
 4783:           <tr bgcolor="#ffffe6">
 4784:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
 4785:           </tr>
 4786:           <tr bgcolor="#ffffe6">
 4787:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
 4788:           </tr>
 4789:           <tr bgcolor="#ffffe6">
 4790: 	    <td> Options: </td>
 4791:             <td>
 4792: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
 4793:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
 4794:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
 4795: 	    </td>
 4796:           </tr>
 4797:           <tr bgcolor="#ffffe6">
 4798:             <td colspan="2">
 4799:               <input type="submit" value="Grading: Validate Scantron Records" />
 4800:             </td>
 4801:           </tr>
 4802:         </table>
 4803:        </td>
 4804:      </form>
 4805:     </tr>
 4806: SCANTRONFORM
 4807:    
 4808:     $r->print($result);
 4809: 
 4810:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 4811:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 4812: 
 4813: 	# Chunk of form to prompt for a scantron file upload.
 4814: 
 4815:         $r->print(<<SCANTRONFORM);
 4816:     <tr>
 4817:       <td bgcolor="#777777">
 4818:         <table width="100%" border="0">
 4819:           <tr bgcolor="#e6ffff">
 4820:             <td>
 4821:               &nbsp;<b>Specify a Scantron data file to upload.</b>
 4822:             </td>
 4823:           </tr>
 4824:           <tr bgcolor="#ffffe6">
 4825:             <td>
 4826: SCANTRONFORM
 4827:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 4828:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4829:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 4830:     $r->print(<<UPLOAD);
 4831:               <script type="text/javascript" language="javascript">
 4832:     function checkUpload(formname) {
 4833: 	if (formname.upfile.value == "") {
 4834: 	    alert("Please use the browse button to select a file from your local directory.");
 4835: 	    return false;
 4836: 	}
 4837: 	formname.submit();
 4838:     }
 4839:               </script>
 4840: 
 4841:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 4842:                 $default_form_data
 4843:                 <input name='courseid' type='hidden' value='$cnum' />
 4844:                 <input name='domainid' type='hidden' value='$cdom' />
 4845:                 <input name='command' value='scantronupload_save' type='hidden' />
 4846:                 File to upload:<input type="file" name="upfile" size="50" />
 4847:                 <br />
 4848:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 4849:               </form>
 4850: UPLOAD
 4851: 
 4852:         $r->print(<<SCANTRONFORM);
 4853:             </td>
 4854:           </tr>
 4855:         </table>
 4856:       </td>
 4857:     </tr>
 4858: SCANTRONFORM
 4859:     }
 4860: 
 4861:     # Chunk of the form that prompts to view a scoring office file,
 4862:     # corrected file, skipped records in a file.
 4863: 
 4864:     $r->print(<<SCANTRONFORM);
 4865:     <tr>
 4866:       <form action='/adm/grades' name='scantron_download'>
 4867:         <td bgcolor="#777777">
 4868: 	  $default_form_data
 4869:           <input type="hidden" name="command" value="scantron_download" />
 4870:           <table width="100%" border="0">
 4871:             <tr bgcolor="#e6ffff">
 4872:               <td colspan="2">
 4873:                 &nbsp;<b>Download a scoring office file</b>
 4874:               </td>
 4875:             </tr>
 4876:             <tr bgcolor="#ffffe6">
 4877:               <td> Filename of scoring office file: </td><td> $file_selector </td>
 4878:             </tr>
 4879:             <tr bgcolor="#ffffe6">
 4880:               <td colspan="2">
 4881:                 <input type="submit" value="Download: Show List of Associated Files" />
 4882:               </td>
 4883:             </tr>
 4884:           </table>
 4885:         </td>
 4886:       </form>
 4887:     </tr>
 4888: SCANTRONFORM
 4889: 
 4890:     $r->print(<<SCANTRONFORM);
 4891:   </table>
 4892: $grading_menu_button
 4893: SCANTRONFORM
 4894: 
 4895:     return
 4896: }
 4897: 
 4898: =pod
 4899: 
 4900: =item get_scantron_config
 4901: 
 4902:    Parse and return the scantron configuration line selected as a
 4903:    hash of configuration file fields.
 4904: 
 4905:  Arguments:
 4906:     which - the name of the configuration to parse from the file.
 4907: 
 4908: 
 4909:  Returns:
 4910:             If the named configuration is not in the file, an empty
 4911:             hash is returned.
 4912:     a hash with the fields
 4913:       name         - internal name for the this configuration setup
 4914:       description  - text to display to operator that describes this config
 4915:       CODElocation - if 0 or the string 'none'
 4916:                           - no CODE exists for this config
 4917:                      if -1 || the string 'letter'
 4918:                           - a CODE exists for this config and is
 4919:                             a string of letters
 4920:                      Unsupported value (but planned for future support)
 4921:                           if a positive integer
 4922:                                - The CODE exists as the first n items from
 4923:                                  the question section of the form
 4924:                           if the string 'number'
 4925:                                - The CODE exists for this config and is
 4926:                                  a string of numbers
 4927:       CODEstart   - (only matter if a CODE exists) column in the line where
 4928:                      the CODE starts
 4929:       CODElength  - length of the CODE
 4930:       IDstart     - column where the student ID number starts
 4931:       IDlength    - length of the student ID info
 4932:       Qstart      - column where the information from the bubbled
 4933:                     'questions' start
 4934:       Qlength     - number of columns comprising a single bubble line from
 4935:                     the sheet. (usually either 1 or 10)
 4936:       Qon         - either a single character representing the character used
 4937:                     to signal a bubble was chosen in the positional setup, or
 4938:                     the string 'letter' if the letter of the chosen bubble is
 4939:                     in the final, or 'number' if a number representing the
 4940:                     chosen bubble is in the file (1->A 0->J)
 4941:       Qoff        - the character used to represent that a bubble was
 4942:                     left blank
 4943:       PaperID     - if the scanning process generates a unique number for each
 4944:                     sheet scanned the column that this ID number starts in
 4945:       PaperIDlength - number of columns that comprise the unique ID number
 4946:                       for the sheet of paper
 4947:       FirstName   - column that the first name starts in
 4948:       FirstNameLength - number of columns that the first name spans
 4949:  
 4950:       LastName    - column that the last name starts in
 4951:       LastNameLength - number of columns that the last name spans
 4952: 
 4953: =cut
 4954: 
 4955: sub get_scantron_config {
 4956:     my ($which) = @_;
 4957:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4958:     my %config;
 4959:     #FIXME probably should move to XML it has already gotten a bit much now
 4960:     foreach my $line (<$fh>) {
 4961: 	my ($name,$descrip)=split(/:/,$line);
 4962: 	if ($name ne $which ) { next; }
 4963: 	chomp($line);
 4964: 	my @config=split(/:/,$line);
 4965: 	$config{'name'}=$config[0];
 4966: 	$config{'description'}=$config[1];
 4967: 	$config{'CODElocation'}=$config[2];
 4968: 	$config{'CODEstart'}=$config[3];
 4969: 	$config{'CODElength'}=$config[4];
 4970: 	$config{'IDstart'}=$config[5];
 4971: 	$config{'IDlength'}=$config[6];
 4972: 	$config{'Qstart'}=$config[7];
 4973: 	$config{'Qlength'}=$config[8];
 4974: 	$config{'Qoff'}=$config[9];
 4975: 	$config{'Qon'}=$config[10];
 4976: 	$config{'PaperID'}=$config[11];
 4977: 	$config{'PaperIDlength'}=$config[12];
 4978: 	$config{'FirstName'}=$config[13];
 4979: 	$config{'FirstNamelength'}=$config[14];
 4980: 	$config{'LastName'}=$config[15];
 4981: 	$config{'LastNamelength'}=$config[16];
 4982: 	last;
 4983:     }
 4984:     return %config;
 4985: }
 4986: 
 4987: =pod 
 4988: 
 4989: =item username_to_idmap
 4990: 
 4991:     creates a hash keyed by student id with values of the corresponding
 4992:     student username:domain.
 4993: 
 4994:   Arguments:
 4995: 
 4996:     $classlist - reference to the class list hash. This is a hash
 4997:                  keyed by student name:domain  whose elements are references
 4998:                  to arrays containing various chunks of information
 4999:                  about the student. (See loncoursedata for more info).
 5000: 
 5001:   Returns
 5002:     %idmap - the constructed hash
 5003: 
 5004: =cut
 5005: 
 5006: sub username_to_idmap {
 5007:     my ($classlist)= @_;
 5008:     my %idmap;
 5009:     foreach my $student (keys(%$classlist)) {
 5010: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5011: 	    $student;
 5012:     }
 5013:     return %idmap;
 5014: }
 5015: 
 5016: =pod
 5017: 
 5018: =item scantron_fixup_scanline
 5019: 
 5020:    Process a requested correction to a scanline.
 5021: 
 5022:   Arguments:
 5023:     $scantron_config   - hash from &get_scantron_config()
 5024:     $scan_data         - hash of correction information 
 5025:                           (see &scantron_getfile())
 5026:     $line              - existing scanline
 5027:     $whichline         - line number of the passed in scanline
 5028:     $field             - type of change to process 
 5029:                          (either 
 5030:                           'ID'     -> correct the student ID number
 5031:                           'CODE'   -> correct the CODE
 5032:                           'answer' -> fixup the submitted answers)
 5033:     
 5034:    $args               - hash of additional info,
 5035:                           - 'ID' 
 5036:                                'newid' -> studentID to use in replacement
 5037:                                           of existing one
 5038:                           - 'CODE' 
 5039:                                'CODE_ignore_dup' - set to true if duplicates
 5040:                                                    should be ignored.
 5041: 	                       'CODE' - is new code or 'use_unfound'
 5042:                                         if the existing unfound code should
 5043:                                         be used as is
 5044:                           - 'answer'
 5045:                                'response' - new answer or 'none' if blank
 5046:                                'question' - the bubble line to change
 5047: 
 5048:   Returns:
 5049:     $line - the modified scanline
 5050: 
 5051:   Side effects: 
 5052:     $scan_data - may be updated
 5053: 
 5054: =cut
 5055: 
 5056: 
 5057: sub scantron_fixup_scanline {
 5058:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5059: 
 5060:     if ($field eq 'ID') {
 5061: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5062: 	    return ($line,1,'New value too large');
 5063: 	}
 5064: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5065: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5066: 				     $args->{'newid'});
 5067: 	}
 5068: 	substr($line,$$scantron_config{'IDstart'}-1,
 5069: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5070: 	if ($args->{'newid'}=~/^\s*$/) {
 5071: 	    &scan_data($scan_data,"$whichline.user",
 5072: 		       $args->{'username'}.':'.$args->{'domain'});
 5073: 	}
 5074:     } elsif ($field eq 'CODE') {
 5075: 	if ($args->{'CODE_ignore_dup'}) {
 5076: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5077: 	}
 5078: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5079: 	if ($args->{'CODE'} ne 'use_unfound') {
 5080: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5081: 		return ($line,1,'New CODE value too large');
 5082: 	    }
 5083: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5084: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5085: 	    }
 5086: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5087: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5088: 	}
 5089:     } elsif ($field eq 'answer') {
 5090: 	my $length=$scantron_config->{'Qlength'};
 5091: 	my $off=$scantron_config->{'Qoff'};
 5092: 	my $on=$scantron_config->{'Qon'};
 5093: 	my $answer=${off}x$length;
 5094: 	if ($args->{'response'} eq 'none') {
 5095: 	    &scan_data($scan_data,
 5096: 		       "$whichline.no_bubble.".$args->{'question'},'1');
 5097: 	} else {
 5098: 	    if ($on eq 'letter') {
 5099: 		my @alphabet=('A'..'Z');
 5100: 		$answer=$alphabet[$args->{'response'}];
 5101: 	    } elsif ($on eq 'number') {
 5102: 		$answer=$args->{'response'}+1;
 5103: 		if ($answer == 10) { $answer = '0'; }
 5104: 	    } else {
 5105: 		substr($answer,$args->{'response'},1)=$on;
 5106: 	    }
 5107: 	    &scan_data($scan_data,
 5108: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
 5109: 	}
 5110: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5111: 	substr($line,$where-1,$length)=$answer;
 5112:     }
 5113:     return $line;
 5114: }
 5115: 
 5116: =pod
 5117: 
 5118: =item scan_data
 5119: 
 5120:     Edit or look up  an item in the scan_data hash.
 5121: 
 5122:   Arguments:
 5123:     $scan_data  - The hash (see scantron_getfile)
 5124:     $key        - shorthand of the key to edit (actual key is
 5125:                   scantronfilename_key).
 5126:     $data        - New value of the hash entry.
 5127:     $delete      - If true, the entry is removed from the hash.
 5128: 
 5129:   Returns:
 5130:     The new value of the hash table field (undefined if deleted).
 5131: 
 5132: =cut
 5133: 
 5134: 
 5135: sub scan_data {
 5136:     my ($scan_data,$key,$value,$delete)=@_;
 5137:     my $filename=$env{'form.scantron_selectfile'};
 5138:     if (defined($value)) {
 5139: 	$scan_data->{$filename.'_'.$key} = $value;
 5140:     }
 5141:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5142:     return $scan_data->{$filename.'_'.$key};
 5143: }
 5144: 
 5145: =pod 
 5146: 
 5147: =item scantron_parse_scanline
 5148: 
 5149:   Decodes a scanline from the selected scantron file
 5150: 
 5151:  Arguments:
 5152:     line             - The text of the scantron file line to process
 5153:     whichline        - Line number
 5154:     scantron_config  - Hash describing the format of the scantron lines.
 5155:     scan_data        - Hash of extra information about the scanline
 5156:                        (see scantron_getfile for more information)
 5157:     just_header      - True if should not process question answers but only
 5158:                        the stuff to the left of the answers.
 5159:  Returns:
 5160:    Hash containing the result of parsing the scanline
 5161: 
 5162:    Keys are all proceeded by the string 'scantron.'
 5163: 
 5164:        CODE    - the CODE in use for this scanline
 5165:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5166:                  by the operator
 5167:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5168:                             CODEs were selected, but the usage has been
 5169:                             forced by the operator
 5170:        ID  - student ID
 5171:        PaperID - if used, the ID number printed on the sheet when the 
 5172:                  paper was scanned
 5173:        FirstName - first name from the sheet
 5174:        LastName  - last name from the sheet
 5175: 
 5176:      if just_header was not true these key may also exist
 5177: 
 5178:        missingerror - a list of bubble ranges that are considered to be answers
 5179:                       to a single question that don't have any bubbles filled in.
 5180:                       Of the form questionnumber:firstbubblenumber:count.
 5181:        doubleerror  - a list of bubble ranges that are considered to be answers
 5182:                       to a single question that have more than one bubble filled in.
 5183:                       Of the form questionnumber::firstbubblenumber:count
 5184:    
 5185:                 In the above, count is the number of bubble responses in the
 5186:                 input line needed to represent the possible answers to the question.
 5187:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5188:                 per line would have count = 2.
 5189: 
 5190:        maxquest     - the number of the last bubble line that was parsed
 5191: 
 5192:        (<number> starts at 1)
 5193:        <number>.answer - zero or more letters representing the selected
 5194:                          letters from the scanline for the bubble line 
 5195:                          <number>.
 5196:                          if blank there was either no bubble or there where
 5197:                          multiple bubbles, (consult the keys missingerror and
 5198:                          doubleerror if this is an error condition)
 5199: 
 5200: =cut
 5201: 
 5202: sub scantron_parse_scanline {
 5203:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5204:     my %record;
 5205:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5206:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5207:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5208: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5209: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5210: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5211: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5212: 	    $record{'scantron.CODE'}=substr($data,
 5213: 					    $$scantron_config{'CODEstart'}-1,
 5214: 					    $$scantron_config{'CODElength'});
 5215: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5216: 		$record{'scantron.useCODE'}=1;
 5217: 	    }
 5218: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5219: 		$record{'scantron.CODE_ignore_dup'}=1;
 5220: 	    }
 5221: 	} else {
 5222: 	    #FIXME interpret first N questions
 5223: 	}
 5224:     }
 5225:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5226: 				  $$scantron_config{'IDlength'});
 5227:     $record{'scantron.PaperID'}=
 5228: 	substr($data,$$scantron_config{'PaperID'}-1,
 5229: 	       $$scantron_config{'PaperIDlength'});
 5230:     $record{'scantron.FirstName'}=
 5231: 	substr($data,$$scantron_config{'FirstName'}-1,
 5232: 	       $$scantron_config{'FirstNamelength'});
 5233:     $record{'scantron.LastName'}=
 5234: 	substr($data,$$scantron_config{'LastName'}-1,
 5235: 	       $$scantron_config{'LastNamelength'});
 5236:     if ($just_header) { return \%record; }
 5237: 
 5238:     my @alphabet=('A'..'Z');
 5239:     my $questnum=0;
 5240:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5241: 
 5242:     while ($questions) {
 5243: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5244: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
 5245: 
 5246: 
 5247: 
 5248: 	$questnum++;
 5249: 	my $currentquest = substr($questions,0,$answer_length);
 5250: 	$questions       = substr($questions,0,$answer_length)='';
 5251: 	if (length($currentquest) < $answer_length) { next; }
 5252: 
 5253: 	# Qon letter implies for each slot in currentquest we have:
 5254: 	#    ? or * for doubles a letter in A-Z for a bubble and
 5255:         #    about anything else (esp. a value of Qoff for missing
 5256: 	#    bubbles.
 5257: 
 5258: 
 5259: 	if ($$scantron_config{'Qon'} eq 'letter') {
 5260: 
 5261: 	    if ($currentquest =~ /\?/
 5262: 		|| $currentquest =~ /\*/
 5263: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
 5264: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5265: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
 5266: 		    $record{"scantron.$ansnum.answer"}='';
 5267: 		    $ansnum++;
 5268: 		}
 5269: 
 5270: 	    } elsif (!defined($currentquest)
 5271: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
 5272: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
 5273: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5274: 		    $record{"scantron.$ansnum.answer"}='';
 5275: 		    $ansnum++;
 5276: 
 5277: 		}
 5278: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5279: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5280: 		    $ansnum += $answers_needed;
 5281: 		}
 5282: 
 5283: 	    } else {
 5284: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5285: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
 5286: 		    $ansnum++;
 5287: 		}
 5288: 	    }
 5289: 
 5290: 	# Qon 'number' implies each slot gives a digit that indexes the
 5291: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
 5292:         #    and *? for double bubbles on a line.
 5293: 	#    these answers are also stored as letters.
 5294: 
 5295: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
 5296: 	    if ($currentquest =~ /\?/
 5297: 		|| $currentquest =~ /\*/
 5298: 		|| (&occurence_count($currentquest, '\d') > 1)) {
 5299: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5300: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5301: 		    $record{"scantron.$ansnum.answer"}='';
 5302: 		    $ansnum++;
 5303: 		}
 5304: 
 5305: 	    } elsif (!defined($currentquest)
 5306: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
 5307: 		     || (&occurence_count($currentquest, '\d') == 0)) {
 5308: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5309: 		    $record{"scantron.$ansnum.answer"}='';
 5310: 		    $ansnum++;
 5311: 
 5312: 		}
 5313: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5314: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5315: 		    $ansnum += $answers_needed;
 5316: 		}
 5317: 
 5318: 	    } else {
 5319: 		$currentquest = &digits_to_letters($currentquest);
 5320: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
 5321: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
 5322: 		    $ansnum++;
 5323: 		}
 5324: 	    }
 5325: 	} else {
 5326: 
 5327: 	    # Otherwise there's a positional notation;
 5328: 	    # each bubble line requires Qlength items, and there are filled in
 5329: 	    # bubbles for each case where there 'Qon' characters.
 5330: 	    #
 5331: 
 5332: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
 5333: 
 5334: 	    # If the split only  giveas us one element.. the full length of the
 5335: 	    # answser string, no bubbles are filled in:
 5336: 
 5337: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5338: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5339: 		    $record{"scantron.$ansnum.answer"}='';
 5340: 		    $ansnum++;
 5341: 
 5342: 		}
 5343: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5344: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5345: 		}
 5346: 	    } elsif (scalar(@array) lt 2) {
 5347: 
 5348: 		my $location      = [length($array[0])];
 5349: 		my $line_num      = $location / $$scantron_config{'Qlength'};
 5350: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
 5351: 
 5352: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5353: 		    if ($ans eq $line_num) {
 5354: 			$record{"scantron.$ansnum.answer"} = $bubble;
 5355: 		    } else {
 5356: 			$record{"scantron.$ansnum.answer"} = ' ';
 5357: 		    }
 5358: 		    $ansnum++;
 5359: 		}
 5360: 	    }
 5361: 	    #  If there's more than one instance of a bubble character
 5362: 	    #  That's a double bubble; with positional notation we can
 5363: 	    #  record all the bubbles filled in as well as the 
 5364: 	    #  fact this response consists of multiple bubbles.
 5365: 	    #
 5366: 	    else {
 5367: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5368: 
 5369: 		my $first_answer = $ansnum;
 5370: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
 5371: 		    $record{"scantron.$ansnum.answer"} = '';
 5372: 		    $ans++;
 5373: 		}
 5374: 
 5375: 		my @ans=@array;
 5376: 		my $i=length($ans[0]);shift(@ans);
 5377: 		while ($#ans) {
 5378: 		    $i+=length($ans[0])+1;
 5379: 		    my $line   = $i/$$scantron_config{'Qlength'} + $first_answer;
 5380: 		    my $bubble = $i%$$scantron_config{'Qlength'};
 5381: 
 5382: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
 5383: 		    shift(@ans);
 5384: 		}
 5385: 	    }
 5386: 	}
 5387:     }
 5388:     $record{'scantron.maxquest'}=$questnum;
 5389:     return \%record;
 5390: }
 5391: 
 5392: =pod
 5393: 
 5394: =item scantron_add_delay
 5395: 
 5396:    Adds an error message that occurred during the grading phase to a
 5397:    queue of messages to be shown after grading pass is complete
 5398: 
 5399:  Arguments:
 5400:    $delayqueue  - arrary ref of hash ref of error messages
 5401:    $scanline    - the scanline that caused the error
 5402:    $errormesage - the error message
 5403:    $errorcode   - a numeric code for the error
 5404: 
 5405:  Side Effects:
 5406:    updates the $delayqueue to have a new hash ref of the error
 5407: 
 5408: =cut
 5409: 
 5410: sub scantron_add_delay {
 5411:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5412:     push(@$delayqueue,
 5413: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5414: 	  'ecode' => $errorcode }
 5415: 	 );
 5416: }
 5417: 
 5418: =pod
 5419: 
 5420: =item scantron_find_student
 5421: 
 5422:    Finds the username for the current scanline
 5423: 
 5424:   Arguments:
 5425:    $scantron_record - hash result from scantron_parse_scanline
 5426:    $scan_data       - hash of correction information 
 5427:                       (see &scantron_getfile() form more information)
 5428:    $idmap           - hash from &username_to_idmap()
 5429:    $line            - number of current scanline
 5430:  
 5431:   Returns:
 5432:    Either 'username:domain' or undef if unknown
 5433: 
 5434: =cut
 5435: 
 5436: sub scantron_find_student {
 5437:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5438:     my $scanID=$$scantron_record{'scantron.ID'};
 5439:     if ($scanID =~ /^\s*$/) {
 5440:  	return &scan_data($scan_data,"$line.user");
 5441:     }
 5442:     foreach my $id (keys(%$idmap)) {
 5443:  	if (lc($id) eq lc($scanID)) {
 5444:  	    return $$idmap{$id};
 5445:  	}
 5446:     }
 5447:     return undef;
 5448: }
 5449: 
 5450: =pod
 5451: 
 5452: =item scantron_filter
 5453: 
 5454:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5455:    hidden resources was selected
 5456: 
 5457: =cut
 5458: 
 5459: sub scantron_filter {
 5460:     my ($curres)=@_;
 5461: 
 5462:     if (ref($curres) && $curres->is_problem()) {
 5463: 	# if the user has asked to not have either hidden
 5464: 	# or 'randomout' controlled resources to be graded
 5465: 	# don't include them
 5466: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5467: 	    && $curres->randomout) {
 5468: 	    return 0;
 5469: 	}
 5470: 	return 1;
 5471:     }
 5472:     return 0;
 5473: }
 5474: 
 5475: =pod
 5476: 
 5477: =item scantron_process_corrections
 5478: 
 5479:    Gets correction information out of submitted form data and corrects
 5480:    the scanline
 5481: 
 5482: =cut
 5483: 
 5484: sub scantron_process_corrections {
 5485:     my ($r) = @_;
 5486:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5487:     my ($scanlines,$scan_data)=&scantron_getfile();
 5488:     my $classlist=&Apache::loncoursedata::get_classlist();
 5489:     my $which=$env{'form.scantron_line'};
 5490:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5491:     my ($skip,$err,$errmsg);
 5492:     if ($env{'form.scantron_skip_record'}) {
 5493: 	$skip=1;
 5494:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5495: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5496: 	    $env{'form.scantron_domain'};
 5497: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5498: 	($line,$err,$errmsg)=
 5499: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5500: 				     'ID',{'newid'=>$newid,
 5501: 				    'username'=>$env{'form.scantron_username'},
 5502: 				    'domain'=>$env{'form.scantron_domain'}});
 5503:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5504: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5505: 	my $newCODE;
 5506: 	my %args;
 5507: 	if      ($resolution eq 'use_unfound') {
 5508: 	    $newCODE='use_unfound';
 5509: 	} elsif ($resolution eq 'use_found') {
 5510: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5511: 	} elsif ($resolution eq 'use_typed') {
 5512: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5513: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5514: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5515: 	}
 5516: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5517: 	    $args{'CODE_ignore_dup'}=1;
 5518: 	}
 5519: 	$args{'CODE'}=$newCODE;
 5520: 	($line,$err,$errmsg)=
 5521: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5522: 				     'CODE',\%args);
 5523:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5524: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5525: 	    ($line,$err,$errmsg)=
 5526: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5527: 					 $which,'answer',
 5528: 					 { 'question'=>$question,
 5529: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
 5530: 	    if ($err) { last; }
 5531: 	}
 5532:     }
 5533:     if ($err) {
 5534: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5535:     } else {
 5536: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5537: 	&scantron_putfile($scanlines,$scan_data);
 5538:     }
 5539: }
 5540: 
 5541: =pod
 5542: 
 5543: =item reset_skipping_status
 5544: 
 5545:    Forgets the current set of remember skipped scanlines (and thus
 5546:    reverts back to considering all lines in the
 5547:    scantron_skipped_<filename> file)
 5548: 
 5549: =cut
 5550: 
 5551: sub reset_skipping_status {
 5552:     my ($scanlines,$scan_data)=&scantron_getfile();
 5553:     &scan_data($scan_data,'remember_skipping',undef,1);
 5554:     &scantron_putfile(undef,$scan_data);
 5555: }
 5556: 
 5557: =pod
 5558: 
 5559: =item start_skipping
 5560: 
 5561:    Marks a scanline to be skipped. 
 5562: 
 5563: =cut
 5564: 
 5565: sub start_skipping {
 5566:     my ($scan_data,$i)=@_;
 5567:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5568:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5569: 	$remembered{$i}=2;
 5570:     } else {
 5571: 	$remembered{$i}=1;
 5572:     }
 5573:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5574: }
 5575: 
 5576: =pod
 5577: 
 5578: =item should_be_skipped
 5579: 
 5580:    Checks whether a scanline should be skipped.
 5581: 
 5582: =cut
 5583: 
 5584: sub should_be_skipped {
 5585:     my ($scanlines,$scan_data,$i)=@_;
 5586:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5587: 	# not redoing old skips
 5588: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5589: 	return 0;
 5590:     }
 5591:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5592: 
 5593:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5594: 	return 0;
 5595:     }
 5596:     return 1;
 5597: }
 5598: 
 5599: =pod
 5600: 
 5601: =item remember_current_skipped
 5602: 
 5603:    Discovers what scanlines are in the scantron_skipped_<filename>
 5604:    file and remembers them into scan_data for later use.
 5605: 
 5606: =cut
 5607: 
 5608: sub remember_current_skipped {
 5609:     my ($scanlines,$scan_data)=&scantron_getfile();
 5610:     my %to_remember;
 5611:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 5612: 	if ($scanlines->{'skipped'}[$i]) {
 5613: 	    $to_remember{$i}=1;
 5614: 	}
 5615:     }
 5616: 
 5617:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 5618:     &scantron_putfile(undef,$scan_data);
 5619: }
 5620: 
 5621: =pod
 5622: 
 5623: =item check_for_error
 5624: 
 5625:     Checks if there was an error when attempting to remove a specific
 5626:     scantron_.. bubble sheet data file. Prints out an error if
 5627:     something went wrong.
 5628: 
 5629: =cut
 5630: 
 5631: sub check_for_error {
 5632:     my ($r,$result)=@_;
 5633:     if ($result ne 'ok' && $result ne 'not_found' ) {
 5634: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
 5635:     }
 5636: }
 5637: 
 5638: =pod
 5639: 
 5640: =item scantron_warning_screen
 5641: 
 5642:    Interstitial screen to make sure the operator has selected the
 5643:    correct options before we start the validation phase.
 5644: 
 5645: =cut
 5646: 
 5647: sub scantron_warning_screen {
 5648:     my ($button_text)=@_;
 5649:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 5650:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5651:     my $CODElist;
 5652:     if ($scantron_config{'CODElocation'} &&
 5653: 	$scantron_config{'CODEstart'} &&
 5654: 	$scantron_config{'CODElength'}) {
 5655: 	$CODElist=$env{'form.scantron_CODElist'};
 5656: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 5657: 	$CODElist=
 5658: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
 5659: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 5660:     }
 5661:     return (<<STUFF);
 5662: <p>
 5663: <span class="LC_warning">Please double check the information
 5664:                  below before clicking on '$button_text'</span>
 5665: </p>
 5666: <table>
 5667: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
 5668: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
 5669: $CODElist
 5670: </table>
 5671: <br />
 5672: <p> If this information is correct, please click on '$button_text'.</p>
 5673: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
 5674: 
 5675: <br />
 5676: STUFF
 5677: }
 5678: 
 5679: =pod
 5680: 
 5681: =item scantron_do_warning
 5682: 
 5683:    Check if the operator has picked something for all required
 5684:    fields. Error out if something is missing.
 5685: 
 5686: =cut
 5687: 
 5688: sub scantron_do_warning {
 5689:     my ($r)=@_;
 5690:     my ($symb)=&get_symb($r);
 5691:     if (!$symb) {return '';}
 5692:     my $default_form_data=&defaultFormData($symb);
 5693:     $r->print(&scantron_form_start().$default_form_data);
 5694:     if ( $env{'form.selectpage'} eq '' ||
 5695: 	 $env{'form.scantron_selectfile'} eq '' ||
 5696: 	 $env{'form.scantron_format'} eq '' ) {
 5697: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
 5698: 	if ( $env{'form.selectpage'} eq '') {
 5699: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
 5700: 	} 
 5701: 	if ( $env{'form.scantron_selectfile'} eq '') {
 5702: 	    $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
 5703: 	} 
 5704: 	if ( $env{'form.scantron_format'} eq '') {
 5705: 	    $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
 5706: 	} 
 5707:     } else {
 5708: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 5709: 	$r->print(<<STUFF);
 5710: $warning
 5711: <input type="submit" name="submit" value="Grading: Validate Records" />
 5712: <input type="hidden" name="command" value="scantron_validate" />
 5713: STUFF
 5714:     }
 5715:     $r->print("</form><br />".&show_grading_menu_form($symb));
 5716:     return '';
 5717: }
 5718: 
 5719: =pod
 5720: 
 5721: =item scantron_form_start
 5722: 
 5723:     html hidden input for remembering all selected grading options
 5724: 
 5725: =cut
 5726: 
 5727: sub scantron_form_start {
 5728:     my ($max_bubble)=@_;
 5729:     my $result= <<SCANTRONFORM;
 5730: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 5731:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 5732:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 5733:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 5734:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 5735:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 5736:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 5737:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 5738:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 5739:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 5740: SCANTRONFORM
 5741: 
 5742:   my $line = 0;
 5743:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 5744: 	&Apache::lonnet::logthis("Saving chunk for $line");
 5745:        my $chunk =
 5746: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 5747:        $chunk .=
 5748: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 5749:        $result .= $chunk;
 5750:        $line++;
 5751:    }
 5752:     return $result;
 5753: }
 5754: 
 5755: =pod
 5756: 
 5757: =item scantron_validate_file
 5758: 
 5759:     Dispatch routine for doing validation of a bubble sheet data file.
 5760: 
 5761:     Also processes any necessary information resets that need to
 5762:     occur before validation begins (ignore previous corrections,
 5763:     restarting the skipped records processing)
 5764: 
 5765: =cut
 5766: 
 5767: sub scantron_validate_file {
 5768:     my ($r) = @_;
 5769:     my ($symb)=&get_symb($r);
 5770:     if (!$symb) {return '';}
 5771:     my $default_form_data=&defaultFormData($symb);
 5772:     
 5773:     # do the detection of only doing skipped records first befroe we delete
 5774:     # them when doing the corrections reset
 5775:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 5776: 	&reset_skipping_status();
 5777:     }
 5778:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 5779: 	&remember_current_skipped();
 5780: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 5781:     }
 5782: 
 5783:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 5784: 	&check_for_error($r,&scantron_remove_file('corrected'));
 5785: 	&check_for_error($r,&scantron_remove_file('skipped'));
 5786: 	&check_for_error($r,&scantron_remove_scan_data());
 5787: 	$env{'form.scantron_options_ignore'}='done';
 5788:     }
 5789: 
 5790:     if ($env{'form.scantron_corrections'}) {
 5791: 	&scantron_process_corrections($r);
 5792:     }
 5793:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
 5794:     #get the student pick code ready
 5795:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 5796:     my $max_bubble=&scantron_get_maxbubble();
 5797:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 5798:     $r->print($result);
 5799:     
 5800:     my @validate_phases=( 'sequence',
 5801: 			  'ID',
 5802: 			  'CODE',
 5803: 			  'doublebubble',
 5804: 			  'missingbubbles');
 5805:     if (!$env{'form.validatepass'}) {
 5806: 	$env{'form.validatepass'} = 0;
 5807:     }
 5808:     my $currentphase=$env{'form.validatepass'};
 5809: 
 5810:     &Apache::lonnet::logthis("Phase: $currentphase");
 5811: 
 5812:     my $stop=0;
 5813:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 5814: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
 5815: 	$r->rflush();
 5816: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 5817: 	{
 5818: 	    no strict 'refs';
 5819: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 5820: 	}
 5821:     }
 5822:     if (!$stop) {
 5823: 	my $warning=&scantron_warning_screen('Start Grading');
 5824: 	$r->print(<<STUFF);
 5825: Validation process complete.<br />
 5826: $warning
 5827: <input type="submit" name="submit" value="Start Grading" />
 5828: <input type="hidden" name="command" value="scantron_process" />
 5829: STUFF
 5830: 
 5831:     } else {
 5832: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 5833: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 5834:     }
 5835:     if ($stop) {
 5836: 	if ($validate_phases[$currentphase] eq 'sequence') {
 5837: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
 5838: 	    $r->print(' this error <br />');
 5839: 
 5840: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
 5841: 	} else {
 5842: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
 5843: 	    $r->print(' using corrected info <br />');
 5844: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
 5845: 	    $r->print(" this scanline saving it for later.");
 5846: 	}
 5847:     }
 5848:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 5849:     return '';
 5850: }
 5851: 
 5852: 
 5853: =pod
 5854: 
 5855: =item scantron_remove_file
 5856: 
 5857:    Removes the requested bubble sheet data file, makes sure that
 5858:    scantron_original_<filename> is never removed
 5859: 
 5860: 
 5861: =cut
 5862: 
 5863: sub scantron_remove_file {
 5864:     my ($which)=@_;
 5865:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5866:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5867:     my $file='scantron_';
 5868:     if ($which eq 'corrected' || $which eq 'skipped') {
 5869: 	$file.=$which.'_';
 5870:     } else {
 5871: 	return 'refused';
 5872:     }
 5873:     $file.=$env{'form.scantron_selectfile'};
 5874:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 5875: }
 5876: 
 5877: 
 5878: =pod
 5879: 
 5880: =item scantron_remove_scan_data
 5881: 
 5882:    Removes all scan_data correction for the requested bubble sheet
 5883:    data file.  (In the case that both the are doing skipped records we need
 5884:    to remember the old skipped lines for the time being so that element
 5885:    persists for a while.)
 5886: 
 5887: =cut
 5888: 
 5889: sub scantron_remove_scan_data {
 5890:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5891:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5892:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 5893:     my @todelete;
 5894:     my $filename=$env{'form.scantron_selectfile'};
 5895:     foreach my $key (@keys) {
 5896: 	if ($key=~/^\Q$filename\E_/) {
 5897: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 5898: 		$key=~/remember_skipping/) {
 5899: 		next;
 5900: 	    }
 5901: 	    push(@todelete,$key);
 5902: 	}
 5903:     }
 5904:     my $result;
 5905:     if (@todelete) {
 5906: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
 5907:     }
 5908:     return $result;
 5909: }
 5910: 
 5911: 
 5912: =pod
 5913: 
 5914: =item scantron_getfile
 5915: 
 5916:     Fetches the requested bubble sheet data file (all 3 versions), and
 5917:     the scan_data hash
 5918:   
 5919:   Arguments:
 5920:     None
 5921: 
 5922:   Returns:
 5923:     2 hash references
 5924: 
 5925:      - first one has 
 5926:          orig      -
 5927:          corrected -
 5928:          skipped   -  each of which points to an array ref of the specified
 5929:                       file broken up into individual lines
 5930:          count     - number of scanlines
 5931:  
 5932:      - second is the scan_data hash possible keys are
 5933:        ($number refers to scanline numbered $number and thus the key affects
 5934:         only that scanline
 5935:         $bubline refers to the specific bubble line element and the aspects
 5936:         refers to that specific bubble line element)
 5937: 
 5938:        $number.user - username:domain to use
 5939:        $number.CODE_ignore_dup 
 5940:                     - ignore the duplicate CODE error 
 5941:        $number.useCODE
 5942:                     - use the CODE in the scanline as is
 5943:        $number.no_bubble.$bubline
 5944:                     - it is valid that there is no bubbled in bubble
 5945:                       at $number $bubline
 5946:        remember_skipping
 5947:                     - a frozen hash containing keys of $number and values
 5948:                       of either 
 5949:                         1 - we are on a 'do skipped records pass' and plan
 5950:                             on processing this line
 5951:                         2 - we are on a 'do skipped records pass' and this
 5952:                             scanline has been marked to skip yet again
 5953: 
 5954: =cut
 5955: 
 5956: sub scantron_getfile {
 5957:     #FIXME really would prefer a scantron directory
 5958:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5959:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5960:     my $lines;
 5961:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5962: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 5963:     my %scanlines;
 5964:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 5965:     my $temp=$scanlines{'orig'};
 5966:     $scanlines{'count'}=$#$temp;
 5967: 
 5968:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5969: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 5970:     if ($lines eq '-1') {
 5971: 	$scanlines{'corrected'}=[];
 5972:     } else {
 5973: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 5974:     }
 5975:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5976: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 5977:     if ($lines eq '-1') {
 5978: 	$scanlines{'skipped'}=[];
 5979:     } else {
 5980: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 5981:     }
 5982:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 5983:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 5984:     my %scan_data = @tmp;
 5985:     return (\%scanlines,\%scan_data);
 5986: }
 5987: 
 5988: =pod
 5989: 
 5990: =item lonnet_putfile
 5991: 
 5992:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 5993: 
 5994:  Arguments:
 5995:    $contents - data to store
 5996:    $filename - filename to store $contents into
 5997: 
 5998:  Returns:
 5999:    result value from &Apache::lonnet::finishuserfileupload
 6000: 
 6001: =cut
 6002: 
 6003: sub lonnet_putfile {
 6004:     my ($contents,$filename)=@_;
 6005:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6006:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6007:     $env{'form.sillywaytopassafilearound'}=$contents;
 6008:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6009: 
 6010: }
 6011: 
 6012: =pod
 6013: 
 6014: =item scantron_putfile
 6015: 
 6016:     Stores the current version of the bubble sheet data files, and the
 6017:     scan_data hash. (Does not modify the original version only the
 6018:     corrected and skipped versions.
 6019: 
 6020:  Arguments:
 6021:     $scanlines - hash ref that looks like the first return value from
 6022:                  &scantron_getfile()
 6023:     $scan_data - hash ref that looks like the second return value from
 6024:                  &scantron_getfile()
 6025: 
 6026: =cut
 6027: 
 6028: sub scantron_putfile {
 6029:     my ($scanlines,$scan_data) = @_;
 6030:     #FIXME really would prefer a scantron directory
 6031:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6032:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6033:     if ($scanlines) {
 6034: 	my $prefix='scantron_';
 6035: # no need to update orig, shouldn't change
 6036: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6037: #		    $env{'form.scantron_selectfile'});
 6038: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6039: 			$prefix.'corrected_'.
 6040: 			$env{'form.scantron_selectfile'});
 6041: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6042: 			$prefix.'skipped_'.
 6043: 			$env{'form.scantron_selectfile'});
 6044:     }
 6045:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6046: }
 6047: 
 6048: =pod
 6049: 
 6050: =item scantron_get_line
 6051: 
 6052:    Returns the correct version of the scanline
 6053: 
 6054:  Arguments:
 6055:     $scanlines - hash ref that looks like the first return value from
 6056:                  &scantron_getfile()
 6057:     $scan_data - hash ref that looks like the second return value from
 6058:                  &scantron_getfile()
 6059:     $i         - number of the requested line (starts at 0)
 6060: 
 6061:  Returns:
 6062:    A scanline, (either the original or the corrected one if it
 6063:    exists), or undef if the requested scanline should be
 6064:    skipped. (Either because it's an skipped scanline, or it's an
 6065:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6066:    pass.
 6067: 
 6068: =cut
 6069: 
 6070: sub scantron_get_line {
 6071:     my ($scanlines,$scan_data,$i)=@_;
 6072:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6073:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6074:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6075:     return $scanlines->{'orig'}[$i]; 
 6076: }
 6077: 
 6078: =pod
 6079: 
 6080: =item scantron_todo_count
 6081: 
 6082:     Counts the number of scanlines that need processing.
 6083: 
 6084:  Arguments:
 6085:     $scanlines - hash ref that looks like the first return value from
 6086:                  &scantron_getfile()
 6087:     $scan_data - hash ref that looks like the second return value from
 6088:                  &scantron_getfile()
 6089: 
 6090:  Returns:
 6091:     $count - number of scanlines to process
 6092: 
 6093: =cut
 6094: 
 6095: sub get_todo_count {
 6096:     my ($scanlines,$scan_data)=@_;
 6097:     my $count=0;
 6098:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6099: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6100: 	if ($line=~/^[\s\cz]*$/) { next; }
 6101: 	$count++;
 6102:     }
 6103:     return $count;
 6104: }
 6105: 
 6106: =pod
 6107: 
 6108: =item scantron_put_line
 6109: 
 6110:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6111:     data file.
 6112: 
 6113:  Arguments:
 6114:     $scanlines - hash ref that looks like the first return value from
 6115:                  &scantron_getfile()
 6116:     $scan_data - hash ref that looks like the second return value from
 6117:                  &scantron_getfile()
 6118:     $i         - line number to update
 6119:     $newline   - contents of the updated scanline
 6120:     $skip      - if true make the line for skipping and update the
 6121:                  'skipped' file
 6122: 
 6123: =cut
 6124: 
 6125: sub scantron_put_line {
 6126:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6127:     if ($skip) {
 6128: 	$scanlines->{'skipped'}[$i]=$newline;
 6129: 	&start_skipping($scan_data,$i);
 6130: 	return;
 6131:     }
 6132:     $scanlines->{'corrected'}[$i]=$newline;
 6133: }
 6134: 
 6135: =pod
 6136: 
 6137: =item scantron_clear_skip
 6138: 
 6139:    Remove a line from the 'skipped' 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: 
 6148: =cut
 6149: 
 6150: sub scantron_clear_skip {
 6151:     my ($scanlines,$scan_data,$i)=@_;
 6152:     if (exists($scanlines->{'skipped'}[$i])) {
 6153: 	undef($scanlines->{'skipped'}[$i]);
 6154: 	return 1;
 6155:     }
 6156:     return 0;
 6157: }
 6158: 
 6159: =pod
 6160: 
 6161: =item scantron_filter_not_exam
 6162: 
 6163:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6164:    filter out resources that are not marked as 'exam' mode
 6165: 
 6166: =cut
 6167: 
 6168: sub scantron_filter_not_exam {
 6169:     my ($curres)=@_;
 6170:     
 6171:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6172: 	# if the user has asked to not have either hidden
 6173: 	# or 'randomout' controlled resources to be graded
 6174: 	# don't include them
 6175: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6176: 	    && $curres->randomout) {
 6177: 	    return 0;
 6178: 	}
 6179: 	return 1;
 6180:     }
 6181:     return 0;
 6182: }
 6183: 
 6184: =pod
 6185: 
 6186: =item scantron_validate_sequence
 6187: 
 6188:     Validates the selected sequence, checking for resource that are
 6189:     not set to exam mode.
 6190: 
 6191: =cut
 6192: 
 6193: sub scantron_validate_sequence {
 6194:     my ($r,$currentphase) = @_;
 6195: 
 6196:     my $navmap=Apache::lonnavmaps::navmap->new();
 6197:     my (undef,undef,$sequence)=
 6198: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6199: 
 6200:     my $map=$navmap->getResourceByUrl($sequence);
 6201: 
 6202:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6203:                                     value="ignore" />');
 6204:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6205: 	my @resources=
 6206: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6207: 	if (@resources) {
 6208: 	    $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>");
 6209: 	    return (1,$currentphase);
 6210: 	}
 6211:     }
 6212: 
 6213:     return (0,$currentphase+1);
 6214: }
 6215: 
 6216: =pod
 6217: 
 6218: =item scantron_validate_ID
 6219: 
 6220:    Validates all scanlines in the selected file to not have any
 6221:    invalid or underspecified student IDs
 6222: 
 6223: =cut
 6224: 
 6225: sub scantron_validate_ID {
 6226:     my ($r,$currentphase) = @_;
 6227:     
 6228:     #get student info
 6229:     my $classlist=&Apache::loncoursedata::get_classlist();
 6230:     my %idmap=&username_to_idmap($classlist);
 6231: 
 6232:     #get scantron line setup
 6233:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6234:     my ($scanlines,$scan_data)=&scantron_getfile();
 6235:     
 6236:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6237: 
 6238:     my %found=('ids'=>{},'usernames'=>{});
 6239:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6240: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6241: 	if ($line=~/^[\s\cz]*$/) { next; }
 6242: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6243: 						 $scan_data);
 6244: 	my $id=$$scan_record{'scantron.ID'};
 6245: 	my $found;
 6246: 	foreach my $checkid (keys(%idmap)) {
 6247: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6248: 	}
 6249: 	if ($found) {
 6250: 	    my $username=$idmap{$found};
 6251: 	    if ($found{'ids'}{$found}) {
 6252: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6253: 					 $line,'duplicateID',$found);
 6254: 		return(1,$currentphase);
 6255: 	    } elsif ($found{'usernames'}{$username}) {
 6256: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6257: 					 $line,'duplicateID',$username);
 6258: 		return(1,$currentphase);
 6259: 	    }
 6260: 	    #FIXME store away line we previously saw the ID on to use above
 6261: 	    $found{'ids'}{$found}++;
 6262: 	    $found{'usernames'}{$username}++;
 6263: 	} else {
 6264: 	    if ($id =~ /^\s*$/) {
 6265: 		my $username=&scan_data($scan_data,"$i.user");
 6266: 		if (defined($username) && $found{'usernames'}{$username}) {
 6267: 		    &scantron_get_correction($r,$i,$scan_record,
 6268: 					     \%scantron_config,
 6269: 					     $line,'duplicateID',$username);
 6270: 		    return(1,$currentphase);
 6271: 		} elsif (!defined($username)) {
 6272: 		    &scantron_get_correction($r,$i,$scan_record,
 6273: 					     \%scantron_config,
 6274: 					     $line,'incorrectID');
 6275: 		    return(1,$currentphase);
 6276: 		}
 6277: 		$found{'usernames'}{$username}++;
 6278: 	    } else {
 6279: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6280: 					 $line,'incorrectID');
 6281: 		return(1,$currentphase);
 6282: 	    }
 6283: 	}
 6284:     }
 6285: 
 6286:     return (0,$currentphase+1);
 6287: }
 6288: 
 6289: =pod
 6290: 
 6291: =item scantron_get_correction
 6292: 
 6293:    Builds the interface screen to interact with the operator to fix a
 6294:    specific error condition in a specific scanline
 6295: 
 6296:  Arguments:
 6297:     $r           - Apache request object
 6298:     $i           - number of the current scanline
 6299:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6300:     $scan_config - hash ref as returned from &get_scantron_config()
 6301:     $line        - full contents of the current scanline
 6302:     $error       - error condition, valid values are
 6303:                    'incorrectCODE', 'duplicateCODE',
 6304:                    'doublebubble', 'missingbubble',
 6305:                    'duplicateID', 'incorrectID'
 6306:     $arg         - extra information needed
 6307:        For errors:
 6308:          - duplicateID   - paper number that this studentID was seen before on
 6309:          - duplicateCODE - array ref of the paper numbers this CODE was
 6310:                            seen on before
 6311:          - incorrectCODE - current incorrect CODE 
 6312:          - doublebubble  - array ref of the bubble lines that have double
 6313:                            bubble errors
 6314:          - missingbubble - array ref of the bubble lines that have missing
 6315:                            bubble errors
 6316: 
 6317: =cut
 6318: 
 6319: sub scantron_get_correction {
 6320:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6321: 
 6322: #FIXME in the case of a duplicated ID the previous line, probaly need
 6323: #to show both the current line and the previous one and allow skipping
 6324: #the previous one or the current one
 6325: 
 6326:     $r->print("<p><b>An error was detected ($error)</b>");
 6327:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6328: 	$r->print(" for PaperID <tt>".
 6329: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
 6330:     } else {
 6331: 	$r->print(" in scanline $i <pre>".
 6332: 		  $line."</pre> \n");
 6333:     }
 6334:     my $message="<p>The ID on the form is  <tt>".
 6335: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
 6336: 	"The name on the paper is ".
 6337: 	$$scan_record{'scantron.LastName'}.",".
 6338: 	$$scan_record{'scantron.FirstName'}."</p>";
 6339: 
 6340:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6341:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6342:     if ($error =~ /ID$/) {
 6343: 	if ($error eq 'incorrectID') {
 6344: 	    $r->print("The encoded ID is not in the classlist</p>\n");
 6345: 	} elsif ($error eq 'duplicateID') {
 6346: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
 6347: 	}
 6348: 	$r->print($message);
 6349: 	$r->print("<p>How should I handle this? <br /> \n");
 6350: 	$r->print("\n<ul><li> ");
 6351: 	#FIXME it would be nice if this sent back the user ID and
 6352: 	#could do partial userID matches
 6353: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6354: 				       'scantron_username','scantron_domain'));
 6355: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6356: 	$r->print("\n@".
 6357: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6358: 
 6359: 	$r->print('</li>');
 6360:     } elsif ($error =~ /CODE$/) {
 6361: 	if ($error eq 'incorrectCODE') {
 6362: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
 6363: 	} elsif ($error eq 'duplicateCODE') {
 6364: 	    $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");
 6365: 	}
 6366: 	$r->print("<p>The CODE on the form is  <tt>'".
 6367: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
 6368: 	$r->print($message);
 6369: 	$r->print("<p>How should I handle this? <br /> \n");
 6370: 	$r->print("\n<br /> ");
 6371: 	my $i=0;
 6372: 	if ($error eq 'incorrectCODE' 
 6373: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6374: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6375: 	    if ($closest > 0) {
 6376: 		foreach my $testcode (@{$closest}) {
 6377: 		    my $checked='';
 6378: 		    if (!$i) { $checked=' checked="checked" '; }
 6379: 		    $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' />");
 6380: 		    $r->print("\n<br />");
 6381: 		    $i++;
 6382: 		}
 6383: 	    }
 6384: 	}
 6385: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6386: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6387: 	    $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>");
 6388: 	    $r->print("\n<br />");
 6389: 	}
 6390: 
 6391: 	$r->print(<<ENDSCRIPT);
 6392: <script type="text/javascript">
 6393: function change_radio(field) {
 6394:     var slct=document.scantronupload.scantron_CODE_resolution;
 6395:     var i;
 6396:     for (i=0;i<slct.length;i++) {
 6397:         if (slct[i].value==field) { slct[i].checked=true; }
 6398:     }
 6399: }
 6400: </script>
 6401: ENDSCRIPT
 6402: 	my $href="/adm/pickcode?".
 6403: 	   "form=".&escape("scantronupload").
 6404: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6405: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6406: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6407: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6408: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6409: 	    $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')\" />");
 6410: 	    $r->print("\n<br />");
 6411: 	}
 6412: 	$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.");
 6413: 	$r->print("\n<br /><br />");
 6414:     } elsif ($error eq 'doublebubble') {
 6415: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
 6416: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6417: 		  join(',',@{$arg}).'" />');
 6418: 	$r->print($message);
 6419: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 6420: 	foreach my $question (@{$arg}) {
 6421: 
 6422: 	    my $selected  = &get_response_bubbles($scan_record, $question);
 6423: 	    &scantron_bubble_selector($r,$scan_config,$question,
 6424: 				      split('',$selected));
 6425: 	}
 6426:     } elsif ($error eq 'missingbubble') {
 6427: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
 6428: 	$r->print($message);
 6429: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 6430: 	$r->print("Some questions have no scanned bubbles\n");
 6431: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6432: 		  join(',',@{$arg}).'" />');
 6433: 	foreach my $question (@{$arg}) {
 6434: 	    my $selected = &get_response_bubbles($scan_record, $question);
 6435: 	    &scantron_bubble_selector($r,$scan_config,$question);
 6436: 	}
 6437:     } else {
 6438: 	$r->print("\n<ul>");
 6439:     }
 6440:     $r->print("\n</li></ul>");
 6441: 
 6442: }
 6443: 
 6444: =pod
 6445: 
 6446: =item scantron_bubble_selector
 6447:   
 6448:    Generates the html radiobuttons to correct a single bubble line
 6449:    possibly showing the existing the selected bubbles if known
 6450: 
 6451:  Arguments:
 6452:     $r           - Apache request object
 6453:     $scan_config - hash from &get_scantron_config()
 6454:     $quest       - number of the bubble line to make a corrector for
 6455:     $selected    - array of letters of previously selected bubbles
 6456: 
 6457: =cut
 6458: 
 6459: sub scantron_bubble_selector {
 6460:     my ($r,$scan_config,$quest,@selected)=@_;
 6461:     my $max=$$scan_config{'Qlength'};
 6462: 
 6463:     my $scmode=$$scan_config{'Qon'};
 6464: 
 6465: 
 6466:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 6467: 
 6468:     my $response = $quest-1;
 6469:     my $lines = $bubble_lines_per_response{$response};
 6470:     &Apache::lonnet::logthis("Question $quest, lines: $lines");
 6471: 
 6472:     my $total_lines = $lines*2;
 6473:     my @alphabet=('A'..'Z');
 6474:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
 6475: 
 6476:     for (my $l = 0; $l < $lines; $l++) {
 6477: 	if ($l != 0) {
 6478: 	    $r->print('<tr>');
 6479: 	}
 6480: 
 6481: 	# FIXME:  This loop probably has to be considerably more clever for
 6482: 	#  multiline bubbles: User can multibubble by having bubbles in
 6483: 	#  several lines.  User can skip lines legitimately etc. etc.
 6484: 
 6485: 	for (my $i=0;$i<$max;$i++) {
 6486: 	    $r->print("\n".'<td align="center">');
 6487: 	    if ($selected[0] eq $alphabet[$i]) { 
 6488: 		$r->print('X'); 
 6489: 		shift(@selected) ;
 6490: 	    } else { 
 6491: 		$r->print('&nbsp;'); 
 6492: 	    }
 6493: 	    $r->print('</td>');
 6494: 	    
 6495: 	}
 6496: 
 6497: 	if ($l == 0) {
 6498: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
 6499: 
 6500: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
 6501: 	      $quest.'" value="none" /> No bubble </label></td>');
 6502: 	
 6503: 	}
 6504: 
 6505: 	$r->print('</tr><tr>');
 6506: 
 6507: 	# FIXME: This may have to be a bit more clever for
 6508: 	#        multiline questions (different values e.g..).
 6509: 
 6510: 	for (my $i=0;$i<$max;$i++) {
 6511: 	    $r->print("\n".
 6512: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
 6513: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 6514: 	}
 6515: 	$r->print('</tr>');
 6516: 
 6517: 	    
 6518:     }
 6519:     $r->print('</table>');
 6520: }
 6521: 
 6522: =pod
 6523: 
 6524: =item num_matches
 6525: 
 6526:    Counts the number of characters that are the same between the two arguments.
 6527: 
 6528:  Arguments:
 6529:    $orig - CODE from the scanline
 6530:    $code - CODE to match against
 6531: 
 6532:  Returns:
 6533:    $count - integer count of the number of same characters between the
 6534:             two arguments
 6535: 
 6536: =cut
 6537: 
 6538: sub num_matches {
 6539:     my ($orig,$code) = @_;
 6540:     my @code=split(//,$code);
 6541:     my @orig=split(//,$orig);
 6542:     my $same=0;
 6543:     for (my $i=0;$i<scalar(@code);$i++) {
 6544: 	if ($code[$i] eq $orig[$i]) { $same++; }
 6545:     }
 6546:     return $same;
 6547: }
 6548: 
 6549: =pod
 6550: 
 6551: =item scantron_get_closely_matching_CODEs
 6552: 
 6553:    Cycles through all CODEs and finds the set that has the greatest
 6554:    number of same characters as the provided CODE
 6555: 
 6556:  Arguments:
 6557:    $allcodes - hash ref returned by &get_codes()
 6558:    $CODE     - CODE from the current scanline
 6559: 
 6560:  Returns:
 6561:    2 element list
 6562:     - first elements is number of how closely matching the best fit is 
 6563:       (5 means best set has 5 matching characters)
 6564:     - second element is an arrary ref containing the set of valid CODEs
 6565:       that best fit the passed in CODE
 6566: 
 6567: =cut
 6568: 
 6569: sub scantron_get_closely_matching_CODEs {
 6570:     my ($allcodes,$CODE)=@_;
 6571:     my @CODEs;
 6572:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 6573: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 6574:     }
 6575: 
 6576:     return ($#CODEs,$CODEs[-1]);
 6577: }
 6578: 
 6579: =pod
 6580: 
 6581: =item get_codes
 6582: 
 6583:    Builds a hash which has keys of all of the valid CODEs from the selected
 6584:    set of remembered CODEs.
 6585: 
 6586:  Arguments:
 6587:   $old_name - name of the set of remembered CODEs
 6588:   $cdom     - domain of the course
 6589:   $cnum     - internal course name
 6590: 
 6591:  Returns:
 6592:   %allcodes - keys are the valid CODEs, values are all 1
 6593: 
 6594: =cut
 6595: 
 6596: sub get_codes {
 6597:     my ($old_name, $cdom, $cnum) = @_;
 6598:     if (!$old_name) {
 6599: 	$old_name=$env{'form.scantron_CODElist'};
 6600:     }
 6601:     if (!$cdom) {
 6602: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 6603:     }
 6604:     if (!$cnum) {
 6605: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 6606:     }
 6607:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 6608: 				    $cdom,$cnum);
 6609:     my %allcodes;
 6610:     if ($result{"type\0$old_name"} eq 'number') {
 6611: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 6612:     } else {
 6613: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 6614:     }
 6615:     return %allcodes;
 6616: }
 6617: 
 6618: =pod
 6619: 
 6620: =item scantron_validate_CODE
 6621: 
 6622:    Validates all scanlines in the selected file to not have any
 6623:    invalid or underspecified CODEs and that none of the codes are
 6624:    duplicated if this was requested.
 6625: 
 6626: =cut
 6627: 
 6628: sub scantron_validate_CODE {
 6629:     my ($r,$currentphase) = @_;
 6630:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6631:     if ($scantron_config{'CODElocation'} &&
 6632: 	$scantron_config{'CODEstart'} &&
 6633: 	$scantron_config{'CODElength'}) {
 6634: 	if (!defined($env{'form.scantron_CODElist'})) {
 6635: 	    &FIXME_blow_up()
 6636: 	}
 6637:     } else {
 6638: 	return (0,$currentphase+1);
 6639:     }
 6640:     
 6641:     my %usedCODEs;
 6642: 
 6643:     my %allcodes=&get_codes();
 6644: 
 6645:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 6646: 
 6647:     my ($scanlines,$scan_data)=&scantron_getfile();
 6648:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6649: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6650: 	if ($line=~/^[\s\cz]*$/) { next; }
 6651: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6652: 						 $scan_data);
 6653: 	my $CODE=$$scan_record{'scantron.CODE'};
 6654: 	my $error=0;
 6655: 	if (!&Apache::lonnet::validCODE($CODE)) {
 6656: 	    &scantron_get_correction($r,$i,$scan_record,
 6657: 				     \%scantron_config,
 6658: 				     $line,'incorrectCODE',\%allcodes);
 6659: 	    return(1,$currentphase);
 6660: 	}
 6661: 	if (%allcodes && !exists($allcodes{$CODE}) 
 6662: 	    && !$$scan_record{'scantron.useCODE'}) {
 6663: 	    &scantron_get_correction($r,$i,$scan_record,
 6664: 				     \%scantron_config,
 6665: 				     $line,'incorrectCODE',\%allcodes);
 6666: 	    return(1,$currentphase);
 6667: 	}
 6668: 	if (exists($usedCODEs{$CODE}) 
 6669: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 6670: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 6671: 	    &scantron_get_correction($r,$i,$scan_record,
 6672: 				     \%scantron_config,
 6673: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 6674: 	    return(1,$currentphase);
 6675: 	}
 6676: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 6677:     }
 6678:     return (0,$currentphase+1);
 6679: }
 6680: 
 6681: =pod
 6682: 
 6683: =item scantron_validate_doublebubble
 6684: 
 6685:    Validates all scanlines in the selected file to not have any
 6686:    bubble lines with multiple bubbles marked.
 6687: 
 6688: =cut
 6689: 
 6690: sub scantron_validate_doublebubble {
 6691:     my ($r,$currentphase) = @_;
 6692:     #get student info
 6693:     my $classlist=&Apache::loncoursedata::get_classlist();
 6694:     my %idmap=&username_to_idmap($classlist);
 6695: 
 6696:     #get scantron line setup
 6697:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6698:     my ($scanlines,$scan_data)=&scantron_getfile();
 6699: 
 6700:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 6701: 
 6702:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6703: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6704: 	if ($line=~/^[\s\cz]*$/) { next; }
 6705: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6706: 						 $scan_data);
 6707: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 6708: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 6709: 				 'doublebubble',
 6710: 				 $$scan_record{'scantron.doubleerror'});
 6711:     	return (1,$currentphase);
 6712:     }
 6713:     return (0,$currentphase+1);
 6714: }
 6715: 
 6716: =pod
 6717: 
 6718: =item scantron_get_maxbubble
 6719: 
 6720:    Returns the maximum number of bubble lines that are expected to
 6721:    occur. Does this by walking the selected sequence rendering the
 6722:    resource and then checking &Apache::lonxml::get_problem_counter()
 6723:    for what the current value of the problem counter is.
 6724: 
 6725:    Caches the results to $env{'form.scantron_maxbubble'},
 6726:    $env{'form.scantron.bubble_lines.n'} and 
 6727:    $env{'form.scantron.first_bubble_line.n'}
 6728:    which are the total number of bubble, lines, the number of bubble
 6729:    lines for reponse n and number of the first bubble line for response n.
 6730: 
 6731: =cut
 6732: 
 6733: sub scantron_get_maxbubble {    
 6734:     &Apache::lonnet::logthis("get_max_bubble");
 6735:     if (defined($env{'form.scantron_maxbubble'}) &&
 6736: 	$env{'form.scantron_maxbubble'}) {
 6737: 	&Apache::lonnet::logthis("cached");
 6738: 	&restore_bubble_lines();
 6739: 	return $env{'form.scantron_maxbubble'};
 6740:     }
 6741:     &Apache::lonnet::logthis("computing");
 6742: 
 6743:     my (undef, undef, $sequence) =
 6744: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6745: 
 6746:     my $navmap=Apache::lonnavmaps::navmap->new();
 6747:     my $map=$navmap->getResourceByUrl($sequence);
 6748:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 6749: 
 6750:     &Apache::lonxml::clear_problem_counter();
 6751: 
 6752:     my $uname       = $env{'form.student'};
 6753:     my $udom        = $env{'form.userdom'};
 6754:     my $cid         = $env{'request.course.id'};
 6755:     my $total_lines = 0;
 6756:     %bubble_lines_per_response = ();
 6757:     %first_bubble_line         = ();
 6758: 
 6759:   
 6760:     my $response_number = 0;
 6761:     my $bubble_line     = 0;
 6762:     foreach my $resource (@resources) {
 6763: 	my $symb = $resource->symb();
 6764: 	&Apache::lonxml::clear_bubble_lines_for_part();
 6765: 	my $result=&Apache::lonnet::ssi($resource->src(),
 6766: 					('symb' => $resource->symb()),
 6767: 					('grade_target' => 'analyze'),
 6768: 					('grade_courseid' => $cid),
 6769: 					('grade_domain' => $udom),
 6770: 					('grade_username' => $uname));
 6771: 	my (undef, $an) =
 6772: 	    split(/_HASH_REF__/,$result, 2);
 6773: 
 6774: 	my %analysis = &Apache::lonnet::str2hash($an);
 6775: 
 6776: 
 6777: 
 6778: 	foreach my $part_id (@{$analysis{'parts'}}) {
 6779: 	    my ($trash, $part) = split(/\./, $part_id);
 6780: 
 6781: 	    my $lines = $analysis{"$part_id.bubble_lines"}[0];
 6782: 
 6783: 	    # TODO - make this a persistent hash not an array.
 6784: 
 6785: 
 6786: 	    $first_bubble_line{$response_number}           = $bubble_line;
 6787: 	    $bubble_lines_per_response{$response_number}   = $lines;
 6788: 	    $response_number++;
 6789: 
 6790: 	    $bubble_line +=  $lines;
 6791: 	    $total_lines +=  $lines;
 6792: 	}
 6793: 
 6794:     }
 6795:     &Apache::lonnet::delenv('scantron\.');
 6796: 
 6797:     &save_bubble_lines();
 6798:     $env{'form.scantron_maxbubble'} =
 6799: 	$total_lines;
 6800:     return $env{'form.scantron_maxbubble'};
 6801: }
 6802: 
 6803: =pod
 6804: 
 6805: =item scantron_validate_missingbubbles
 6806: 
 6807:    Validates all scanlines in the selected file to not have any
 6808:     answers that don't have bubbles that have not been verified
 6809:     to be bubble free.
 6810: 
 6811: =cut
 6812: 
 6813: sub scantron_validate_missingbubbles {
 6814:     my ($r,$currentphase) = @_;
 6815:     #get student info
 6816:     my $classlist=&Apache::loncoursedata::get_classlist();
 6817:     my %idmap=&username_to_idmap($classlist);
 6818: 
 6819:     #get scantron line setup
 6820:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6821:     my ($scanlines,$scan_data)=&scantron_getfile();
 6822:     my $max_bubble=&scantron_get_maxbubble();
 6823:     if (!$max_bubble) { $max_bubble=2**31; }
 6824:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6825: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6826: 	if ($line=~/^[\s\cz]*$/) { next; }
 6827: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6828: 						 $scan_data);
 6829: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 6830: 	my @to_correct;
 6831: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 6832: 	    if ($missing > $max_bubble) { next; }
 6833: 	    push(@to_correct,$missing);
 6834: 	}
 6835: 	if (@to_correct) {
 6836: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6837: 				     $line,'missingbubble',\@to_correct);
 6838: 	    return (1,$currentphase);
 6839: 	}
 6840: 
 6841:     }
 6842:     return (0,$currentphase+1);
 6843: }
 6844: 
 6845: =pod
 6846: 
 6847: =item scantron_process_students
 6848: 
 6849:    Routine that does the actual grading of the bubble sheet information.
 6850: 
 6851:    The parsed scanline hash is added to %env 
 6852: 
 6853:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 6854:    foreach resource , with the form data of
 6855: 
 6856: 	'submitted'     =>'scantron' 
 6857: 	'grade_target'  =>'grade',
 6858: 	'grade_username'=> username of student
 6859: 	'grade_domain'  => domain of student
 6860: 	'grade_courseid'=> of course
 6861: 	'grade_symb'    => symb of resource to grade
 6862: 
 6863:     This triggers a grading pass. The problem grading code takes care
 6864:     of converting the bubbled letter information (now in %env) into a
 6865:     valid submission.
 6866: 
 6867: =cut
 6868: 
 6869: sub scantron_process_students {
 6870:     my ($r) = @_;
 6871:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6872:     my ($symb)=&get_symb($r);
 6873:     if (!$symb) {return '';}
 6874:     my $default_form_data=&defaultFormData($symb);
 6875: 
 6876:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6877:     my ($scanlines,$scan_data)=&scantron_getfile();
 6878:     my $classlist=&Apache::loncoursedata::get_classlist();
 6879:     my %idmap=&username_to_idmap($classlist);
 6880:     my $navmap=Apache::lonnavmaps::navmap->new();
 6881:     my $map=$navmap->getResourceByUrl($sequence);
 6882:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 6883: #    $r->print("geto ".scalar(@resources)."<br />");
 6884:     my $result= <<SCANTRONFORM;
 6885: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6886:   <input type="hidden" name="command" value="scantron_configphase" />
 6887:   $default_form_data
 6888: SCANTRONFORM
 6889:     $r->print($result);
 6890: 
 6891:     my @delayqueue;
 6892:     my %completedstudents;
 6893:     
 6894:     my $count=&get_todo_count($scanlines,$scan_data);
 6895:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 6896:  				    'Scantron Progress',$count,
 6897: 				    'inline',undef,'scantronupload');
 6898:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 6899: 					  'Processing first student');
 6900:     my $start=&Time::HiRes::time();
 6901:     my $i=-1;
 6902:     my ($uname,$udom,$started);
 6903: 
 6904:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 6905: 
 6906:     while ($i<$scanlines->{'count'}) {
 6907:  	($uname,$udom)=('','');
 6908:  	$i++;
 6909:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6910:  	if ($line=~/^[\s\cz]*$/) { next; }
 6911: 	if ($started) {
 6912: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 6913: 						     'last student');
 6914: 	}
 6915: 	$started=1;
 6916:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6917:  						 $scan_data);
 6918:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 6919:  					      \%idmap,$i)) {
 6920:   	    &scantron_add_delay(\@delayqueue,$line,
 6921:  				'Unable to find a student that matches',1);
 6922:  	    next;
 6923:   	}
 6924:  	if (exists $completedstudents{$uname}) {
 6925:  	    &scantron_add_delay(\@delayqueue,$line,
 6926:  				'Student '.$uname.' has multiple sheets',2);
 6927:  	    next;
 6928:  	}
 6929:   	($uname,$udom)=split(/:/,$uname);
 6930: 
 6931: 	&Apache::lonxml::clear_problem_counter();
 6932:   	&Apache::lonnet::appenv(%$scan_record);
 6933: 
 6934: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 6935: 	    &scantron_putfile($scanlines,$scan_data);
 6936: 	}
 6937: 	
 6938: 	my $i=0;
 6939: 	foreach my $resource (@resources) {
 6940: 	    $i++;
 6941: 	    my %form=('submitted'     =>'scantron',
 6942: 		      'grade_target'  =>'grade',
 6943: 		      'grade_username'=>$uname,
 6944: 		      'grade_domain'  =>$udom,
 6945: 		      'grade_courseid'=>$env{'request.course.id'},
 6946: 		      'grade_symb'    =>$resource->symb());
 6947: 	    if (exists($scan_record->{'scantron.CODE'})
 6948: 		&& 
 6949: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
 6950: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 6951: 	    } else {
 6952: 		$form{'CODE'}='';
 6953: 	    }
 6954: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
 6955: 	    if ($result ne '') {
 6956: 	    }
 6957: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 6958: 	}
 6959: 	$completedstudents{$uname}={'line'=>$line};
 6960: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 6961:     } continue {
 6962: 	&Apache::lonxml::clear_problem_counter();
 6963: 	&Apache::lonnet::delenv('scantron\.');
 6964:     }
 6965:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 6966: #    my $lasttime = &Time::HiRes::time()-$start;
 6967: #    $r->print("<p>took $lasttime</p>");
 6968: 
 6969:     $r->print("</form>");
 6970:     $r->print(&show_grading_menu_form($symb));
 6971:     return '';
 6972: }
 6973: 
 6974: =pod
 6975: 
 6976: =item scantron_upload_scantron_data
 6977: 
 6978:     Creates the screen for adding a new bubble sheet data file to a course.
 6979: 
 6980: =cut
 6981: 
 6982: sub scantron_upload_scantron_data {
 6983:     my ($r)=@_;
 6984:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 6985:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 6986: 							  'domainid',
 6987: 							  'coursename');
 6988:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 6989: 						   'domainid');
 6990:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 6991:     $r->print(<<UPLOAD);
 6992: <script type="text/javascript" language="javascript">
 6993:     function checkUpload(formname) {
 6994: 	if (formname.upfile.value == "") {
 6995: 	    alert("Please use the browse button to select a file from your local directory.");
 6996: 	    return false;
 6997: 	}
 6998: 	formname.submit();
 6999:     }
 7000: </script>
 7001: 
 7002: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 7003: $default_form_data
 7004: <table>
 7005: <tr><td>$select_link </td></tr>
 7006: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
 7007: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
 7008: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
 7009: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
 7010: </table>
 7011: <input name='command' value='scantronupload_save' type='hidden' />
 7012: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 7013: </form>
 7014: UPLOAD
 7015:     return '';
 7016: }
 7017: 
 7018: =pod
 7019: 
 7020: =item scantron_upload_scantron_data_save
 7021: 
 7022:    Adds a provided bubble information data file to the course if user
 7023:    has the correct privileges to do so.  
 7024: 
 7025: =cut
 7026: 
 7027: sub scantron_upload_scantron_data_save {
 7028:     my($r)=@_;
 7029:     my ($symb)=&get_symb($r,1);
 7030:     my $doanotherupload=
 7031: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7032: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7033: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
 7034: 	'</form>'."\n";
 7035:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7036: 	!&Apache::lonnet::allowed('usc',
 7037: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7038: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
 7039: 	if ($symb) {
 7040: 	    $r->print(&show_grading_menu_form($symb));
 7041: 	} else {
 7042: 	    $r->print($doanotherupload);
 7043: 	}
 7044: 	return '';
 7045:     }
 7046:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7047:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
 7048:     my $fname=$env{'form.upfile.filename'};
 7049:     #FIXME
 7050:     #copied from lonnet::userfileupload()
 7051:     #make that function able to target a specified course
 7052:     # Replace Windows backslashes by forward slashes
 7053:     $fname=~s/\\/\//g;
 7054:     # Get rid of everything but the actual filename
 7055:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7056:     # Replace spaces by underscores
 7057:     $fname=~s/\s+/\_/g;
 7058:     # Replace all other weird characters by nothing
 7059:     $fname=~s/[^\w\.\-]//g;
 7060:     # See if there is anything left
 7061:     unless ($fname) { return 'error: no uploaded file'; }
 7062:     my $uploadedfile=$fname;
 7063:     $fname='scantron_orig_'.$fname;
 7064:     if (length($env{'form.upfile'}) < 2) {
 7065: 	$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.");
 7066:     } else {
 7067: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7068: 	if ($result =~ m|^/uploaded/|) {
 7069: 	    $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
 7070: 	} else {
 7071: 	    $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>");
 7072: 	}
 7073:     }
 7074:     if ($symb) {
 7075: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7076:     } else {
 7077: 	$r->print($doanotherupload);
 7078:     }
 7079:     return '';
 7080: }
 7081: 
 7082: =pod
 7083: 
 7084: =item valid_file
 7085: 
 7086:    Validates that the requested bubble data file exists in the course.
 7087: 
 7088: =cut
 7089: 
 7090: sub valid_file {
 7091:     my ($requested_file)=@_;
 7092:     foreach my $filename (sort(&scantron_filenames())) {
 7093: 	if ($requested_file eq $filename) { return 1; }
 7094:     }
 7095:     return 0;
 7096: }
 7097: 
 7098: =pod
 7099: 
 7100: =item scantron_download_scantron_data
 7101: 
 7102:    Shows a list of the three internal files (original, corrected,
 7103:    skipped) for a specific bubble sheet data file that exists in the
 7104:    course.
 7105: 
 7106: =cut
 7107: 
 7108: sub scantron_download_scantron_data {
 7109:     my ($r)=@_;
 7110:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7111:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7112:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7113:     my $file=$env{'form.scantron_selectfile'};
 7114:     if (! &valid_file($file)) {
 7115: 	$r->print(<<ERROR);
 7116: 	<p>
 7117: 	    The requested file name was invalid.
 7118:         </p>
 7119: ERROR
 7120: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7121: 	return;
 7122:     }
 7123:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7124:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7125:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7126:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7127:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7128:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7129:     $r->print(<<DOWNLOAD);
 7130:     <p>
 7131: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
 7132:     </p>
 7133:     <p>
 7134: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
 7135:     </p>
 7136:     <p>
 7137: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
 7138:     </p>
 7139: DOWNLOAD
 7140:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7141:     return '';
 7142: }
 7143: 
 7144: =pod
 7145: 
 7146: =back
 7147: 
 7148: =cut
 7149: 
 7150: #-------- end of section for handling grading scantron forms -------
 7151: #
 7152: #-------------------------------------------------------------------
 7153: 
 7154: #-------------------------- Menu interface -------------------------
 7155: #
 7156: #--- Show a Grading Menu button - Calls the next routine ---
 7157: sub show_grading_menu_form {
 7158:     my ($symb)=@_;
 7159:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 7160: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7161: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 7162: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 7163: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
 7164: 	'</form>'."\n";
 7165:     return $result;
 7166: }
 7167: 
 7168: # -- Retrieve choices for grading form
 7169: sub savedState {
 7170:     my %savedState = ();
 7171:     if ($env{'form.saveState'}) {
 7172: 	foreach (split(/:/,$env{'form.saveState'})) {
 7173: 	    my ($key,$value) = split(/=/,$_,2);
 7174: 	    $savedState{$key} = $value;
 7175: 	}
 7176:     }
 7177:     return \%savedState;
 7178: }
 7179: 
 7180: sub grading_menu {
 7181:     my ($request) = @_;
 7182:     my ($symb)=&get_symb($request);
 7183:     if (!$symb) {return '';}
 7184:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7185:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7186: 
 7187:     #
 7188:     # Define menu data
 7189:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 7190:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 7191:     $request->print($table);
 7192:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 7193:                   'handgrade'=>$hdgrade,
 7194:                   'probTitle'=>$probTitle,
 7195:                   'command'=>'submit_options',
 7196:                   'saveState'=>"",
 7197:                   'gradingMenu'=>1,
 7198:                   'showgrading'=>"yes");
 7199:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7200:     my @menu = ({ url => $url,
 7201:                      name => &mt('Manual Grading/View Submissions'),
 7202:                      short_description => 
 7203:     &mt('Start the process of hand grading submissions.'),
 7204:                  });
 7205:     $fields{'command'} = 'csvform';
 7206:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7207:     push (@menu, { url => $url,
 7208:                    name => &mt('Upload Scores'),
 7209:                    short_description => 
 7210:             &mt('Specify a file containing the class scores for current resource.')});
 7211:     $fields{'command'} = 'processclicker';
 7212:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7213:     push (@menu, { url => $url,
 7214:                    name => &mt('Process Clicker'),
 7215:                    short_description => 
 7216:             &mt('Specify a file containing the clicker information for this resource.')});
 7217:     $fields{'command'} = 'scantron_selectphase';
 7218:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7219:     push (@menu, { url => $url,
 7220:                    name => &mt('Grade Scantron Forms'),
 7221:                    short_description => 
 7222:             &mt('')});
 7223:     $fields{'command'} = 'verify';
 7224:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7225:     push (@menu, { url => "",
 7226:                    jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
 7227:                    name => &mt('Verify Receipt'),
 7228:                    short_description => 
 7229:             &mt('')});
 7230:     $fields{'command'} = 'manage';
 7231:     $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
 7232:     push (@menu, { url => $url,
 7233:                    name => &mt('Manage Access Times'),
 7234:                    short_description => 
 7235:             &mt('')});
 7236:     $fields{'command'} = 'view';
 7237:     $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
 7238:     push (@menu, { url => $url,
 7239:                    name => &mt('View Saved CODEs'),
 7240:                    short_description => 
 7241:             &mt('')});
 7242: 
 7243:     #
 7244:     # Create the menu
 7245:     my $Str;
 7246:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 7247:     $Str .= '<form method="post" action="" name="gradingMenu">';
 7248:     $Str .= '<input type="hidden" name="command" value="" />'.
 7249:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7250: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7251: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
 7252: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7253: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7254: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7255: 
 7256:     foreach my $menudata (@menu) {
 7257:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 7258:             $Str .='    <h3><a '.
 7259:                 $menudata->{'jscript'}.
 7260:                 ' href="'.
 7261:                 $menudata->{'url'}.'" >'.
 7262:                 $menudata->{'name'}."</a></h3>\n";
 7263:         } else {
 7264:             $Str .='    <h3><a '.
 7265:                 $menudata->{'jscript'}.
 7266:                 ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
 7267:                 $menudata->{'name'}."</a></h3>\n";
 7268:             $Str .= ('&nbsp;'x8).
 7269:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
 7270:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 7271:         }
 7272:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 7273:             "\n";
 7274:     }
 7275:     $Str .="</dl>\n";
 7276:     $Str .="</form>\n";
 7277:     $request->print(<<GRADINGMENUJS);
 7278: <script type="text/javascript" language="javascript">
 7279:     function checkChoice(formname,val,cmdx) {
 7280: 	if (val <= 2) {
 7281: 	    var cmd = radioSelection(formname.radioChoice);
 7282: 	    var cmdsave = cmd;
 7283: 	} else {
 7284: 	    cmd = cmdx;
 7285: 	    cmdsave = 'submission';
 7286: 	}
 7287: 	formname.command.value = cmd;
 7288: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 7289: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 7290: 	if (val < 5) formname.submit();
 7291: 	if (val == 5) {
 7292: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7293: 	    formname.submit();
 7294: 	}
 7295: 	if (val < 7) formname.submit();
 7296:     }
 7297:     function checkChoice2(formname,val,cmdx) {
 7298: 	if (val <= 2) {
 7299: 	    var cmd = radioSelection(formname.radioChoice);
 7300: 	    var cmdsave = cmd;
 7301: 	} else {
 7302: 	    cmd = cmdx;
 7303: 	    cmdsave = 'submission';
 7304: 	}
 7305: 	formname.command.value = cmd;
 7306: 	if (val < 5) formname.submit();
 7307: 	if (val == 5) {
 7308: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7309: 	    formname.submit();
 7310: 	}
 7311: 	if (val < 7) formname.submit();
 7312:     }
 7313: 
 7314:     function checkReceiptNo(formname,nospace) {
 7315: 	var receiptNo = formname.receipt.value;
 7316: 	var checkOpt = false;
 7317: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7318: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7319: 	if (checkOpt) {
 7320: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7321: 	    formname.receipt.value = "";
 7322: 	    formname.receipt.focus();
 7323: 	    return false;
 7324: 	}
 7325: 	return true;
 7326:     }
 7327: </script>
 7328: GRADINGMENUJS
 7329:     &commonJSfunctions($request);
 7330:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
 7331:     $result.=$table;
 7332:     my (undef,$sections) = &getclasslist('all','0');
 7333:     my $savedState = &savedState();
 7334:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 7335:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 7336:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 7337:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 7338: 
 7339:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 7340: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7341: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7342: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
 7343: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7344: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7345: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7346: 
 7347:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
 7348: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
 7349: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
 7350: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
 7351: 
 7352:     $result.='<table width="100%" border="0">';
 7353:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
 7354:     $result.='<td><b>'.&mt('Sections').'</b></td>';
 7355: #    $result.='<td>Groups</td>';
 7356:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
 7357:     $result.='</tr>';
 7358:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
 7359: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
 7360:     if (ref($sections)) {
 7361: 	foreach (sort (@$sections)) {
 7362: 	    $result.='<option value="'.$_.'" '.
 7363: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
 7364: 	}
 7365:     }
 7366:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 7367:     return $Str;    
 7368: }
 7369: 
 7370: 
 7371: #--- Displays the submissions first page -------
 7372: sub submit_options {
 7373:     my ($request) = @_;
 7374:     my ($symb)=&get_symb($request);
 7375:     if (!$symb) {return '';}
 7376:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7377: 
 7378:     $request->print(<<GRADINGMENUJS);
 7379: <script type="text/javascript" language="javascript">
 7380:     function checkChoice(formname,val,cmdx) {
 7381: 	if (val <= 2) {
 7382: 	    var cmd = radioSelection(formname.radioChoice);
 7383: 	    var cmdsave = cmd;
 7384: 	} else {
 7385: 	    cmd = cmdx;
 7386: 	    cmdsave = 'submission';
 7387: 	}
 7388: 	formname.command.value = cmd;
 7389: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 7390: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 7391: 	if (val < 5) formname.submit();
 7392: 	if (val == 5) {
 7393: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7394: 	    formname.submit();
 7395: 	}
 7396: 	if (val < 7) formname.submit();
 7397:     }
 7398: 
 7399:     function checkReceiptNo(formname,nospace) {
 7400: 	var receiptNo = formname.receipt.value;
 7401: 	var checkOpt = false;
 7402: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7403: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7404: 	if (checkOpt) {
 7405: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7406: 	    formname.receipt.value = "";
 7407: 	    formname.receipt.focus();
 7408: 	    return false;
 7409: 	}
 7410: 	return true;
 7411:     }
 7412: </script>
 7413: GRADINGMENUJS
 7414:     &commonJSfunctions($request);
 7415:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
 7416:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7417:     $result.=$table;
 7418:     my (undef,$sections) = &getclasslist('all','0');
 7419:     my $savedState = &savedState();
 7420:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 7421:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 7422:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 7423:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 7424: 
 7425:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 7426: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7427: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7428: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 7429: 	'<input type="hidden" name="command"     value="" />'."\n".
 7430: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7431: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7432: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7433: 
 7434:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
 7435: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
 7436: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
 7437: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
 7438: 
 7439:     $result.='<table width="100%" border="0">';
 7440:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
 7441:     $result.='<td><b>'.&mt('Sections').'</b></td>';
 7442:     $result.='<td><b>'.&mt('Groups').'</b></td>';
 7443:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
 7444:     $result.='</tr>';
 7445:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
 7446: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
 7447:     if (ref($sections)) {
 7448: 	foreach (sort (@$sections)) {
 7449: 	    $result.='<option value="'.$_.'" '.
 7450: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
 7451: 	}
 7452:     }
 7453:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 7454:     $result.= '</td><td>'."\n";
 7455:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
 7456:     $result.='</td><td>'."\n";
 7457:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
 7458: 
 7459:     $result.='</td></tr>';
 7460: 
 7461:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
 7462: 	'<input type="radio" name="radioChoice" value="submission" '.
 7463: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
 7464: 	'</label> <select name="submitonly">'.
 7465: 	'<option value="yes" '.
 7466: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
 7467: 	'<option value="queued" '.
 7468: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
 7469: 	'<option value="graded" '.
 7470: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
 7471: 	'<option value="incorrect" '.
 7472: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
 7473: 	'<option value="all" '.
 7474: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
 7475: 
 7476:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7477: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
 7478: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 7479: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
 7480: 
 7481:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
 7482: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
 7483: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 7484: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
 7485: 
 7486:     $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
 7487: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
 7488: 	'</td></tr></table>'."\n";
 7489: 
 7490:     $result.='</td>'; #<td valign="top">';
 7491: 
 7492: #    $result.='<table width="100%" border="0">';
 7493: #    $result.='<tr bgcolor="#ffffe6"><td>'.
 7494: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
 7495: #	' '.&mt('scores from file').' </td></tr>'."\n";
 7496: #
 7497: #    $result.='<tr bgcolor="#ffffe6"><td>'.
 7498: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
 7499: #        ' '.&mt('clicker file').' </td></tr>'."\n";
 7500: #
 7501: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7502: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
 7503: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
 7504: #
 7505: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
 7506: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 7507: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
 7508: #	    ' '.&mt('receipt').': '.
 7509: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
 7510: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
 7511: #	    '</td></tr>'."\n";
 7512: #    } 
 7513: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7514: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
 7515: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
 7516: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7517: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
 7518: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
 7519: #
 7520: #    $result.='</table>'."\n".'</td>';
 7521:     $result.= '</tr></table>'."\n".
 7522: 	'</td></tr></table></form>'."\n";
 7523:     return $result;
 7524: }
 7525: 
 7526: sub reset_perm {
 7527:     undef(%perm);
 7528: }
 7529: 
 7530: sub init_perm {
 7531:     &reset_perm();
 7532:     foreach my $test_perm ('vgr','mgr','opa') {
 7533: 
 7534: 	my $scope = $env{'request.course.id'};
 7535: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 7536: 
 7537: 	    $scope .= '/'.$env{'request.course.sec'};
 7538: 	    if ( $perm{$test_perm}=
 7539: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 7540: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 7541: 	    } else {
 7542: 		delete($perm{$test_perm});
 7543: 	    }
 7544: 	}
 7545:     }
 7546: }
 7547: 
 7548: sub gather_clicker_ids {
 7549:     my %clicker_ids;
 7550: 
 7551:     my $classlist = &Apache::loncoursedata::get_classlist();
 7552: 
 7553:     # Set up a couple variables.
 7554:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 7555:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 7556:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 7557: 
 7558:     foreach my $student (keys(%$classlist)) {
 7559:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 7560:         my $username = $classlist->{$student}->[$username_idx];
 7561:         my $domain   = $classlist->{$student}->[$domain_idx];
 7562:         my $clickers =
 7563: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 7564:         foreach my $id (split(/\,/,$clickers)) {
 7565:             $id=~s/^[\#0]+//;
 7566:             $id=~s/[\-\:]//g;
 7567:             if (exists($clicker_ids{$id})) {
 7568: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 7569:             } else {
 7570: 		$clicker_ids{$id}=$username.':'.$domain;
 7571:             }
 7572:         }
 7573:     }
 7574:     return %clicker_ids;
 7575: }
 7576: 
 7577: sub gather_adv_clicker_ids {
 7578:     my %clicker_ids;
 7579:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 7580:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7581:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 7582:     foreach my $element (sort(keys(%coursepersonnel))) {
 7583:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 7584:             my ($puname,$pudom)=split(/\:/,$person);
 7585:             my $clickers =
 7586: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 7587:             foreach my $id (split(/\,/,$clickers)) {
 7588: 		$id=~s/^[\#0]+//;
 7589:                 $id=~s/[\-\:]//g;
 7590: 		if (exists($clicker_ids{$id})) {
 7591: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 7592: 		} else {
 7593: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 7594: 		}
 7595:             }
 7596:         }
 7597:     }
 7598:     return %clicker_ids;
 7599: }
 7600: 
 7601: sub clicker_grading_parameters {
 7602:     return ('gradingmechanism' => 'scalar',
 7603:             'upfiletype' => 'scalar',
 7604:             'specificid' => 'scalar',
 7605:             'pcorrect' => 'scalar',
 7606:             'pincorrect' => 'scalar');
 7607: }
 7608: 
 7609: sub process_clicker {
 7610:     my ($r)=@_;
 7611:     my ($symb)=&get_symb($r);
 7612:     if (!$symb) {return '';}
 7613:     my $result=&checkforfile_js();
 7614:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 7615:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 7616:     $result.=$table;
 7617:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 7618:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 7619:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 7620:         '.</b></td></tr>'."\n";
 7621:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 7622: # Attempt to restore parameters from last session, set defaults if not present
 7623:     my %Saveable_Parameters=&clicker_grading_parameters();
 7624:     &Apache::loncommon::restore_course_settings('grades_clicker',
 7625:                                                  \%Saveable_Parameters);
 7626:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 7627:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 7628:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 7629:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 7630: 
 7631:     my %checked;
 7632:     foreach my $gradingmechanism ('attendance','personnel','specific') {
 7633:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 7634:           $checked{$gradingmechanism}="checked='checked'";
 7635:        }
 7636:     }
 7637: 
 7638:     my $upload=&mt("Upload File");
 7639:     my $type=&mt("Type");
 7640:     my $attendance=&mt("Award points just for participation");
 7641:     my $personnel=&mt("Correctness determined from response by course personnel");
 7642:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 7643:     my $pcorrect=&mt("Percentage points for correct solution");
 7644:     my $pincorrect=&mt("Percentage points for incorrect solution");
 7645:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 7646: 						   ('iclicker' => 'i>clicker',
 7647:                                                     'interwrite' => 'interwrite PRS'));
 7648:     $symb = &Apache::lonenc::check_encrypt($symb);
 7649:     $result.=<<ENDUPFORM;
 7650: <script type="text/javascript">
 7651: function sanitycheck() {
 7652: // Accept only integer percentages
 7653:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 7654:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 7655: // Find out grading choice
 7656:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 7657:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 7658:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 7659:       }
 7660:    }
 7661: // By default, new choice equals user selection
 7662:    newgradingchoice=gradingchoice;
 7663: // Not good to give more points for false answers than correct ones
 7664:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 7665:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 7666:    }
 7667: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 7668:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 7669:       document.forms.gradesupload.pcorrect.value=100;
 7670:       document.forms.gradesupload.pincorrect.value=100;
 7671:    }
 7672: // If the values are different, cannot be attendance only
 7673:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 7674:        (gradingchoice=='attendance')) {
 7675:        newgradingchoice='personnel';
 7676:    }
 7677: // Change grading choice to new one
 7678:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 7679:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 7680:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 7681:       } else {
 7682:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 7683:       }
 7684:    }
 7685: // Remember the old state
 7686:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 7687: }
 7688: </script>
 7689: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 7690: <input type="hidden" name="symb" value="$symb" />
 7691: <input type="hidden" name="command" value="processclickerfile" />
 7692: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 7693: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 7694: <input type="file" name="upfile" size="50" />
 7695: <br /><label>$type: $selectform</label>
 7696: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
 7697: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
 7698: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
 7699: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 7700: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 7701: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 7702: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 7703: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 7704: </form>
 7705: ENDUPFORM
 7706:     $result.='</td></tr></table>'."\n".
 7707:              '</td></tr></table><br /><br />'."\n";
 7708:     $result.=&show_grading_menu_form($symb);
 7709:     return $result;
 7710: }
 7711: 
 7712: sub process_clicker_file {
 7713:     my ($r)=@_;
 7714:     my ($symb)=&get_symb($r);
 7715:     if (!$symb) {return '';}
 7716: 
 7717:     my %Saveable_Parameters=&clicker_grading_parameters();
 7718:     &Apache::loncommon::store_course_settings('grades_clicker',
 7719:                                               \%Saveable_Parameters);
 7720: 
 7721:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 7722:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 7723: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 7724: 	return $result.&show_grading_menu_form($symb);
 7725:     }
 7726:     my %clicker_ids=&gather_clicker_ids();
 7727:     my %correct_ids;
 7728:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 7729: 	%correct_ids=&gather_adv_clicker_ids();
 7730:     }
 7731:     if ($env{'form.gradingmechanism'} eq 'specific') {
 7732: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 7733: 	   $correct_id=~tr/a-z/A-Z/;
 7734: 	   $correct_id=~s/\s//gs;
 7735: 	   $correct_id=~s/^[\#0]+//;
 7736:            $correct_id=~s/[\-\:]//g;
 7737:            if ($correct_id) {
 7738: 	      $correct_ids{$correct_id}='specified';
 7739:            }
 7740:         }
 7741:     }
 7742:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 7743: 	$result.=&mt('Score based on attendance only');
 7744:     } else {
 7745: 	my $number=0;
 7746: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 7747: 	foreach my $id (sort(keys(%correct_ids))) {
 7748: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 7749: 	    if ($correct_ids{$id} eq 'specified') {
 7750: 		$result.=&mt('specified');
 7751: 	    } else {
 7752: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 7753: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 7754: 	    }
 7755: 	    $number++;
 7756: 	}
 7757:         $result.="</p>\n";
 7758: 	if ($number==0) {
 7759: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 7760: 	    return $result.&show_grading_menu_form($symb);
 7761: 	}
 7762:     }
 7763:     if (length($env{'form.upfile'}) < 2) {
 7764:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 7765: 		     '<span class="LC_error">',
 7766: 		     '</span>',
 7767: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 7768:         return $result.&show_grading_menu_form($symb);
 7769:     }
 7770: 
 7771: # Were able to get all the info needed, now analyze the file
 7772: 
 7773:     $result.=&Apache::loncommon::studentbrowser_javascript();
 7774:     $symb = &Apache::lonenc::check_encrypt($symb);
 7775:     my $heading=&mt('Scanning clicker file');
 7776:     $result.=(<<ENDHEADER);
 7777: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 7778: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 7779: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 7780: <form method="post" action="/adm/grades" name="clickeranalysis">
 7781: <input type="hidden" name="symb" value="$symb" />
 7782: <input type="hidden" name="command" value="assignclickergrades" />
 7783: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 7784: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 7785: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 7786: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 7787: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 7788: ENDHEADER
 7789:     my %responses;
 7790:     my @questiontitles;
 7791:     my $errormsg='';
 7792:     my $number=0;
 7793:     if ($env{'form.upfiletype'} eq 'iclicker') {
 7794: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 7795:     }
 7796:     if ($env{'form.upfiletype'} eq 'interwrite') {
 7797:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 7798:     }
 7799:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 7800:              '<input type="hidden" name="number" value="'.$number.'" />'.
 7801:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
 7802:              '<input type="hidden" name="number" value="'.$number.'" />'.
 7803:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 7804:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 7805:              '<br />';
 7806: # Remember Question Titles
 7807: # FIXME: Possibly need delimiter other than ":"
 7808:     for (my $i=0;$i<$number;$i++) {
 7809:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 7810:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 7811:     }
 7812:     my $correct_count=0;
 7813:     my $student_count=0;
 7814:     my $unknown_count=0;
 7815: # Match answers with usernames
 7816: # FIXME: Possibly need delimiter other than ":"
 7817:     foreach my $id (keys(%responses)) {
 7818:        if ($correct_ids{$id}) {
 7819:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 7820:           $correct_count++;
 7821:        } elsif ($clicker_ids{$id}) {
 7822:           if ($clicker_ids{$id}=~/\,/) {
 7823: # More than one user with the same clicker!
 7824:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 7825:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 7826:                            "<select name='multi".$id."'>";
 7827:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 7828:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 7829:              }
 7830:              $result.='</select>';
 7831:              $unknown_count++;
 7832:           } else {
 7833: # Good: found one and only one user with the right clicker
 7834:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 7835:              $student_count++;
 7836:           }
 7837:        } else {
 7838:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 7839:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 7840:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 7841:                    "\n".&mt("Domain").": ".
 7842:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 7843:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 7844:           $unknown_count++;
 7845:        }
 7846:     }
 7847:     $result.='<hr />'.
 7848:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 7849:     if ($env{'form.gradingmechanism'} ne 'attendance') {
 7850:        if ($correct_count==0) {
 7851:           $errormsg.="Found no correct answers answers for grading!";
 7852:        } elsif ($correct_count>1) {
 7853:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 7854:        }
 7855:     }
 7856:     if ($number<1) {
 7857:        $errormsg.="Found no questions.";
 7858:     }
 7859:     if ($errormsg) {
 7860:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 7861:     } else {
 7862:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 7863:     }
 7864:     $result.='</form></td></tr></table>'."\n".
 7865:              '</td></tr></table><br /><br />'."\n";
 7866:     return $result.&show_grading_menu_form($symb);
 7867: }
 7868: 
 7869: sub iclicker_eval {
 7870:     my ($questiontitles,$responses)=@_;
 7871:     my $number=0;
 7872:     my $errormsg='';
 7873:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 7874:         my %components=&Apache::loncommon::record_sep($line);
 7875:         my @entries=map {$components{$_}} (sort(keys(%components)));
 7876: 	if ($entries[0] eq 'Question') {
 7877: 	    for (my $i=3;$i<$#entries;$i+=6) {
 7878: 		$$questiontitles[$number]=$entries[$i];
 7879: 		$number++;
 7880: 	    }
 7881: 	}
 7882: 	if ($entries[0]=~/^\#/) {
 7883: 	    my $id=$entries[0];
 7884: 	    my @idresponses;
 7885: 	    $id=~s/^[\#0]+//;
 7886: 	    for (my $i=0;$i<$number;$i++) {
 7887: 		my $idx=3+$i*6;
 7888: 		push(@idresponses,$entries[$idx]);
 7889: 	    }
 7890: 	    $$responses{$id}=join(',',@idresponses);
 7891: 	}
 7892:     }
 7893:     return ($errormsg,$number);
 7894: }
 7895: 
 7896: sub interwrite_eval {
 7897:     my ($questiontitles,$responses)=@_;
 7898:     my $number=0;
 7899:     my $errormsg='';
 7900:     my $skipline=1;
 7901:     my $questionnumber=0;
 7902:     my %idresponses=();
 7903:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 7904:         my %components=&Apache::loncommon::record_sep($line);
 7905:         my @entries=map {$components{$_}} (sort(keys(%components)));
 7906:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 7907:         if ($entries[1] eq 'Response') { $skipline=1; }
 7908:         next if $skipline;
 7909:         if ($entries[0]!=$questionnumber) {
 7910:            $questionnumber=$entries[0];
 7911:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 7912:            $number++;
 7913:         }
 7914:         my $id=$entries[4];
 7915:         $id=~s/^[\#0]+//;
 7916:         $id=~s/^v\d*\://i;
 7917:         $id=~s/[\-\:]//g;
 7918:         $idresponses{$id}[$number]=$entries[6];
 7919:     }
 7920:     foreach my $id (keys %idresponses) {
 7921:        $$responses{$id}=join(',',@{$idresponses{$id}});
 7922:        $$responses{$id}=~s/^\s*\,//;
 7923:     }
 7924:     return ($errormsg,$number);
 7925: }
 7926: 
 7927: sub assign_clicker_grades {
 7928:     my ($r)=@_;
 7929:     my ($symb)=&get_symb($r);
 7930:     if (!$symb) {return '';}
 7931: # See which part we are saving to
 7932:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 7933: # FIXME: This should probably look for the first handgradeable part
 7934:     my $part=$$partlist[0];
 7935: # Start screen output
 7936:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 7937: 
 7938:     my $heading=&mt('Assigning grades based on clicker file');
 7939:     $result.=(<<ENDHEADER);
 7940: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 7941: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 7942: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 7943: ENDHEADER
 7944: # Get correct result
 7945: # FIXME: Possibly need delimiter other than ":"
 7946:     my @correct=();
 7947:     my $gradingmechanism=$env{'form.gradingmechanism'};
 7948:     my $number=$env{'form.number'};
 7949:     if ($gradingmechanism ne 'attendance') {
 7950:        foreach my $key (keys(%env)) {
 7951:           if ($key=~/^form\.correct\:/) {
 7952:              my @input=split(/\,/,$env{$key});
 7953:              for (my $i=0;$i<=$#input;$i++) {
 7954:                  if (($correct[$i]) && ($input[$i]) &&
 7955:                      ($correct[$i] ne $input[$i])) {
 7956:                     $result.='<br /><span class="LC_warning">'.
 7957:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 7958:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 7959:                  } elsif ($input[$i]) {
 7960:                     $correct[$i]=$input[$i];
 7961:                  }
 7962:              }
 7963:           }
 7964:        }
 7965:        for (my $i=0;$i<$number;$i++) {
 7966:           if (!$correct[$i]) {
 7967:              $result.='<br /><span class="LC_error">'.
 7968:                       &mt('No correct result given for question "[_1]"!',
 7969:                           $env{'form.question:'.$i}).'</span>';
 7970:           }
 7971:        }
 7972:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 7973:     }
 7974: # Start grading
 7975:     my $pcorrect=$env{'form.pcorrect'};
 7976:     my $pincorrect=$env{'form.pincorrect'};
 7977:     my $storecount=0;
 7978:     foreach my $key (keys(%env)) {
 7979:        my $user='';
 7980:        if ($key=~/^form\.student\:(.*)$/) {
 7981:           $user=$1;
 7982:        }
 7983:        if ($key=~/^form\.unknown\:(.*)$/) {
 7984:           my $id=$1;
 7985:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 7986:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 7987:           } elsif ($env{'form.multi'.$id}) {
 7988:              $user=$env{'form.multi'.$id};
 7989:           }
 7990:        }
 7991:        if ($user) { 
 7992:           my @answer=split(/\,/,$env{$key});
 7993:           my $sum=0;
 7994:           for (my $i=0;$i<$number;$i++) {
 7995:              if ($answer[$i]) {
 7996:                 if ($gradingmechanism eq 'attendance') {
 7997:                    $sum+=$pcorrect;
 7998:                 } else {
 7999:                    if ($answer[$i] eq $correct[$i]) {
 8000:                       $sum+=$pcorrect;
 8001:                    } else {
 8002:                       $sum+=$pincorrect;
 8003:                    }
 8004:                 }
 8005:              }
 8006:           }
 8007:           my $ave=$sum/(100*$number);
 8008: # Store
 8009:           my ($username,$domain)=split(/\:/,$user);
 8010:           my %grades=();
 8011:           $grades{"resource.$part.solved"}='correct_by_override';
 8012:           $grades{"resource.$part.awarded"}=$ave;
 8013:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8014:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8015:                                                  $env{'request.course.id'},
 8016:                                                  $domain,$username);
 8017:           if ($returncode ne 'ok') {
 8018:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8019:           } else {
 8020:              $storecount++;
 8021:           }
 8022:        }
 8023:     }
 8024: # We are done
 8025:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 8026:              '</td></tr></table>'."\n".
 8027:              '</td></tr></table><br /><br />'."\n";
 8028:     return $result.&show_grading_menu_form($symb);
 8029: }
 8030: 
 8031: sub handler {
 8032:     my $request=$_[0];
 8033: 
 8034:     &reset_caches();
 8035:     if ($env{'browser.mathml'}) {
 8036: 	&Apache::loncommon::content_type($request,'text/xml');
 8037:     } else {
 8038: 	&Apache::loncommon::content_type($request,'text/html');
 8039:     }
 8040:     $request->send_http_header;
 8041:     return '' if $request->header_only;
 8042:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8043:     my $symb=&get_symb($request,1);
 8044:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8045:     my $command=$commands[0];
 8046: 
 8047:     if ($#commands > 0) {
 8048: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8049:     }
 8050: 
 8051: 
 8052:     $request->print(&Apache::loncommon::start_page('Grading'));
 8053:     if ($symb eq '' && $command eq '') {
 8054: 	if ($env{'user.adv'}) {
 8055: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8056: 		($env{'form.codethree'})) {
 8057: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8058: 		    $env{'form.codethree'};
 8059: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8060: 		    &Apache::lonnet::checkin($token);
 8061: 		if ($tsymb) {
 8062: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8063: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8064: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
 8065: 					  ('grade_username' => $tuname,
 8066: 					   'grade_domain' => $tudom,
 8067: 					   'grade_courseid' => $tcrsid,
 8068: 					   'grade_symb' => $tsymb)));
 8069: 		    } else {
 8070: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8071: 		    }
 8072: 		} else {
 8073: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8074: 		}
 8075: 	    } else {
 8076: 		$request->print(&Apache::lonxml::tokeninputfield());
 8077: 	    }
 8078: 	}
 8079:     } else {
 8080: 	&init_perm();
 8081: 	if ($command eq 'submission' && $perm{'vgr'}) {
 8082: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 8083: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 8084: 	    &pickStudentPage($request);
 8085: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 8086: 	    &displayPage($request);
 8087: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 8088: 	    &updateGradeByPage($request);
 8089: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 8090: 	    &processGroup($request);
 8091: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 8092: 	    $request->print(&grading_menu($request));
 8093: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 8094: 	    $request->print(&submit_options($request));
 8095: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 8096: 	    $request->print(&viewgrades($request));
 8097: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 8098: 	    $request->print(&processHandGrade($request));
 8099: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 8100: 	    $request->print(&editgrades($request));
 8101: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 8102: 	    $request->print(&verifyreceipt($request));
 8103:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 8104:             $request->print(&process_clicker($request));
 8105:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 8106:             $request->print(&process_clicker_file($request));
 8107:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 8108:             $request->print(&assign_clicker_grades($request));
 8109: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 8110: 	    $request->print(&upcsvScores_form($request));
 8111: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 8112: 	    $request->print(&csvupload($request));
 8113: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 8114: 	    $request->print(&csvuploadmap($request));
 8115: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 8116: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 8117: 		$request->print(&csvuploadoptions($request));
 8118: 	    } else {
 8119: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 8120: 		    $env{'form.upfile_associate'} = 'reverse';
 8121: 		} else {
 8122: 		    $env{'form.upfile_associate'} = 'forward';
 8123: 		}
 8124: 		$request->print(&csvuploadmap($request));
 8125: 	    }
 8126: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 8127: 	    $request->print(&csvuploadassign($request));
 8128: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 8129: 	    &Apache::lonnet::logthis("Selecting pyhase");
 8130: 	    $request->print(&scantron_selectphase($request));
 8131:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 8132:  	    $request->print(&scantron_do_warning($request));
 8133: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 8134: 	    $request->print(&scantron_validate_file($request));
 8135: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 8136: 	    $request->print(&scantron_process_students($request));
 8137:  	} elsif ($command eq 'scantronupload' && 
 8138:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8139: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8140:  	    $request->print(&scantron_upload_scantron_data($request)); 
 8141:  	} elsif ($command eq 'scantronupload_save' &&
 8142:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8143: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8144:  	    $request->print(&scantron_upload_scantron_data_save($request));
 8145:  	} elsif ($command eq 'scantron_download' &&
 8146: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 8147:  	    $request->print(&scantron_download_scantron_data($request));
 8148: 	} elsif ($command) {
 8149: 	    $request->print("Access Denied ($command)");
 8150: 	}
 8151:     }
 8152:     $request->print(&Apache::loncommon::end_page());
 8153:     &reset_caches();
 8154:     return '';
 8155: }
 8156: 
 8157: 1;
 8158: 
 8159: __END__;

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