File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.452: download - view: text, annotated - select for diffs
Thu Oct 11 20:25:34 2007 UTC (16 years, 7 months ago) by banghart
Branches: MAIN
CVS tags: HEAD
	Saving work in progres. Selecting groups to grade seems to work,
	needs more testing.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.452 2007/10/11 20:25:34 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: 	        } elsif (($grp eq 'none') && !$group) {
  535: 	            $exclude = 0;
  536: 	        }
  537: 	    }
  538: 	    if ($exclude) {
  539: 	        delete($classlist->{$student});
  540: 	    }
  541: 	}
  542: 	$section = ($section ne '' ? $section : 'none');
  543: 	if (&canview($section)) {
  544: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  545: 		$sections{$section}++;
  546: 		if ($classlist->{$student}) {
  547: 		    $fullnames{$student}=$fullname;
  548: 		}
  549: 	    } else {
  550: 		delete($classlist->{$student});
  551: 	    }
  552: 	} else {
  553: 	    delete($classlist->{$student});
  554: 	}
  555:     }
  556:     my %seen = ();
  557:     my @sections = sort(keys(%sections));
  558:     return ($classlist,\@sections,\%fullnames);
  559: }
  560: 
  561: sub canmodify {
  562:     my ($sec)=@_;
  563:     if ($perm{'mgr'}) {
  564: 	if (!defined($perm{'mgr_section'})) {
  565: 	    # can modify whole class
  566: 	    return 1;
  567: 	} else {
  568: 	    if ($sec eq $perm{'mgr_section'}) {
  569: 		#can modify the requested section
  570: 		return 1;
  571: 	    } else {
  572: 		# can't modify the request section
  573: 		return 0;
  574: 	    }
  575: 	}
  576:     }
  577:     #can't modify
  578:     return 0;
  579: }
  580: 
  581: sub canview {
  582:     my ($sec)=@_;
  583:     if ($perm{'vgr'}) {
  584: 	if (!defined($perm{'vgr_section'})) {
  585: 	    # can modify whole class
  586: 	    return 1;
  587: 	} else {
  588: 	    if ($sec eq $perm{'vgr_section'}) {
  589: 		#can modify the requested section
  590: 		return 1;
  591: 	    } else {
  592: 		# can't modify the request section
  593: 		return 0;
  594: 	    }
  595: 	}
  596:     }
  597:     #can't modify
  598:     return 0;
  599: }
  600: 
  601: #--- Retrieve the grade status of a student for all the parts
  602: sub student_gradeStatus {
  603:     my ($symb,$udom,$uname,$partlist) = @_;
  604:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  605:     my %partstatus = ();
  606:     foreach (@$partlist) {
  607: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  608: 	$status              = 'nothing' if ($status eq '');
  609: 	$partstatus{$_}      = $status;
  610: 	my $subkey           = "resource.$_.submitted_by";
  611: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  612:     }
  613:     return %partstatus;
  614: }
  615: 
  616: # hidden form and javascript that calls the form
  617: # Use by verifyscript and viewgrades
  618: # Shows a student's view of problem and submission
  619: sub jscriptNform {
  620:     my ($symb) = @_;
  621:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  622:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  623: 	'    function viewOneStudent(user,domain) {'."\n".
  624: 	'	document.onestudent.student.value = user;'."\n".
  625: 	'	document.onestudent.userdom.value = domain;'."\n".
  626: 	'	document.onestudent.submit();'."\n".
  627: 	'    }'."\n".
  628: 	'</script>'."\n";
  629:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  630: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  631: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  632: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  633: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  634: 	'<input type="hidden" name="command" value="submission" />'."\n".
  635: 	'<input type="hidden" name="student" value="" />'."\n".
  636: 	'<input type="hidden" name="userdom" value="" />'."\n".
  637: 	'</form>'."\n";
  638:     return $jscript;
  639: }
  640: 
  641: 
  642: 
  643: # Given the score (as a number [0-1] and the weight) what is the final
  644: # point value? This function will round to the nearest tenth, third,
  645: # or quarter if one of those is within the tolerance of .00001.
  646: sub compute_points {
  647:     my ($score, $weight) = @_;
  648:     
  649:     my $tolerance = .00001;
  650:     my $points = $score * $weight;
  651: 
  652:     # Check for nearness to 1/x.
  653:     my $check_for_nearness = sub {
  654:         my ($factor) = @_;
  655:         my $num = ($points * $factor) + $tolerance;
  656:         my $floored_num = floor($num);
  657:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  658:             return $floored_num / $factor;
  659:         }
  660:         return $points;
  661:     };
  662: 
  663:     $points = $check_for_nearness->(10);
  664:     $points = $check_for_nearness->(3);
  665:     $points = $check_for_nearness->(4);
  666:     
  667:     return $points;
  668: }
  669: 
  670: #------------------ End of general use routines --------------------
  671: 
  672: #
  673: # Find most similar essay
  674: #
  675: 
  676: sub most_similar {
  677:     my ($uname,$udom,$uessay,$old_essays)=@_;
  678: 
  679: # ignore spaces and punctuation
  680: 
  681:     $uessay=~s/\W+/ /gs;
  682: 
  683: # ignore empty submissions (occuring when only files are sent)
  684: 
  685:     unless ($uessay=~/\w+/) { return ''; }
  686: 
  687: # these will be returned. Do not care if not at least 50 percent similar
  688:     my $limit=0.6;
  689:     my $sname='';
  690:     my $sdom='';
  691:     my $scrsid='';
  692:     my $sessay='';
  693: # go through all essays ...
  694:     foreach my $tkey (keys(%$old_essays)) {
  695: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  696: # ... except the same student
  697:         next if (($tname eq $uname) && ($tdom eq $udom));
  698: 	my $tessay=$old_essays->{$tkey};
  699: 	$tessay=~s/\W+/ /gs;
  700: # String similarity gives up if not even limit
  701: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  702: # Found one
  703: 	if ($tsimilar>$limit) {
  704: 	    $limit=$tsimilar;
  705: 	    $sname=$tname;
  706: 	    $sdom=$tdom;
  707: 	    $scrsid=$tcrsid;
  708: 	    $sessay=$old_essays->{$tkey};
  709: 	}
  710:     }
  711:     if ($limit>0.6) {
  712:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  713:     } else {
  714:        return ('','','','',0);
  715:     }
  716: }
  717: 
  718: #-------------------------------------------------------------------
  719: 
  720: #------------------------------------ Receipt Verification Routines
  721: #
  722: #--- Check whether a receipt number is valid.---
  723: sub verifyreceipt {
  724:     my $request  = shift;
  725: 
  726:     my $courseid = $env{'request.course.id'};
  727:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  728: 	$env{'form.receipt'};
  729:     $receipt     =~ s/[^\-\d]//g;
  730:     my ($symb)   = &get_symb($request);
  731: 
  732:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
  733: 	$receipt.'</h3></span>'."\n".
  734: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
  735: 
  736:     my ($string,$contents,$matches) = ('','',0);
  737:     my (undef,undef,$fullname) = &getclasslist('all','0');
  738:     
  739:     my $receiptparts=0;
  740:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  741: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  742:     my $parts=['0'];
  743:     if ($receiptparts) { ($parts)=&response_type($symb); }
  744:     foreach (sort 
  745: 	     {
  746: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  747: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  748: 		 }
  749: 		 return $a cmp $b;
  750: 	     } (keys(%$fullname))) {
  751: 	my ($uname,$udom)=split(/\:/);
  752: 	foreach my $part (@$parts) {
  753: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  754: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
  755: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  756: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  757: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  758: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  759: 		if ($receiptparts) {
  760: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  761: 		}
  762: 		$contents.='</tr>'."\n";
  763: 		
  764: 		$matches++;
  765: 	    }
  766: 	}
  767:     }
  768:     if ($matches == 0) {
  769: 	$string = $title.'No match found for the above receipt.';
  770:     } else {
  771: 	$string = &jscriptNform($symb).$title.
  772: 	    'The above receipt matches the following student'.
  773: 	    ($matches <= 1 ? '.' : 's.')."\n".
  774: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
  775: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
  776: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
  777: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
  778: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
  779: 	if ($receiptparts) {
  780: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
  781: 	}
  782: 	$string.='</tr>'."\n".$contents.
  783: 	    '</table></td></tr></table>'."\n";
  784:     }
  785:     return $string.&show_grading_menu_form($symb);
  786: }
  787: 
  788: #--- This is called by a number of programs.
  789: #--- Called from the Grading Menu - View/Grade an individual student
  790: #--- Also called directly when one clicks on the subm button 
  791: #    on the problem page.
  792: sub listStudents {
  793:     my ($request) = shift;
  794: 
  795:     my ($symb) = &get_symb($request);
  796:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  797:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  798:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  799:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  800:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  801:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  802:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  803: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  804: 
  805:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
  806: 	' Submissions for a Student or a Group of Students</span></h3>';
  807: 
  808:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  809: 
  810:     $request->print(<<LISTJAVASCRIPT);
  811: <script type="text/javascript" language="javascript">
  812:     function checkSelect(checkBox) {
  813: 	var ctr=0;
  814: 	var sense="";
  815: 	if (checkBox.length > 1) {
  816: 	    for (var i=0; i<checkBox.length; i++) {
  817: 		if (checkBox[i].checked) {
  818: 		    ctr++;
  819: 		}
  820: 	    }
  821: 	    sense = "a student or group of students";
  822: 	} else {
  823: 	    if (checkBox.checked) {
  824: 		ctr = 1;
  825: 	    }
  826: 	    sense = "the student";
  827: 	}
  828: 	if (ctr == 0) {
  829: 	    alert("Please select "+sense+" before clicking on the Next button.");
  830: 	    return false;
  831: 	}
  832: 	document.gradesub.submit();
  833:     }
  834: 
  835:     function reLoadList(formname) {
  836: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  837: 	formname.command.value = 'submission';
  838: 	formname.submit();
  839:     }
  840: </script>
  841: LISTJAVASCRIPT
  842: 
  843:     &commonJSfunctions($request);
  844:     $request->print($result);
  845: 
  846:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  847:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  848:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  849: 	"\n".$table.
  850: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
  851: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
  852: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
  853: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
  854: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
  855: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
  856: 	'&nbsp;<b>Submissions: </b>'."\n";
  857:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  858: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
  859:     }
  860:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  861:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  862:     $env{'form.Status'} = $saveStatus;
  863:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
  864: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
  865: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
  866: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
  867:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
  868:         '<option value="1">Whole Points</option>'.
  869:         '<option value=".5">Half Points</option>'.
  870:         '<option value=".25">Quarter Points</option>'.
  871:         '<option value=".1">Tenths of a Point</option>'.
  872:         '</select>'.
  873:         &build_section_inputs().
  874: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  875: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  876: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  877: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  878: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  879: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  880: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  881: 
  882:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  883: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  884:     } else {
  885: 	$gradeTable.='<b>Student Status:</b> '.
  886: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
  887:     }
  888: 
  889:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
  890: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
  891: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  892: 
  893: # checkall buttons
  894:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  895:     $gradeTable.='<input type="button" '."\n".
  896: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  897: 	'value="Next->" /> <br />'."\n";
  898:     $gradeTable.=&check_buttons();
  899:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
  900:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  901:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
  902: 	'<table border="0"><tr bgcolor="#e6ffff">';
  903:     my $loop = 0;
  904:     while ($loop < 2) {
  905: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
  906: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
  907: 	if ($env{'form.showgrading'} eq 'yes' 
  908: 	    && $submitonly ne 'queued'
  909: 	    && $submitonly ne 'all') {
  910: 	    foreach (sort(@$partlist)) {
  911: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
  912: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
  913: 		    ' Status&nbsp;</b></td>';
  914: 	    }
  915: 	} elsif ($submitonly eq 'queued') {
  916: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
  917: 	}
  918: 	$loop++;
  919: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  920:     }
  921:     $gradeTable.='</tr>'."\n";
  922: 
  923:     my $ctr = 0;
  924:     foreach my $student (sort 
  925: 			 {
  926: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  927: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  928: 			     }
  929: 			     return $a cmp $b;
  930: 			 }
  931: 			 (keys(%$fullname))) {
  932: 	my ($uname,$udom) = split(/:/,$student);
  933: 
  934: 	my %status = ();
  935: 
  936: 	if ($submitonly eq 'queued') {
  937: 	    my %queue_status = 
  938: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  939: 							$udom,$uname);
  940: 	    next if (!defined($queue_status{'gradingqueue'}));
  941: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  942: 	}
  943: 
  944: 	if ($env{'form.showgrading'} eq 'yes' 
  945: 	    && $submitonly ne 'queued'
  946: 	    && $submitonly ne 'all') {
  947: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  948: 	    my $submitted = 0;
  949: 	    my $graded = 0;
  950: 	    my $incorrect = 0;
  951: 	    foreach (keys(%status)) {
  952: 		$submitted = 1 if ($status{$_} ne 'nothing');
  953: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  954: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  955: 		
  956: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  957: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  958: 		    $submitted = 0;
  959: 		    my ($part)=split(/\./,$partid);
  960: 		    $gradeTable.='<input type="hidden" name="'.
  961: 			$student.':'.$part.':submitted_by" value="'.
  962: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
  963: 		}
  964: 	    }
  965: 	    
  966: 	    next if (!$submitted && ($submitonly eq 'yes' ||
  967: 				     $submitonly eq 'incorrect' ||
  968: 				     $submitonly eq 'graded'));
  969: 	    next if (!$graded && ($submitonly eq 'graded'));
  970: 	    next if (!$incorrect && $submitonly eq 'incorrect');
  971: 	}
  972: 
  973: 	$ctr++;
  974: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  975:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  976: 	if ( $perm{'vgr'} eq 'F' ) {
  977: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
  978: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
  979:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
  980:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
  981: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
  982: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
  983: 	       '&nbsp;'.$section.'/'.$group.'</td>'."\n";
  984: 
  985: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
  986: 		foreach (sort keys(%status)) {
  987: 		    next if (/^resource.*?submitted_by$/);
  988: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
  989: 		}
  990: 	    }
  991: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
  992: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
  993: 	}
  994:     }
  995:     if ($ctr%2 ==1) {
  996: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
  997: 	    if ($env{'form.showgrading'} eq 'yes' 
  998: 		&& $submitonly ne 'queued'
  999: 		&& $submitonly ne 'all') {
 1000: 		foreach (@$partlist) {
 1001: 		    $gradeTable.='<td>&nbsp;</td>';
 1002: 		}
 1003: 	    } elsif ($submitonly eq 'queued') {
 1004: 		$gradeTable.='<td>&nbsp;</td>';
 1005: 	    }
 1006: 	$gradeTable.='</tr>';
 1007:     }
 1008: 
 1009:     $gradeTable.='</table></td></tr></table>'."\n".
 1010: 	'<input type="button" '.
 1011: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1012: 	'value="Next->" /></form>'."\n";
 1013:     if ($ctr == 0) {
 1014: 	my $num_students=(scalar(keys(%$fullname)));
 1015: 	if ($num_students eq 0) {
 1016: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
 1017: 	} else {
 1018: 	    my $submissions='submissions';
 1019: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1020: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1021: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1022: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1023: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
 1024: 		' students checked for '.$submissions.')</span><br />';
 1025: 	}
 1026:     } elsif ($ctr == 1) {
 1027: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
 1028:     }
 1029:     $gradeTable.=&show_grading_menu_form($symb);
 1030:     $request->print($gradeTable);
 1031:     return '';
 1032: }
 1033: 
 1034: #---- Called from the listStudents routine
 1035: 
 1036: sub check_script {
 1037:     my ($form, $type)=@_;
 1038:     my $chkallscript='<script type="text/javascript">
 1039:     function checkall() {
 1040:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1041:             ele = document.forms.'.$form.'.elements[i];
 1042:             if (ele.name == "'.$type.'") {
 1043:             document.forms.'.$form.'.elements[i].checked=true;
 1044:                                        }
 1045:         }
 1046:     }
 1047: 
 1048:     function checksec() {
 1049:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1050:             ele = document.forms.'.$form.'.elements[i];
 1051:            string = document.forms.'.$form.'.chksec.value;
 1052:            if
 1053:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1054:               document.forms.'.$form.'.elements[i].checked=true;
 1055:             }
 1056:         }
 1057:     }
 1058: 
 1059: 
 1060:     function uncheckall() {
 1061:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1062:             ele = document.forms.'.$form.'.elements[i];
 1063:             if (ele.name == "'.$type.'") {
 1064:             document.forms.'.$form.'.elements[i].checked=false;
 1065:                                        }
 1066:         }
 1067:     }
 1068: 
 1069: </script>'."\n";
 1070:     return $chkallscript;
 1071: }
 1072: 
 1073: sub check_buttons {
 1074:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
 1075:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
 1076:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
 1077:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1078:     return $buttons;
 1079: }
 1080: 
 1081: #     Displays the submissions for one student or a group of students
 1082: sub processGroup {
 1083:     my ($request)  = shift;
 1084:     my $ctr        = 0;
 1085:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1086:     my $total      = scalar(@stuchecked)-1;
 1087: 
 1088:     foreach my $student (@stuchecked) {
 1089: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1090: 	$env{'form.student'}        = $uname;
 1091: 	$env{'form.userdom'}        = $udom;
 1092: 	$env{'form.fullname'}       = $fullname;
 1093: 	&submission($request,$ctr,$total);
 1094: 	$ctr++;
 1095:     }
 1096:     return '';
 1097: }
 1098: 
 1099: #------------------------------------------------------------------------------------
 1100: #
 1101: #-------------------------- Next few routines handles grading by student, essentially
 1102: #                           handles essay response type problem/part
 1103: #
 1104: #--- Javascript to handle the submission page functionality ---
 1105: sub sub_page_js {
 1106:     my $request = shift;
 1107:     $request->print(<<SUBJAVASCRIPT);
 1108: <script type="text/javascript" language="javascript">
 1109:     function updateRadio(formname,id,weight) {
 1110: 	var gradeBox = formname["GD_BOX"+id];
 1111: 	var radioButton = formname["RADVAL"+id];
 1112: 	var oldpts = formname["oldpts"+id].value;
 1113: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1114: 	gradeBox.value = pts;
 1115: 	var resetbox = false;
 1116: 	if (isNaN(pts) || pts < 0) {
 1117: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1118: 	    for (var i=0; i<radioButton.length; i++) {
 1119: 		if (radioButton[i].checked) {
 1120: 		    gradeBox.value = i;
 1121: 		    resetbox = true;
 1122: 		}
 1123: 	    }
 1124: 	    if (!resetbox) {
 1125: 		formtextbox.value = "";
 1126: 	    }
 1127: 	    return;
 1128: 	}
 1129: 
 1130: 	if (pts > weight) {
 1131: 	    var resp = confirm("You entered a value ("+pts+
 1132: 			       ") greater than the weight for the part. Accept?");
 1133: 	    if (resp == false) {
 1134: 		gradeBox.value = oldpts;
 1135: 		return;
 1136: 	    }
 1137: 	}
 1138: 
 1139: 	for (var i=0; i<radioButton.length; i++) {
 1140: 	    radioButton[i].checked=false;
 1141: 	    if (pts == i && pts != "") {
 1142: 		radioButton[i].checked=true;
 1143: 	    }
 1144: 	}
 1145: 	updateSelect(formname,id);
 1146: 	formname["stores"+id].value = "0";
 1147:     }
 1148: 
 1149:     function writeBox(formname,id,pts) {
 1150: 	var gradeBox = formname["GD_BOX"+id];
 1151: 	if (checkSolved(formname,id) == 'update') {
 1152: 	    gradeBox.value = pts;
 1153: 	} else {
 1154: 	    var oldpts = formname["oldpts"+id].value;
 1155: 	    gradeBox.value = oldpts;
 1156: 	    var radioButton = formname["RADVAL"+id];
 1157: 	    for (var i=0; i<radioButton.length; i++) {
 1158: 		radioButton[i].checked=false;
 1159: 		if (i == oldpts) {
 1160: 		    radioButton[i].checked=true;
 1161: 		}
 1162: 	    }
 1163: 	}
 1164: 	formname["stores"+id].value = "0";
 1165: 	updateSelect(formname,id);
 1166: 	return;
 1167:     }
 1168: 
 1169:     function clearRadBox(formname,id) {
 1170: 	if (checkSolved(formname,id) == 'noupdate') {
 1171: 	    updateSelect(formname,id);
 1172: 	    return;
 1173: 	}
 1174: 	gradeSelect = formname["GD_SEL"+id];
 1175: 	for (var i=0; i<gradeSelect.length; i++) {
 1176: 	    if (gradeSelect[i].selected) {
 1177: 		var selectx=i;
 1178: 	    }
 1179: 	}
 1180: 	var stores = formname["stores"+id];
 1181: 	if (selectx == stores.value) { return };
 1182: 	var gradeBox = formname["GD_BOX"+id];
 1183: 	gradeBox.value = "";
 1184: 	var radioButton = formname["RADVAL"+id];
 1185: 	for (var i=0; i<radioButton.length; i++) {
 1186: 	    radioButton[i].checked=false;
 1187: 	}
 1188: 	stores.value = selectx;
 1189:     }
 1190: 
 1191:     function checkSolved(formname,id) {
 1192: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1193: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1194: 	    if (!reply) {return "noupdate";}
 1195: 	    formname.overRideScore.value = 'yes';
 1196: 	}
 1197: 	return "update";
 1198:     }
 1199: 
 1200:     function updateSelect(formname,id) {
 1201: 	formname["GD_SEL"+id][0].selected = true;
 1202: 	return;
 1203:     }
 1204: 
 1205: //=========== Check that a point is assigned for all the parts  ============
 1206:     function checksubmit(formname,val,total,parttot) {
 1207: 	formname.gradeOpt.value = val;
 1208: 	if (val == "Save & Next") {
 1209: 	    for (i=0;i<=total;i++) {
 1210: 		for (j=0;j<parttot;j++) {
 1211: 		    var partid = formname["partid"+i+"_"+j].value;
 1212: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1213: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1214: 			if (points == "") {
 1215: 			    var name = formname["name"+i].value;
 1216: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1217: 			    var resp = confirm("You did not assign a score for "+studentID+
 1218: 					       ", part "+partid+". Continue?");
 1219: 			    if (resp == false) {
 1220: 				formname["GD_BOX"+i+"_"+partid].focus();
 1221: 				return false;
 1222: 			    }
 1223: 			}
 1224: 		    }
 1225: 		    
 1226: 		}
 1227: 	    }
 1228: 	    
 1229: 	}
 1230: 	if (val == "Grade Student") {
 1231: 	    formname.showgrading.value = "yes";
 1232: 	    if (formname.Status.value == "") {
 1233: 		formname.Status.value = "Active";
 1234: 	    }
 1235: 	    formname.studentNo.value = total;
 1236: 	}
 1237: 	formname.submit();
 1238:     }
 1239: 
 1240: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1241:     function checkSubmitPage(formname,total) {
 1242: 	noscore = new Array(100);
 1243: 	var ptr = 0;
 1244: 	for (i=1;i<total;i++) {
 1245: 	    var partid = formname["q_"+i].value;
 1246: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1247: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1248: 		var status = formname["solved"+i+"_"+partid].value;
 1249: 		if (points == "" && status != "correct_by_student") {
 1250: 		    noscore[ptr] = i;
 1251: 		    ptr++;
 1252: 		}
 1253: 	    }
 1254: 	}
 1255: 	if (ptr != 0) {
 1256: 	    var sense = ptr == 1 ? ": " : "s: ";
 1257: 	    var prolist = "";
 1258: 	    if (ptr == 1) {
 1259: 		prolist = noscore[0];
 1260: 	    } else {
 1261: 		var i = 0;
 1262: 		while (i < ptr-1) {
 1263: 		    prolist += noscore[i]+", ";
 1264: 		    i++;
 1265: 		}
 1266: 		prolist += "and "+noscore[i];
 1267: 	    }
 1268: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1269: 	    if (resp == false) {
 1270: 		return false;
 1271: 	    }
 1272: 	}
 1273: 
 1274: 	formname.submit();
 1275:     }
 1276: </script>
 1277: SUBJAVASCRIPT
 1278: }
 1279: 
 1280: #--- javascript for essay type problem --
 1281: sub sub_page_kw_js {
 1282:     my $request = shift;
 1283:     my $iconpath = $request->dir_config('lonIconsURL');
 1284:     &commonJSfunctions($request);
 1285: 
 1286:     my $inner_js_msg_central=<<INNERJS;
 1287:     <script text="text/javascript">
 1288:     function checkInput() {
 1289:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1290:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1291:       var usrctr = document.msgcenter.usrctr.value;
 1292:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1293:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1294: 
 1295:       var msgchk = "";
 1296:       if (document.msgcenter.subchk.checked) {
 1297:          msgchk = "msgsub,";
 1298:       }
 1299:       var includemsg = 0;
 1300:       for (var i=1; i<=nmsg; i++) {
 1301:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1302:           var frmmsg = document.msgcenter["msg"+i];
 1303:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1304:           var showflg = opener.document.SCORE["shownOnce"+i];
 1305:           showflg.value = "1";
 1306:           var chkbox = document.msgcenter["msgn"+i];
 1307:           if (chkbox.checked) {
 1308:              msgchk += "savemsg"+i+",";
 1309:              includemsg = 1;
 1310:           }
 1311:       }
 1312:       if (document.msgcenter.newmsgchk.checked) {
 1313:          msgchk += "newmsg"+usrctr;
 1314:          includemsg = 1;
 1315:       }
 1316:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1317:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1318:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1319:       includemsg.value = msgchk;
 1320: 
 1321:       self.close()
 1322: 
 1323:     }
 1324:     </script>
 1325: INNERJS
 1326: 
 1327:     my $inner_js_highlight_central=<<INNERJS;
 1328:  <script type="text/javascript">
 1329:     function updateChoice(flag) {
 1330:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1331:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1332:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1333:       opener.document.SCORE.refresh.value = "on";
 1334:       if (opener.document.SCORE.keywords.value!=""){
 1335:          opener.document.SCORE.submit();
 1336:       }
 1337:       self.close()
 1338:     }
 1339: </script>
 1340: INNERJS
 1341: 
 1342:     my $start_page_msg_central = 
 1343:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1344: 				       {'js_ready'  => 1,
 1345: 					'only_body' => 1,
 1346: 					'bgcolor'   =>'#FFFFFF',});
 1347:     my $end_page_msg_central = 
 1348: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1349: 
 1350: 
 1351:     my $start_page_highlight_central = 
 1352:         &Apache::loncommon::start_page('Highlight Central',
 1353: 				       $inner_js_highlight_central,
 1354: 				       {'js_ready'  => 1,
 1355: 					'only_body' => 1,
 1356: 					'bgcolor'   =>'#FFFFFF',});
 1357:     my $end_page_highlight_central = 
 1358: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1359: 
 1360:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1361:     $docopen=~s/^document\.//;
 1362:     $request->print(<<SUBJAVASCRIPT);
 1363: <script type="text/javascript" language="javascript">
 1364: 
 1365: //===================== Show list of keywords ====================
 1366:   function keywords(formname) {
 1367:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1368:     if (nret==null) return;
 1369:     formname.keywords.value = nret;
 1370: 
 1371:     if (formname.keywords.value != "") {
 1372: 	formname.refresh.value = "on";
 1373: 	formname.submit();
 1374:     }
 1375:     return;
 1376:   }
 1377: 
 1378: //===================== Script to view submitted by ==================
 1379:   function viewSubmitter(submitter) {
 1380:     document.SCORE.refresh.value = "on";
 1381:     document.SCORE.NCT.value = "1";
 1382:     document.SCORE.unamedom0.value = submitter;
 1383:     document.SCORE.submit();
 1384:     return;
 1385:   }
 1386: 
 1387: //===================== Script to add keyword(s) ==================
 1388:   function getSel() {
 1389:     if (document.getSelection) txt = document.getSelection();
 1390:     else if (document.selection) txt = document.selection.createRange().text;
 1391:     else return;
 1392:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1393:     if (cleantxt=="") {
 1394: 	alert("Please select a word or group of words from document and then click this link.");
 1395: 	return;
 1396:     }
 1397:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1398:     if (nret==null) return;
 1399:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1400:     if (document.SCORE.keywords.value != "") {
 1401: 	document.SCORE.refresh.value = "on";
 1402: 	document.SCORE.submit();
 1403:     }
 1404:     return;
 1405:   }
 1406: 
 1407: //====================== Script for composing message ==============
 1408:    // preload images
 1409:    img1 = new Image();
 1410:    img1.src = "$iconpath/mailbkgrd.gif";
 1411:    img2 = new Image();
 1412:    img2.src = "$iconpath/mailto.gif";
 1413: 
 1414:   function msgCenter(msgform,usrctr,fullname) {
 1415:     var Nmsg  = msgform.savemsgN.value;
 1416:     savedMsgHeader(Nmsg,usrctr,fullname);
 1417:     var subject = msgform.msgsub.value;
 1418:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1419:     re = /msgsub/;
 1420:     var shwsel = "";
 1421:     if (re.test(msgchk)) { shwsel = "checked" }
 1422:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1423:     displaySubject(checkEntities(subject),shwsel);
 1424:     for (var i=1; i<=Nmsg; i++) {
 1425: 	var testmsg = "savemsg"+i+",";
 1426: 	re = new RegExp(testmsg,"g");
 1427: 	shwsel = "";
 1428: 	if (re.test(msgchk)) { shwsel = "checked" }
 1429: 	var message = document.SCORE["savemsg"+i].value;
 1430: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1431: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1432: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1433:     }
 1434:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1435:     shwsel = "";
 1436:     re = /newmsg/;
 1437:     if (re.test(msgchk)) { shwsel = "checked" }
 1438:     newMsg(newmsg,shwsel);
 1439:     msgTail(); 
 1440:     return;
 1441:   }
 1442: 
 1443:   function checkEntities(strx) {
 1444:     if (strx.length == 0) return strx;
 1445:     var orgStr = ["&", "<", ">", '"']; 
 1446:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1447:     var counter = 0;
 1448:     while (counter < 4) {
 1449: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1450: 	counter++;
 1451:     }
 1452:     return strx;
 1453:   }
 1454: 
 1455:   function strReplace(strx, orgStr, newStr) {
 1456:     return strx.split(orgStr).join(newStr);
 1457:   }
 1458: 
 1459:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1460:     var height = 70*Nmsg+250;
 1461:     var scrollbar = "no";
 1462:     if (height > 600) {
 1463: 	height = 600;
 1464: 	scrollbar = "yes";
 1465:     }
 1466:     var xpos = (screen.width-600)/2;
 1467:     xpos = (xpos < 0) ? '0' : xpos;
 1468:     var ypos = (screen.height-height)/2-30;
 1469:     ypos = (ypos < 0) ? '0' : ypos;
 1470: 
 1471:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1472:     pWin.focus();
 1473:     pDoc = pWin.document;
 1474:     pDoc.$docopen;
 1475:     pDoc.write('$start_page_msg_central');
 1476: 
 1477:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1478:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1479:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
 1480: 
 1481:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1482:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1483:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
 1484: }
 1485:     function displaySubject(msg,shwsel) {
 1486:     pDoc = pWin.document;
 1487:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1488:     pDoc.write("<td>Subject</td>");
 1489:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1490:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
 1491: }
 1492: 
 1493:   function displaySavedMsg(ctr,msg,shwsel) {
 1494:     pDoc = pWin.document;
 1495:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1496:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
 1497:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1498:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
 1499: }
 1500: 
 1501:   function newMsg(newmsg,shwsel) {
 1502:     pDoc = pWin.document;
 1503:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1504:     pDoc.write("<td align=\\"center\\">New</td>");
 1505:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1506:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
 1507: }
 1508: 
 1509:   function msgTail() {
 1510:     pDoc = pWin.document;
 1511:     pDoc.write("</table>");
 1512:     pDoc.write("</td></tr></table>&nbsp;");
 1513:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1514:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1515:     pDoc.write("</form>");
 1516:     pDoc.write('$end_page_msg_central');
 1517:     pDoc.close();
 1518: }
 1519: 
 1520: //====================== Script for keyword highlight options ==============
 1521:   function kwhighlight() {
 1522:     var kwclr    = document.SCORE.kwclr.value;
 1523:     var kwsize   = document.SCORE.kwsize.value;
 1524:     var kwstyle  = document.SCORE.kwstyle.value;
 1525:     var redsel = "";
 1526:     var grnsel = "";
 1527:     var blusel = "";
 1528:     if (kwclr=="red")   {var redsel="checked"};
 1529:     if (kwclr=="green") {var grnsel="checked"};
 1530:     if (kwclr=="blue")  {var blusel="checked"};
 1531:     var sznsel = "";
 1532:     var sz1sel = "";
 1533:     var sz2sel = "";
 1534:     if (kwsize=="0")  {var sznsel="checked"};
 1535:     if (kwsize=="+1") {var sz1sel="checked"};
 1536:     if (kwsize=="+2") {var sz2sel="checked"};
 1537:     var synsel = "";
 1538:     var syisel = "";
 1539:     var sybsel = "";
 1540:     if (kwstyle=="")    {var synsel="checked"};
 1541:     if (kwstyle=="<i>") {var syisel="checked"};
 1542:     if (kwstyle=="<b>") {var sybsel="checked"};
 1543:     highlightCentral();
 1544:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1545:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1546:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1547:     highlightend();
 1548:     return;
 1549:   }
 1550: 
 1551:   function highlightCentral() {
 1552: //    if (window.hwdWin) window.hwdWin.close();
 1553:     var xpos = (screen.width-400)/2;
 1554:     xpos = (xpos < 0) ? '0' : xpos;
 1555:     var ypos = (screen.height-330)/2-30;
 1556:     ypos = (ypos < 0) ? '0' : ypos;
 1557: 
 1558:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1559:     hwdWin.focus();
 1560:     var hDoc = hwdWin.document;
 1561:     hDoc.$docopen;
 1562:     hDoc.write('$start_page_highlight_central');
 1563:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1564:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
 1565: 
 1566:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1567:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1568:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
 1569:   }
 1570: 
 1571:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1572:     var hDoc = hwdWin.document;
 1573:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1574:     hDoc.write("<td align=\\"left\\">");
 1575:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
 1576:     hDoc.write("<td align=\\"left\\">");
 1577:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
 1578:     hDoc.write("<td align=\\"left\\">");
 1579:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
 1580:     hDoc.write("</tr>");
 1581:   }
 1582: 
 1583:   function highlightend() { 
 1584:     var hDoc = hwdWin.document;
 1585:     hDoc.write("</table>");
 1586:     hDoc.write("</td></tr></table>&nbsp;");
 1587:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1588:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1589:     hDoc.write("</form>");
 1590:     hDoc.write('$end_page_highlight_central');
 1591:     hDoc.close();
 1592:   }
 1593: 
 1594: </script>
 1595: SUBJAVASCRIPT
 1596: }
 1597: 
 1598: sub get_increment {
 1599:     my $increment = $env{'form.increment'};
 1600:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1601:         $increment != .1) {
 1602:         $increment = 1;
 1603:     }
 1604:     return $increment;
 1605: }
 1606: 
 1607: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1608: sub gradeBox {
 1609:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1610:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1611: 	'" src="'.$request->dir_config('lonIconsURL').
 1612: 	'/check.gif" height="16" border="0" />';
 1613:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1614:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
 1615: 		  '<span class="LC_info">problem weight assigned by computer</span>');
 1616:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1617:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1618: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1619:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1620:     my $display_part=&get_display_part($partid,$symb);
 1621:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1622: 				       [$partid]);
 1623:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1624:     if ($last_resets{$partid}) {
 1625:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1626:     }
 1627:     $result.='<table border="0"><tr><td>'.
 1628: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
 1629:     my $ctr = 0;
 1630:     my $thisweight = 0;
 1631:     my $increment = &get_increment();
 1632:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1633:     while ($thisweight<=$wgt) {
 1634: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1635: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1636: 	    $thisweight.')" value="'.$thisweight.'" '.
 1637: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1638: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1639:         $thisweight += $increment;
 1640: 	$ctr++;
 1641:     }
 1642:     $result.='</tr></table>';
 1643:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
 1644:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1645: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1646: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1647: 	$wgt.')" /></td>'."\n";
 1648:     $result.='<td>/'.$wgt.' '.$wgtmsg.
 1649: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1650: 	' </td><td>'."\n";
 1651:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1652: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1653:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1654: 	$result.='<option></option>'.
 1655: 	    '<option selected="selected">excused</option>';
 1656:     } else {
 1657: 	$result.='<option selected="selected"></option>'.
 1658: 	    '<option>excused</option>';
 1659:     }
 1660:     $result.='<option>reset status</option></select>'."\n";
 1661:     $result.="&nbsp;&nbsp;\n";
 1662:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1663: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1664: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1665: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1666:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1667:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1668:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1669:         $aggtries.'" />'."\n";
 1670:     $result.='</td></tr></table>'."\n";
 1671:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1672:     return $result;
 1673: }
 1674: 
 1675: sub handback_box {
 1676:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1677:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1678:     my (@respids);
 1679:      my @part_response_id = &flatten_responseType($responseType);
 1680:     foreach my $part_response_id (@part_response_id) {
 1681:     	my ($part,$resp) = @{ $part_response_id };
 1682:         if ($part eq $partid) {
 1683:             push(@respids,$resp);
 1684:         }
 1685:     }
 1686:     my $result;
 1687:     foreach my $respid (@respids) {
 1688: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1689: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1690: 	next if (!@$files);
 1691: 	my $file_counter = 1;
 1692: 	foreach my $file (@$files) {
 1693: 	    if ($file =~ /\/portfolio\//) {
 1694:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1695:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1696:     	        $file_disp = "$name.$ext";
 1697:     	        $file = $file_path.$file_disp;
 1698:     	        $result.=&mt('Return commented version of [_1] to student.',
 1699:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1700:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1701:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1702:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
 1703:     	        $file_counter++;
 1704: 	    }
 1705: 	}
 1706:     }
 1707:     return $result;    
 1708: }
 1709: 
 1710: sub show_problem {
 1711:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1712:     my $rendered;
 1713:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1714:     &Apache::lonxml::remember_problem_counter();
 1715:     if ($mode eq 'both' or $mode eq 'text') {
 1716: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1717: 						       $env{'request.course.id'},
 1718: 						       undef,\%form);
 1719:     }
 1720:     if ($removeform) {
 1721: 	$rendered=~s|<form(.*?)>||g;
 1722: 	$rendered=~s|</form>||g;
 1723: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1724:     }
 1725:     my $companswer;
 1726:     if ($mode eq 'both' or $mode eq 'answer') {
 1727: 	&Apache::lonxml::restore_problem_counter();
 1728: 	$companswer=
 1729: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1730: 						    $env{'request.course.id'},
 1731: 						    %form);
 1732:     }
 1733:     if ($removeform) {
 1734: 	$companswer=~s|<form(.*?)>||g;
 1735: 	$companswer=~s|</form>||g;
 1736: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1737:     }
 1738:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 1739:     $result.='<table border="0" width="100%">';
 1740:     if ($viewon) {
 1741: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
 1742: 	if ($mode eq 'both' or $mode eq 'text') {
 1743: 	    $result.='View of the problem - ';
 1744: 	} else {
 1745: 	    $result.='Correct answer: ';
 1746: 	}
 1747: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
 1748:     }
 1749:     if ($mode eq 'both') {
 1750: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
 1751: 	$result.='<b>Correct answer:</b><br />'.$companswer;
 1752:     } elsif ($mode eq 'text') {
 1753: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
 1754:     } elsif ($mode eq 'answer') {
 1755: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
 1756:     }
 1757:     $result.='</td></tr></table>';
 1758:     $result.='</td></tr></table><br />';
 1759:     return $result;
 1760: }
 1761: 
 1762: sub files_exist {
 1763:     my ($r, $symb) = @_;
 1764:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1765: 
 1766:     foreach my $student (@students) {
 1767:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1768:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1769: 					      $udom,$uname);
 1770:         my ($string,$timestamp)= &get_last_submission(\%record);
 1771:         foreach my $submission (@$string) {
 1772:             my ($partid,$respid) =
 1773: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1774:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1775: 					   \%record);
 1776:             return 1 if (@$files);
 1777:         }
 1778:     }
 1779:     return 0;
 1780: }
 1781: 
 1782: sub download_all_link {
 1783:     my ($r,$symb) = @_;
 1784:     my $all_students = 
 1785: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1786: 
 1787:     my $parts =
 1788: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1789: 
 1790:     my $identifier = &Apache::loncommon::get_cgi_id();
 1791:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
 1792:                             'cgi.'.$identifier.'.symb' => $symb,
 1793:                             'cgi.'.$identifier.'.parts' => $parts,);
 1794:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1795: 	      &mt('Download All Submitted Documents').'</a>');
 1796:     return
 1797: }
 1798: 
 1799: sub build_section_inputs {
 1800:     my $section_inputs;
 1801:     if ($env{'form.section'} eq '') {
 1802:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1803:     } else {
 1804:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1805:         foreach my $section (@sections) {
 1806:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1807:         }
 1808:     }
 1809:     return $section_inputs;
 1810: }
 1811: 
 1812: # --------------------------- show submissions of a student, option to grade 
 1813: sub submission {
 1814:     my ($request,$counter,$total) = @_;
 1815:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1816:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1817:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1818:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1819:     my $symb = &get_symb($request); 
 1820:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1821: 
 1822:     if (!&canview($usec)) {
 1823: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1824: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1825: 			$env{'request.course.id'}.')</span>');
 1826: 	$request->print(&show_grading_menu_form($symb));
 1827: 	return;
 1828:     }
 1829: 
 1830:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1831:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1832:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1833:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1834:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1835: 	'" src="'.$request->dir_config('lonIconsURL').
 1836: 	'/check.gif" height="16" border="0" />';
 1837: 
 1838:     my %old_essays;
 1839:     # header info
 1840:     if ($counter == 0) {
 1841: 	&sub_page_js($request);
 1842: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1843: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1844: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1845: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1846: 	    &download_all_link($request, $symb);
 1847: 	}
 1848: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
 1849: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
 1850: 
 1851: 	if ($env{'form.handgrade'} eq 'no') {
 1852: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
 1853: 		$checkIcon.' symbol.'."\n";
 1854: 	    $request->print($checkMark);
 1855: 	}
 1856: 
 1857: 	# option to display problem, only once else it cause problems 
 1858:         # with the form later since the problem has a form.
 1859: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1860: 	    my $mode;
 1861: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1862: 		$mode='both';
 1863: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1864: 		$mode='text';
 1865: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1866: 		$mode='answer';
 1867: 	    }
 1868: 	    &Apache::lonxml::clear_problem_counter();
 1869: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1870: 	}
 1871: 
 1872: 	# kwclr is the only variable that is guaranteed to be non blank 
 1873:         # if this subroutine has been called once.
 1874: 	my %keyhash = ();
 1875: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1876: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1877: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1878: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1879: 
 1880: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1881: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1882: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1883: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1884: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1885: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1886: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1887: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1888: 	}
 1889: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1890: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1891: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1892: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1893: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1894: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1895: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1896: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1897: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1898: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1899: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1900: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1901: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1902: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1903: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1904: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1905: 			&build_section_inputs().
 1906: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1907: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1908: 			'<input type="hidden" name="NCT"'.
 1909: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1910: 	if ($env{'form.handgrade'} eq 'yes') {
 1911: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1912: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1913: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1914: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1915: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1916: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1917: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1918: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1919: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1920: 	    }
 1921: 	}
 1922: 	
 1923: 	my ($cts,$prnmsg) = (1,'');
 1924: 	while ($cts <= $env{'form.savemsgN'}) {
 1925: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1926: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1927: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1928: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1929: 		'" />'."\n".
 1930: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1931: 	    $cts++;
 1932: 	}
 1933: 	$request->print($prnmsg);
 1934: 
 1935: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1936: #
 1937: # Print out the keyword options line
 1938: #
 1939: 	    $request->print(<<KEYWORDS);
 1940: &nbsp;<b>Keyword Options:</b>&nbsp;
 1941: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1942: <a href="#" onMouseDown="javascript:getSel(); return false"
 1943:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1944: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1945: KEYWORDS
 1946: #
 1947: # Load the other essays for similarity check
 1948: #
 1949:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1950: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1951: 	    $apath=&escape($apath);
 1952: 	    $apath=~s/\W/\_/gs;
 1953: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 1954:         }
 1955:     }
 1956: 
 1957: # This is where output for one specific student would start
 1958:     my $bgcolor='#DDEEDD';
 1959:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
 1960:     $request->print("\n\n".
 1961:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
 1962: 
 1963:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 1964: 	my $mode;
 1965: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 1966: 	    $mode='both';
 1967: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 1968: 	    $mode='text';
 1969: 	} elsif ($env{'form.vAns'} eq 'all') {
 1970: 	    $mode='answer';
 1971: 	}
 1972: 	&Apache::lonxml::clear_problem_counter();
 1973: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
 1974:     }
 1975: 
 1976:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 1977:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1978: 
 1979:     # Display student info
 1980:     $request->print(($counter == 0 ? '' : '<br />'));
 1981:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
 1982: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
 1983: 
 1984:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
 1985:     $result.='<input type="hidden" name="name'.$counter.
 1986: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 1987: 
 1988:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 1989:     my @col_fullnames;
 1990:     my ($classlist,$fullname);
 1991:     if ($env{'form.handgrade'} eq 'yes') {
 1992: 	($classlist,undef,$fullname) = &getclasslist('all','0');
 1993: 	for (keys (%$handgrade)) {
 1994: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
 1995: 					    '.maxcollaborators',
 1996:                                             $symb,$udom,$uname);
 1997: 	    next if ($ncol <= 0);
 1998:             s/\_/\./g;
 1999:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
 2000:             my @goodcollaborators = ();
 2001:             my @badcollaborators  = ();
 2002: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
 2003: 		$_ =~ s/[\$\^\(\)]//g;
 2004: 		next if ($_ eq '');
 2005: 		my ($co_name,$co_dom) = split /\@|:/,$_;
 2006: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2007: 		next if ($co_name eq $uname && $co_dom eq $udom);
 2008: 		# Doing this grep allows 'fuzzy' specification
 2009: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
 2010: 		if (! scalar(@Matches)) {
 2011: 		    push @badcollaborators,$_;
 2012: 		} else {
 2013: 		    push @goodcollaborators, @Matches;
 2014: 		}
 2015: 	    }
 2016:             if (scalar(@goodcollaborators) != 0) {
 2017:                 $result.='<b>Collaborators: </b>';
 2018:                 foreach (@goodcollaborators) {
 2019: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
 2020: 		    push @col_fullnames, $givenn.' '.$lastname;
 2021: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
 2022: 		}
 2023:                 $result.='<br />'."\n";
 2024: 		my ($part)=split(/\./,$_);
 2025: 		$result.='<input type="hidden" name="collaborator'.$counter.
 2026: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
 2027: 		    "\n";
 2028: 	    }
 2029: 	    if (scalar(@badcollaborators) > 0) {
 2030: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
 2031: 		$result.='This student has submitted ';
 2032: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
 2033: 		$result .= ': '.join(', ',@badcollaborators);
 2034: 		$result .= '</td></tr></table>';
 2035: 	    }         
 2036: 	    if (scalar(@badcollaborators > $ncol)) {
 2037: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
 2038: 		$result .= 'This student has submitted too many '.
 2039: 		    'collaborators.  Maximum is '.$ncol.'.';
 2040: 		$result .= '</td></tr></table>';
 2041: 	    }
 2042: 	}
 2043:     }
 2044:     $request->print($result."\n");
 2045: 
 2046:     # print student answer/submission
 2047:     # Options are (1) Handgaded submission only
 2048:     #             (2) Last submission, includes submission that is not handgraded 
 2049:     #                  (for multi-response type part)
 2050:     #             (3) Last submission plus the parts info
 2051:     #             (4) The whole record for this student
 2052:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2053: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2054: 	my $lastsubonly=''.
 2055: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
 2056: 	     $$timestamp)."</td></tr>\n";
 2057: 	if ($$timestamp eq '') {
 2058: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
 2059: 	} else {
 2060: 	    my %seenparts;
 2061: 	    my @part_response_id = &flatten_responseType($responseType);
 2062: 	    foreach my $part (@part_response_id) {
 2063: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2064: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2065: 
 2066: 		my ($partid,$respid) = @{ $part };
 2067: 		my $display_part=&get_display_part($partid,$symb);
 2068: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2069: 		    if (exists($seenparts{$partid})) { next; }
 2070: 		    $seenparts{$partid}=1;
 2071: 		    my $submitby='<b>Part:</b> '.$display_part.
 2072: 			' <b>Collaborative submission by:</b> '.
 2073: 			'<a href="javascript:viewSubmitter(\''.
 2074: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2075: 			'\');" target="_self">'.
 2076: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2077: 		    $request->print($submitby);
 2078: 		    next;
 2079: 		}
 2080: 		my $responsetype = $responseType->{$partid}->{$respid};
 2081: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2082: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
 2083: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2084: 			' )</span>&nbsp; &nbsp;'.
 2085: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
 2086: 		    next;
 2087: 		}
 2088: 		foreach (@$string) {
 2089: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
 2090: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2091: 		    my ($ressub,$subval) = split(/:/,$_,2);
 2092: 		    # Similarity check
 2093: 		    my $similar='';
 2094: 		    if($env{'form.checkPlag'}){
 2095: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2096: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2097: 			if ($osim) {
 2098: 			    $osim=int($osim*100.0);
 2099: 			    my %old_course_desc = 
 2100: 				&Apache::lonnet::coursedescription($ocrsid,
 2101: 								   {'one_time' => 1});
 2102: 
 2103: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2104: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2105: 				    $osim,
 2106: 				    &Apache::loncommon::plainname($oname,$odom),
 2107: 				    $oname,$odom,
 2108: 				    $old_course_desc{'description'},
 2109: 				    $old_course_desc{'num'},
 2110: 				    $old_course_desc{'domain'}).
 2111: 				'</span></h3><blockquote><i>'.
 2112: 				&keywords_highlight($oessay).
 2113: 				'</i></blockquote><hr />';
 2114: 			}
 2115: 		    }
 2116: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2117: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2118: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2119: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2120: 			my $display_part=&get_display_part($partid,$symb);
 2121: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
 2122: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2123: 			    ' )</span>&nbsp; &nbsp;';
 2124: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2125: 			if (@$files) {
 2126: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
 2127: 			    my $file_counter = 0;
 2128: 			    foreach my $file (@$files) {
 2129: 			        $file_counter ++;
 2130: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2131: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2132: 			    }
 2133: 			    $lastsubonly.='<br />';
 2134: 			}
 2135: 			$lastsubonly.='<b>Submitted Answer: </b>'.
 2136: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2137: 					 $respid,\%record,$order);
 2138: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2139: 		    }
 2140: 		}
 2141: 	    }
 2142: 	}
 2143: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
 2144: 	$request->print($lastsubonly);
 2145:     } elsif ($env{'form.lastSub'} eq 'datesub') {
 2146: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2147: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2148:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2149: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2150: 								 $env{'request.course.id'},
 2151: 								 $last,'.submission',
 2152: 								 'Apache::grades::keywords_highlight'));
 2153:     }
 2154: 
 2155:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2156: 	.$udom.'" />'."\n");
 2157:     
 2158:     # return if view submission with no grading option
 2159:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2160: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2161: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2162: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2163: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
 2164: 	if (($env{'form.command'} eq 'submission') || 
 2165: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2166: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2167: 	}
 2168: 	$request->print($toGrade);
 2169: 	return;
 2170:     } else {
 2171: 	$request->print('</td></tr></table></td></tr></table>'."\n");
 2172:     }
 2173: 
 2174:     # essay grading message center
 2175:     if ($env{'form.handgrade'} eq 'yes') {
 2176: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2177: 	my $msgfor = $givenn.' '.$lastname;
 2178: 	if (scalar(@col_fullnames) > 0) {
 2179: 	    my $lastone = pop @col_fullnames;
 2180: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
 2181: 	}
 2182: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2183: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2184: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2185: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2186: 	    ',\''.$msgfor.'\');" target="_self">'.
 2187: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2188: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2189: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2190: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2191: 	    '<br />&nbsp;('.
 2192: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
 2193: 	$request->print($result);
 2194:     }
 2195:     if ($perm{'vgr'}) {
 2196: 	$request->print('<br />'.
 2197: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2198: 						   $uname,$udom,'check'));
 2199:     }
 2200:     if ($perm{'opa'}) {
 2201: 	$request->print('<br />'.
 2202: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2203: 					 $uname,$udom,$symb,'check'));
 2204:     }
 2205: 
 2206:     my %seen = ();
 2207:     my @partlist;
 2208:     my @gradePartRespid;
 2209:     my @part_response_id = &flatten_responseType($responseType);
 2210:     foreach my $part_response_id (@part_response_id) {
 2211:     	my ($partid,$respid) = @{ $part_response_id };
 2212: 	my $part_resp = join('_',@{ $part_response_id });
 2213: 	next if ($seen{$partid} > 0);
 2214: 	$seen{$partid}++;
 2215: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2216: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2217: 	push @partlist,$partid;
 2218: 	push @gradePartRespid,$partid.'.'.$respid;
 2219: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2220:     }
 2221:     $result='<input type="hidden" name="partlist'.$counter.
 2222: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2223:     $result.='<input type="hidden" name="gradePartRespid'.
 2224: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2225:     my $ctr = 0;
 2226:     while ($ctr < scalar(@partlist)) {
 2227: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2228: 	    $partlist[$ctr].'" />'."\n";
 2229: 	$ctr++;
 2230:     }
 2231:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
 2232: 
 2233: # Done with printing info for one student
 2234: 
 2235:     $request->print('</td></tr></table></p>');
 2236: 
 2237: 
 2238:     # print end of form
 2239:     if ($counter == $total) {
 2240: 	my $endform='<table border="0"><tr><td>'."\n";
 2241: 	$endform.='<input type="button" value="Save & Next" '.
 2242: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2243: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2244: 	my $ntstu ='<select name="NTSTU">'.
 2245: 	    '<option>1</option><option>2</option>'.
 2246: 	    '<option>3</option><option>5</option>'.
 2247: 	    '<option>7</option><option>10</option></select>'."\n";
 2248: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2249: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2250: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
 2251: 	$endform.='<input type="button" value="Previous" '.
 2252: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2253: 	    '<input type="button" value="Next" '.
 2254: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2255: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
 2256:         $endform.="<input type='hidden' value='".&get_increment().
 2257:             "' name='increment' />";
 2258: 	$endform.='</td><tr></table></form>';
 2259: 	$endform.=&show_grading_menu_form($symb);
 2260: 	$request->print($endform);
 2261:     }
 2262:     return '';
 2263: }
 2264: 
 2265: #--- Retrieve the last submission for all the parts
 2266: sub get_last_submission {
 2267:     my ($returnhash)=@_;
 2268:     my (@string,$timestamp);
 2269:     if ($$returnhash{'version'}) {
 2270: 	my %lasthash=();
 2271: 	my ($version);
 2272: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2273: 	    foreach my $key (sort(split(/\:/,
 2274: 					$$returnhash{$version.':keys'}))) {
 2275: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2276: 		$timestamp = 
 2277: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
 2278: 	    }
 2279: 	}
 2280: 	foreach my $key (keys(%lasthash)) {
 2281: 	    next if ($key !~ /\.submission$/);
 2282: 
 2283: 	    my ($partid,$foo) = split(/submission$/,$key);
 2284: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2285: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2286: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2287: 	}
 2288:     }
 2289:     if (!@string) {
 2290: 	$string[0] =
 2291: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2292:     }
 2293:     return (\@string,\$timestamp);
 2294: }
 2295: 
 2296: #--- High light keywords, with style choosen by user.
 2297: sub keywords_highlight {
 2298:     my $string    = shift;
 2299:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2300:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2301:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2302:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2303:     foreach my $keyword (@keylist) {
 2304: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2305:     }
 2306:     return $string;
 2307: }
 2308: 
 2309: #--- Called from submission routine
 2310: sub processHandGrade {
 2311:     my ($request) = shift;
 2312:     my $symb   = &get_symb($request);
 2313:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2314:     my $button = $env{'form.gradeOpt'};
 2315:     my $ngrade = $env{'form.NCT'};
 2316:     my $ntstu  = $env{'form.NTSTU'};
 2317:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2318:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2319: 
 2320:     if ($button eq 'Save & Next') {
 2321: 	my $ctr = 0;
 2322: 	while ($ctr < $ngrade) {
 2323: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2324: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2325: 	    if ($errorflag eq 'no_score') {
 2326: 		$ctr++;
 2327: 		next;
 2328: 	    }
 2329: 	    if ($errorflag eq 'not_allowed') {
 2330: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2331: 		$ctr++;
 2332: 		next;
 2333: 	    }
 2334: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2335: 	    my ($subject,$message,$msgstatus) = ('','','');
 2336: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2337:             my ($feedurl,$showsymb) =
 2338: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2339: 	    my $messagetail;
 2340: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2341: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2342: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2343: 		$subject.=' ['.$restitle.']';
 2344: 		my (@msgnum) = split(/,/,$includemsg);
 2345: 		foreach (@msgnum) {
 2346: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2347: 		}
 2348: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2349: 		if ($env{'form.withgrades'.$ctr}) {
 2350: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2351: 		    $messagetail = " for <a href=\"".
 2352: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2353: 		}
 2354: 		$msgstatus = 
 2355:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2356: 						     $message.$messagetail,
 2357:                                                      undef,$feedurl,undef,
 2358:                                                      undef,undef,$showsymb,
 2359:                                                      $restitle);
 2360: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2361: 				$msgstatus);
 2362: 	    }
 2363: 	    if ($env{'form.collaborator'.$ctr}) {
 2364: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2365: 		foreach my $collabstr (@collabstrs) {
 2366: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2367: 		    foreach my $collaborator (@collaborators) {
 2368: 			my ($errorflag,$pts,$wgt) = 
 2369: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2370: 					   $env{'form.unamedom'.$ctr},$part);
 2371: 			if ($errorflag eq 'not_allowed') {
 2372: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2373: 			    next;
 2374: 			} elsif ($message ne '') {
 2375: 			    my ($baseurl,$showsymb) = 
 2376: 				&get_feedurl_and_symb($symb,$collaborator,
 2377: 						      $udom);
 2378: 			    if ($env{'form.withgrades'.$ctr}) {
 2379: 				$messagetail = " for <a href=\"".
 2380:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2381: 			    }
 2382: 			    $msgstatus = 
 2383: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2384: 			}
 2385: 		    }
 2386: 		}
 2387: 	    }
 2388: 	    $ctr++;
 2389: 	}
 2390:     }
 2391: 
 2392:     if ($env{'form.handgrade'} eq 'yes') {
 2393: 	# Keywords sorted in alphabatical order
 2394: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2395: 	my %keyhash = ();
 2396: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2397: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2398: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2399: 	$env{'form.keywords'} = join(' ',@keywords);
 2400: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2401: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2402: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2403: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2404: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2405: 
 2406: 	# message center - Order of message gets changed. Blank line is eliminated.
 2407: 	# New messages are saved in env for the next student.
 2408: 	# All messages are saved in nohist_handgrade.db
 2409: 	my ($ctr,$idx) = (1,1);
 2410: 	while ($ctr <= $env{'form.savemsgN'}) {
 2411: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2412: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2413: 		$idx++;
 2414: 	    }
 2415: 	    $ctr++;
 2416: 	}
 2417: 	$ctr = 0;
 2418: 	while ($ctr < $ngrade) {
 2419: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2420: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2421: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2422: 		$idx++;
 2423: 	    }
 2424: 	    $ctr++;
 2425: 	}
 2426: 	$env{'form.savemsgN'} = --$idx;
 2427: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2428: 	my $putresult = &Apache::lonnet::put
 2429: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2430:     }
 2431:     # Called by Save & Refresh from Highlight Attribute Window
 2432:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2433:     if ($env{'form.refresh'} eq 'on') {
 2434: 	my ($ctr,$total) = (0,0);
 2435: 	while ($ctr < $ngrade) {
 2436: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2437: 	    $ctr++;
 2438: 	}
 2439: 	$env{'form.NTSTU'}=$ngrade;
 2440: 	$ctr = 0;
 2441: 	while ($ctr < $total) {
 2442: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2443: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2444: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2445: 	    &submission($request,$ctr,$total-1);
 2446: 	    $ctr++;
 2447: 	}
 2448: 	return '';
 2449:     }
 2450: 
 2451: # Go directly to grade student - from submission or link from chart page
 2452:     if ($button eq 'Grade Student') {
 2453: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2454: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2455: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2456: 	$env{'form.fullname'} = $$fullname{$processUser};
 2457: 	&submission($request,0,0);
 2458: 	return '';
 2459:     }
 2460: 
 2461:     # Get the next/previous one or group of students
 2462:     my $firststu = $env{'form.unamedom0'};
 2463:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2464:     my $ctr = 2;
 2465:     while ($laststu eq '') {
 2466: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2467: 	$ctr++;
 2468: 	$laststu = $firststu if ($ctr > $ngrade);
 2469:     }
 2470: 
 2471:     my (@parsedlist,@nextlist);
 2472:     my ($nextflg) = 0;
 2473:     foreach (sort 
 2474: 	     {
 2475: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2476: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2477: 		 }
 2478: 		 return $a cmp $b;
 2479: 	     } (keys(%$fullname))) {
 2480: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2481: 	    push @parsedlist,$_;
 2482: 	}
 2483: 	$nextflg = 1 if ($_ eq $laststu);
 2484: 	if ($button eq 'Previous') {
 2485: 	    last if ($_ eq $firststu);
 2486: 	    push @parsedlist,$_;
 2487: 	}
 2488:     }
 2489:     $ctr = 0;
 2490:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2491:     my ($partlist) = &response_type($symb);
 2492:     foreach my $student (@parsedlist) {
 2493: 	my $submitonly=$env{'form.submitonly'};
 2494: 	my ($uname,$udom) = split(/:/,$student);
 2495: 	
 2496: 	if ($submitonly eq 'queued') {
 2497: 	    my %queue_status = 
 2498: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2499: 							$udom,$uname);
 2500: 	    next if (!defined($queue_status{'gradingqueue'}));
 2501: 	}
 2502: 
 2503: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2504: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2505: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2506: 	    my $submitted = 0;
 2507: 	    my $ungraded = 0;
 2508: 	    my $incorrect = 0;
 2509: 	    foreach (keys(%status)) {
 2510: 		$submitted = 1 if ($status{$_} ne 'nothing');
 2511: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
 2512: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 2513: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 2514: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2515: 		    $submitted = 0;
 2516: 		}
 2517: 	    }
 2518: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2519: 				     $submitonly eq 'incorrect' ||
 2520: 				     $submitonly eq 'graded'));
 2521: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2522: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2523: 	}
 2524: 	push @nextlist,$student if ($ctr < $ntstu);
 2525: 	last if ($ctr == $ntstu);
 2526: 	$ctr++;
 2527:     }
 2528: 
 2529:     $ctr = 0;
 2530:     my $total = scalar(@nextlist)-1;
 2531: 
 2532:     foreach (sort @nextlist) {
 2533: 	my ($uname,$udom,$submitter) = split(/:/);
 2534: 	$env{'form.student'}  = $uname;
 2535: 	$env{'form.userdom'}  = $udom;
 2536: 	$env{'form.fullname'} = $$fullname{$_};
 2537: 	&submission($request,$ctr,$total);
 2538: 	$ctr++;
 2539:     }
 2540:     if ($total < 0) {
 2541: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
 2542: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
 2543: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
 2544: 	$the_end.=&show_grading_menu_form($symb);
 2545: 	$request->print($the_end);
 2546:     }
 2547:     return '';
 2548: }
 2549: 
 2550: #---- Save the score and award for each student, if changed
 2551: sub saveHandGrade {
 2552:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2553:     my @version_parts;
 2554:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2555: 					   $env{'request.course.id'});
 2556:     if (!&canmodify($usec)) { return('not_allowed'); }
 2557:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2558:     my @parts_graded;
 2559:     my %newrecord  = ();
 2560:     my ($pts,$wgt) = ('','');
 2561:     my %aggregate = ();
 2562:     my $aggregateflag = 0;
 2563:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2564:     foreach my $new_part (@parts) {
 2565: 	#collaborator ($submi may vary for different parts
 2566: 	if ($submitter && $new_part ne $part) { next; }
 2567: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2568: 	if ($dropMenu eq 'excused') {
 2569: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2570: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2571: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2572: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2573: 		}
 2574: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2575: 	    }
 2576: 	} elsif ($dropMenu eq 'reset status'
 2577: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2578: 	    foreach my $key (keys (%record)) {
 2579: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2580: 	    }
 2581: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2582: 		"$env{'user.name'}:$env{'user.domain'}";
 2583:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2584: 
 2585:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2586: 					       [$new_part]);
 2587:             my $aggtries =$totaltries;
 2588:             if ($last_resets{$new_part}) {
 2589:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2590: 					   $new_part);
 2591:             }
 2592: 
 2593:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2594:             if ($aggtries > 0) {
 2595:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2596:                 $aggregateflag = 1;
 2597:             }
 2598: 	} elsif ($dropMenu eq '') {
 2599: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2600: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2601: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2602: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2603: 		next;
 2604: 	    }
 2605: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2606: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2607: 	    my $partial= $pts/$wgt;
 2608: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2609: 		#do not update score for part if not changed.
 2610:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2611: 		next;
 2612: 	    } else {
 2613: 	        push @parts_graded, $new_part;
 2614: 	    }
 2615: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2616: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2617: 	    }
 2618: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2619: 	    if ($partial == 0) {
 2620: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2621: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2622: 		}
 2623: 	    } else {
 2624: 		if ($record{$reckey} ne 'correct_by_override') {
 2625: 		    $newrecord{$reckey} = 'correct_by_override';
 2626: 		}
 2627: 	    }	    
 2628: 	    if ($submitter && 
 2629: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2630: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2631: 	    }
 2632: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2633: 		"$env{'user.name'}:$env{'user.domain'}";
 2634: 	}
 2635: 	# unless problem has been graded, set flag to version the submitted files
 2636: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2637: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2638: 	        $dropMenu eq 'reset status')
 2639: 	   {
 2640: 	    push (@version_parts,$new_part);
 2641: 	}
 2642:     }
 2643:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2644:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2645: 
 2646:     if (%newrecord) {
 2647:         if (@version_parts) {
 2648:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2649:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2650: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2651: 	    foreach my $new_part (@version_parts) {
 2652: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2653: 				$new_part,\%newrecord);
 2654: 	    }
 2655:         }
 2656: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2657: 				$env{'request.course.id'},$domain,$stuname);
 2658: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2659: 				     $cdom,$cnum,$domain,$stuname);
 2660:     }
 2661:     if ($aggregateflag) {
 2662:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2663: 			      $cdom,$cnum);
 2664:     }
 2665:     return ('',$pts,$wgt);
 2666: }
 2667: 
 2668: sub check_and_remove_from_queue {
 2669:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2670:     my @ungraded_parts;
 2671:     foreach my $part (@{$parts}) {
 2672: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2673: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2674: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2675: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2676: 		) {
 2677: 	    push(@ungraded_parts, $part);
 2678: 	}
 2679:     }
 2680:     if ( !@ungraded_parts ) {
 2681: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2682: 					       $cnum,$domain,$stuname);
 2683:     }
 2684: }
 2685: 
 2686: sub handback_files {
 2687:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2688:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
 2689:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2690: 
 2691:     my @part_response_id = &flatten_responseType($responseType);
 2692:     foreach my $part_response_id (@part_response_id) {
 2693:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2694: 	my $part_resp = join('_',@{ $part_response_id });
 2695:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2696:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2697:                 my $file_counter = 1;
 2698: 		my $file_msg;
 2699:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2700:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2701:                     my ($directory,$answer_file) = 
 2702:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2703:                     my ($answer_name,$answer_ver,$answer_ext) =
 2704: 		        &file_name_version_ext($answer_file);
 2705: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2706: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
 2707: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2708:                     # fix file name
 2709:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2710:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2711:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2712:             	                                $save_file_name);
 2713:                     if ($result !~ m|^/uploaded/|) {
 2714:                         $request->print('<span class="LC_error">An error occurred ('.$result.
 2715:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
 2716:                     } else {
 2717:                         # mark the file as read only
 2718:                         my @files = ($save_file_name);
 2719:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2720:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2721: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2722: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2723: 			}
 2724:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2725: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2726: 
 2727:                     }
 2728:                     $request->print("<br />".$fname." will be the uploaded file name");
 2729:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2730:                     $file_counter++;
 2731:                 }
 2732: 		my $subject = "File Handed Back by Instructor ";
 2733: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2734: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2735: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2736: 		$message .= " and can be found in your portfolio space.";
 2737: 		my ($feedurl,$showsymb) = 
 2738: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2739:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2740: 		my $msgstatus = 
 2741:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2742: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2743:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2744:             }
 2745:         }
 2746:     return;
 2747: }
 2748: 
 2749: sub get_feedurl_and_symb {
 2750:     my ($symb,$uname,$udom) = @_;
 2751:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2752:     $url = &Apache::lonnet::clutter($url);
 2753:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2754: 					$symb,$udom,$uname);
 2755:     if ($encrypturl =~ /^yes$/i) {
 2756: 	&Apache::lonenc::encrypted(\$url,1);
 2757: 	&Apache::lonenc::encrypted(\$symb,1);
 2758:     }
 2759:     return ($url,$symb);
 2760: }
 2761: 
 2762: sub get_submitted_files {
 2763:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2764:     my @files;
 2765:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2766:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2767:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2768:     	    push(@files,$file_url.$file);
 2769:         }
 2770:     }
 2771:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2772:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2773:     }
 2774:     return (\@files);
 2775: }
 2776: 
 2777: # ----------- Provides number of tries since last reset.
 2778: sub get_num_tries {
 2779:     my ($record,$last_reset,$part) = @_;
 2780:     my $timestamp = '';
 2781:     my $num_tries = 0;
 2782:     if ($$record{'version'}) {
 2783:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2784:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2785:                 $timestamp = $$record{$version.':timestamp'};
 2786:                 if ($timestamp > $last_reset) {
 2787:                     $num_tries ++;
 2788:                 } else {
 2789:                     last;
 2790:                 }
 2791:             }
 2792:         }
 2793:     }
 2794:     return $num_tries;
 2795: }
 2796: 
 2797: # ----------- Determine decrements required in aggregate totals 
 2798: sub decrement_aggs {
 2799:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2800:     my %decrement = (
 2801:                         attempts => 0,
 2802:                         users => 0,
 2803:                         correct => 0
 2804:                     );
 2805:     $decrement{'attempts'} = $aggtries;
 2806:     if ($solvedstatus =~ /^correct/) {
 2807:         $decrement{'correct'} = 1;
 2808:     }
 2809:     if ($aggtries == $totaltries) {
 2810:         $decrement{'users'} = 1;
 2811:     }
 2812:     foreach my $type (keys (%decrement)) {
 2813:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2814:     }
 2815:     return;
 2816: }
 2817: 
 2818: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2819: sub get_last_resets {
 2820:     my ($symb,$courseid,$partids) =@_;
 2821:     my %last_resets;
 2822:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2823:     my $cname = $env{'course.'.$courseid.'.num'};
 2824:     my @keys;
 2825:     foreach my $part (@{$partids}) {
 2826: 	push(@keys,"$symb\0$part\0resettime");
 2827:     }
 2828:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2829: 				     $cdom,$cname);
 2830:     foreach my $part (@{$partids}) {
 2831: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2832:     }
 2833:     return %last_resets;
 2834: }
 2835: 
 2836: # ----------- Handles creating versions for portfolio files as answers
 2837: sub version_portfiles {
 2838:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2839:     my $version_parts = join('|',@$v_flag);
 2840:     my @returned_keys;
 2841:     my $parts = join('|', @$parts_graded);
 2842:     my $portfolio_root = &propath($domain,$stu_name).
 2843: 	'/userfiles/portfolio';
 2844:     foreach my $key (keys(%$record)) {
 2845:         my $new_portfiles;
 2846:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2847:             my @versioned_portfiles;
 2848:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2849:             foreach my $file (@portfiles) {
 2850:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2851:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2852: 		my ($answer_name,$answer_ver,$answer_ext) =
 2853: 		    &file_name_version_ext($answer_file);
 2854:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
 2855:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2856:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2857:                 if ($new_answer ne 'problem getting file') {
 2858:                     push(@versioned_portfiles, $directory.$new_answer);
 2859:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2860:                         [$directory.$new_answer],
 2861:                         [$symb,$env{'request.course.id'},'graded']);
 2862:                 }
 2863:             }
 2864:             $$record{$key} = join(',',@versioned_portfiles);
 2865:             push(@returned_keys,$key);
 2866:         }
 2867:     } 
 2868:     return (@returned_keys);   
 2869: }
 2870: 
 2871: sub get_next_version {
 2872:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2873:     my $version;
 2874:     foreach my $row (@$dir_list) {
 2875:         my ($file) = split(/\&/,$row,2);
 2876:         my ($file_name,$file_version,$file_ext) =
 2877: 	    &file_name_version_ext($file);
 2878:         if (($file_name eq $answer_name) && 
 2879: 	    ($file_ext eq $answer_ext)) {
 2880:                 # gets here if filename and extension match, regardless of version
 2881:                 if ($file_version ne '') {
 2882:                 # a versioned file is found  so save it for later
 2883:                 if ($file_version > $version) {
 2884: 		    $version = $file_version;
 2885: 	        }
 2886:             }
 2887:         }
 2888:     } 
 2889:     $version ++;
 2890:     return($version);
 2891: }
 2892: 
 2893: sub version_selected_portfile {
 2894:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2895:     my ($answer_name,$answer_ver,$answer_ext) =
 2896:         &file_name_version_ext($file_name);
 2897:     my $new_answer;
 2898:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2899:     if($env{'form.copy'} eq '-1') {
 2900:         $new_answer = 'problem getting file';
 2901:     } else {
 2902:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2903:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2904:                             $stu_name,$domain,'copy',
 2905: 		        '/portfolio'.$directory.$new_answer);
 2906:     }    
 2907:     return ($new_answer);
 2908: }
 2909: 
 2910: sub file_name_version_ext {
 2911:     my ($file)=@_;
 2912:     my @file_parts = split(/\./, $file);
 2913:     my ($name,$version,$ext);
 2914:     if (@file_parts > 1) {
 2915: 	$ext=pop(@file_parts);
 2916: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 2917: 	    $version=pop(@file_parts);
 2918: 	}
 2919: 	$name=join('.',@file_parts);
 2920:     } else {
 2921: 	$name=join('.',@file_parts);
 2922:     }
 2923:     return($name,$version,$ext);
 2924: }
 2925: 
 2926: #--------------------------------------------------------------------------------------
 2927: #
 2928: #-------------------------- Next few routines handles grading by section or whole class
 2929: #
 2930: #--- Javascript to handle grading by section or whole class
 2931: sub viewgrades_js {
 2932:     my ($request) = shift;
 2933: 
 2934:     $request->print(<<VIEWJAVASCRIPT);
 2935: <script type="text/javascript" language="javascript">
 2936:    function writePoint(partid,weight,point) {
 2937: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2938: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2939: 	if (point == "textval") {
 2940: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 2941: 	    if (isNaN(point) || parseFloat(point) < 0) {
 2942: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 2943: 		var resetbox = false;
 2944: 		for (var i=0; i<radioButton.length; i++) {
 2945: 		    if (radioButton[i].checked) {
 2946: 			textbox.value = i;
 2947: 			resetbox = true;
 2948: 		    }
 2949: 		}
 2950: 		if (!resetbox) {
 2951: 		    textbox.value = "";
 2952: 		}
 2953: 		return;
 2954: 	    }
 2955: 	    if (parseFloat(point) > parseFloat(weight)) {
 2956: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 2957: 				   ") greater than the weight for the part. Accept?");
 2958: 		if (resp == false) {
 2959: 		    textbox.value = "";
 2960: 		    return;
 2961: 		}
 2962: 	    }
 2963: 	    for (var i=0; i<radioButton.length; i++) {
 2964: 		radioButton[i].checked=false;
 2965: 		if (parseFloat(point) == i) {
 2966: 		    radioButton[i].checked=true;
 2967: 		}
 2968: 	    }
 2969: 
 2970: 	} else {
 2971: 	    textbox.value = parseFloat(point);
 2972: 	}
 2973: 	for (i=0;i<document.classgrade.total.value;i++) {
 2974: 	    var user = document.classgrade["ctr"+i].value;
 2975: 	    user = user.replace(new RegExp(':', 'g'),"_");
 2976: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2977: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2978: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2979: 	    if (saveval != "correct") {
 2980: 		scorename.value = point;
 2981: 		if (selname[0].selected != true) {
 2982: 		    selname[0].selected = true;
 2983: 		}
 2984: 	    }
 2985: 	}
 2986: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 2987:     }
 2988: 
 2989:     function writeRadText(partid,weight) {
 2990: 	var selval   = document.classgrade["SELVAL_"+partid];
 2991: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2992:         var override = document.classgrade["FORCE_"+partid].checked;
 2993: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2994: 	if (selval[1].selected || selval[2].selected) {
 2995: 	    for (var i=0; i<radioButton.length; i++) {
 2996: 		radioButton[i].checked=false;
 2997: 
 2998: 	    }
 2999: 	    textbox.value = "";
 3000: 
 3001: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3002: 		var user = document.classgrade["ctr"+i].value;
 3003: 		user = user.replace(new RegExp(':', 'g'),"_");
 3004: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3005: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3006: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3007: 		if ((saveval != "correct") || override) {
 3008: 		    scorename.value = "";
 3009: 		    if (selval[1].selected) {
 3010: 			selname[1].selected = true;
 3011: 		    } else {
 3012: 			selname[2].selected = true;
 3013: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3014: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3015: 		    }
 3016: 		}
 3017: 	    }
 3018: 	} else {
 3019: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3020: 		var user = document.classgrade["ctr"+i].value;
 3021: 		user = user.replace(new RegExp(':', 'g'),"_");
 3022: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3023: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3024: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3025: 		if ((saveval != "correct") || override) {
 3026: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3027: 		    selname[0].selected = true;
 3028: 		}
 3029: 	    }
 3030: 	}	    
 3031:     }
 3032: 
 3033:     function changeSelect(partid,user) {
 3034: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3035: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3036: 	var point  = textbox.value;
 3037: 	var weight = document.classgrade["weight_"+partid].value;
 3038: 
 3039: 	if (isNaN(point) || parseFloat(point) < 0) {
 3040: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3041: 	    textbox.value = "";
 3042: 	    return;
 3043: 	}
 3044: 	if (parseFloat(point) > parseFloat(weight)) {
 3045: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3046: 			       ") greater than the weight of the part. Accept?");
 3047: 	    if (resp == false) {
 3048: 		textbox.value = "";
 3049: 		return;
 3050: 	    }
 3051: 	}
 3052: 	selval[0].selected = true;
 3053:     }
 3054: 
 3055:     function changeOneScore(partid,user) {
 3056: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3057: 	if (selval[1].selected || selval[2].selected) {
 3058: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3059: 	    if (selval[2].selected) {
 3060: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3061: 	    }
 3062:         }
 3063:     }
 3064: 
 3065:     function resetEntry(numpart) {
 3066: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3067: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3068: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3069: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3070: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3071: 	    for (var i=0; i<radioButton.length; i++) {
 3072: 		radioButton[i].checked=false;
 3073: 
 3074: 	    }
 3075: 	    textbox.value = "";
 3076: 	    selval[0].selected = true;
 3077: 
 3078: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3079: 		var user = document.classgrade["ctr"+i].value;
 3080: 		user = user.replace(new RegExp(':', 'g'),"_");
 3081: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3082: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3083: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3084: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3085: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3086: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3087: 		if (saveselval == "excused") {
 3088: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3089: 		} else {
 3090: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3091: 		}
 3092: 	    }
 3093: 	}
 3094:     }
 3095: 
 3096: </script>
 3097: VIEWJAVASCRIPT
 3098: }
 3099: 
 3100: #--- show scores for a section or whole class w/ option to change/update a score
 3101: sub viewgrades {
 3102:     my ($request) = shift;
 3103:     &viewgrades_js($request);
 3104: 
 3105:     my ($symb) = &get_symb($request);
 3106:     #need to make sure we have the correct data for later EXT calls, 
 3107:     #thus invalidate the cache
 3108:     &Apache::lonnet::devalidatecourseresdata(
 3109:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3110:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3111:     &Apache::lonnet::clear_EXT_cache_status();
 3112: 
 3113:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3114:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
 3115: 
 3116:     #view individual student submission form - called using Javascript viewOneStudent
 3117:     $result.=&jscriptNform($symb);
 3118: 
 3119:     #beginning of class grading form
 3120:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3121:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3122: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3123: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3124: 	&build_section_inputs().
 3125: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3126: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3127: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3128: 
 3129:     my $sectionClass;
 3130:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3131:     if ($env{'form.section'} eq 'all') {
 3132: 	$sectionClass='Class </h3>';
 3133:     } elsif ($env{'form.section'} eq 'none') {
 3134: 	$sectionClass=&mt('Students in no Section').'</h3>';
 3135:     } else {
 3136: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
 3137:     }
 3138:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
 3139:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 3140: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
 3141:     #radio buttons/text box for assigning points for a section or class.
 3142:     #handles different parts of a problem
 3143:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3144:     my %weight = ();
 3145:     my $ctsparts = 0;
 3146:     $result.='<table border="0">';
 3147:     my %seen = ();
 3148:     my @part_response_id = &flatten_responseType($responseType);
 3149:     foreach my $part_response_id (@part_response_id) {
 3150:     	my ($partid,$respid) = @{ $part_response_id };
 3151: 	my $part_resp = join('_',@{ $part_response_id });
 3152: 	next if $seen{$partid};
 3153: 	$seen{$partid}++;
 3154: 	my $handgrade=$$handgrade{$part_resp};
 3155: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3156: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3157: 
 3158: 	$result.='<input type="hidden" name="partid_'.
 3159: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3160: 	$result.='<input type="hidden" name="weight_'.
 3161: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3162: 	my $display_part=&get_display_part($partid,$symb);
 3163: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
 3164: 	$result.='<table border="0"><tr>';  
 3165: 	my $ctr = 0;
 3166: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3167: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3168: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3169: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3170: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3171: 	    $ctr++;
 3172: 	}
 3173: 	$result.='</tr></table>';
 3174: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
 3175: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3176: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3177: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3178: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
 3179: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3180: 		$weight{$partid}.')"> '.
 3181: 	    '<option selected="selected"> </option>'.
 3182: 	    '<option>excused</option>'.
 3183: 	    '<option>reset status</option></select></td>'.
 3184:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
 3185: 	$ctsparts++;
 3186:     }
 3187:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
 3188: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3189:     $result.='<input type="button" value="Revert to Default" '.
 3190: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
 3191: 
 3192:     #table listing all the students in a section/class
 3193:     #header of table
 3194:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
 3195:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 3196: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
 3197: 	'<td>'.&nameUserString('header')."</td>\n";
 3198:     my (@parts) = sort(&getpartlist($symb));
 3199:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3200:     my @partids = ();
 3201:     foreach my $part (@parts) {
 3202: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3203: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3204: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3205: 	my ($partid) = &split_part_type($part);
 3206:         push(@partids, $partid);
 3207: 	my $display_part=&get_display_part($partid,$symb);
 3208: 	if ($display =~ /^Partial Credit Factor/) {
 3209: 	    $result.='<td><b>Score Part:</b> '.$display_part.
 3210: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
 3211: 	    next;
 3212: 	} else {
 3213: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
 3214: 	}
 3215: 	$display =~ s|Problem Status|Grade Status<br />|;
 3216: 	$result.='<td><b>'.$display.'</td>'."\n";
 3217:     }
 3218:     $result.='</tr>';
 3219: 
 3220:     my %last_resets = 
 3221: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3222: 
 3223:     #get info for each student
 3224:     #list all the students - with points and grade status
 3225:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3226:     my $ctr = 0;
 3227:     foreach (sort 
 3228: 	     {
 3229: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3230: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3231: 		 }
 3232: 		 return $a cmp $b;
 3233: 	     } (keys(%$fullname))) {
 3234: 	$ctr++;
 3235: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3236: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3237:     }
 3238:     $result.='</table></td></tr></table>';
 3239:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3240:     $result.='<input type="button" value="Save" '.
 3241: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3242:     if (scalar(%$fullname) eq 0) {
 3243: 	my $colspan=3+scalar(@parts);
 3244: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3245:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3246: 	$result='<span class="LC_warning">'.
 3247: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
 3248: 	        $section_display, $stu_status).
 3249: 	    '</span>';
 3250:     }
 3251:     $result.=&show_grading_menu_form($symb);
 3252:     return $result;
 3253: }
 3254: 
 3255: #--- call by previous routine to display each student
 3256: sub viewstudentgrade {
 3257:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3258:     my ($uname,$udom) = split(/:/,$student);
 3259:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3260:     my %aggregates = (); 
 3261:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
 3262: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3263: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3264: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3265: 	'\');" target="_self">'.$fullname.'</a> '.
 3266: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3267:     $student=~s/:/_/; # colon doen't work in javascript for names
 3268:     foreach my $apart (@$parts) {
 3269: 	my ($part,$type) = &split_part_type($apart);
 3270: 	my $score=$record{"resource.$part.$type"};
 3271:         $result.='<td align="center">';
 3272:         my ($aggtries,$totaltries);
 3273:         unless (exists($aggregates{$part})) {
 3274: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3275: 
 3276: 	    $aggtries = $totaltries;
 3277:             if ($$last_resets{$part}) {  
 3278:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3279: 					   $part);
 3280:             }
 3281:             $result.='<input type="hidden" name="'.
 3282:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3283:             $result.='<input type="hidden" name="'.
 3284:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3285:             $aggregates{$part} = 1;
 3286:         }
 3287: 	if ($type eq 'awarded') {
 3288: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3289: 	    $result.='<input type="hidden" name="'.
 3290: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3291: 	    $result.='<input type="text" name="'.
 3292: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3293: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3294: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3295: 	} elsif ($type eq 'solved') {
 3296: 	    my ($status,$foo)=split(/_/,$score,2);
 3297: 	    $status = 'nothing' if ($status eq '');
 3298: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3299: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3300: 	    $result.='&nbsp;<select name="'.
 3301: 		'GD_'.$student.'_'.$part.'_solved" '.
 3302: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3303: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
 3304: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
 3305: 	    $result.='<option>reset status</option>';
 3306: 	    $result.="</select>&nbsp;</td>\n";
 3307: 	} else {
 3308: 	    $result.='<input type="hidden" name="'.
 3309: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3310: 		    "\n";
 3311: 	    $result.='<input type="text" name="'.
 3312: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3313: 		'value="'.$score.'" size="4" /></td>'."\n";
 3314: 	}
 3315:     }
 3316:     $result.='</tr>';
 3317:     return $result;
 3318: }
 3319: 
 3320: #--- change scores for all the students in a section/class
 3321: #    record does not get update if unchanged
 3322: sub editgrades {
 3323:     my ($request) = @_;
 3324: 
 3325:     my $symb=&get_symb($request);
 3326:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3327:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
 3328:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
 3329:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3330: 
 3331:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
 3332:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
 3333: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
 3334: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
 3335: 
 3336:     my %scoreptr = (
 3337: 		    'correct'  =>'correct_by_override',
 3338: 		    'incorrect'=>'incorrect_by_override',
 3339: 		    'excused'  =>'excused',
 3340: 		    'ungraded' =>'ungraded_attempted',
 3341: 		    'nothing'  => '',
 3342: 		    );
 3343:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3344: 
 3345:     my (@partid);
 3346:     my %weight = ();
 3347:     my %columns = ();
 3348:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3349: 
 3350:     my (@parts) = sort(&getpartlist($symb));
 3351:     my $header;
 3352:     while ($ctr < $env{'form.totalparts'}) {
 3353: 	my $partid = $env{'form.partid_'.$ctr};
 3354: 	push @partid,$partid;
 3355: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3356: 	$ctr++;
 3357:     }
 3358:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3359:     foreach my $partid (@partid) {
 3360: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
 3361: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
 3362: 	$columns{$partid}=2;
 3363: 	foreach my $stores (@parts) {
 3364: 	    my ($part,$type) = &split_part_type($stores);
 3365: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3366: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3367: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3368: 	    $display =~ s/\[Part: (\w)+\]//;
 3369: 	    $display =~ s/Number of Attempts/Tries/;
 3370: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
 3371: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
 3372: 	    $columns{$partid}+=2;
 3373: 	}
 3374:     }
 3375:     foreach my $partid (@partid) {
 3376: 	my $display_part=&get_display_part($partid,$symb);
 3377: 	$result .= '<td colspan="'.$columns{$partid}.
 3378: 	    '" align="center"><b>Part:</b> '.$display_part.
 3379: 	    ' (Weight = '.$weight{$partid}.')</td>';
 3380: 
 3381:     }
 3382:     $result .= '</tr><tr bgcolor="#deffff">';
 3383:     $result .= $header;
 3384:     $result .= '</tr>'."\n";
 3385:     my $noupdate;
 3386:     my ($updateCtr,$noupdateCtr) = (1,1);
 3387:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3388: 	my $line;
 3389: 	my $user = $env{'form.ctr'.$i};
 3390: 	my ($uname,$udom)=split(/:/,$user);
 3391: 	my %newrecord;
 3392: 	my $updateflag = 0;
 3393: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3394: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3395: 	if (!&canmodify($usec)) {
 3396: 	    my $numcols=scalar(@partid)*4+2;
 3397: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
 3398: 	    next;
 3399: 	}
 3400:         my %aggregate = ();
 3401:         my $aggregateflag = 0;
 3402: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3403: 	foreach (@partid) {
 3404: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3405: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3406: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3407: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3408: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3409: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3410: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3411: 	    my $score;
 3412: 	    if ($partial eq '') {
 3413: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3414: 	    } elsif ($partial > 0) {
 3415: 		$score = 'correct_by_override';
 3416: 	    } elsif ($partial == 0) {
 3417: 		$score = 'incorrect_by_override';
 3418: 	    }
 3419: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3420: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3421: 
 3422: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3423: 		"$env{'user.name'}:$env{'user.domain'}";
 3424: 	    if ($dropMenu eq 'reset status' &&
 3425: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3426: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3427: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3428: 		$newrecord{'resource.'.$_.'.award'} = '';
 3429: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3430: 		$updateflag = 1;
 3431:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3432:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3433:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3434:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3435:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3436:                     $aggregateflag = 1;
 3437:                 }
 3438: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3439: 		$updateflag = 1;
 3440: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3441: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3442: 		$rec_update++;
 3443: 	    }
 3444: 
 3445: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3446: 		'<td align="center">'.$awarded.
 3447: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3448: 
 3449: 
 3450: 	    my $partid=$_;
 3451: 	    foreach my $stores (@parts) {
 3452: 		my ($part,$type) = &split_part_type($stores);
 3453: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3454: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3455: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3456: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3457: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3458: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3459: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3460: 		    $updateflag=1;
 3461: 		}
 3462: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3463: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3464: 	    }
 3465: 	}
 3466: 	$line.='</tr>'."\n";
 3467: 
 3468: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3469: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3470: 
 3471: 	if ($updateflag) {
 3472: 	    $count++;
 3473: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3474: 				    $udom,$uname);
 3475: 
 3476: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3477: 					      $cnum,$udom,$uname)) {
 3478: 		# need to figure out if should be in queue.
 3479: 		my %record =  
 3480: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3481: 					     $udom,$uname);
 3482: 		my $all_graded = 1;
 3483: 		my $none_graded = 1;
 3484: 		foreach my $part (@parts) {
 3485: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3486: 			$all_graded = 0;
 3487: 		    } else {
 3488: 			$none_graded = 0;
 3489: 		    }
 3490: 		}
 3491: 
 3492: 		if ($all_graded || $none_graded) {
 3493: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3494: 							   $symb,$cdom,$cnum,
 3495: 							   $udom,$uname);
 3496: 		}
 3497: 	    }
 3498: 
 3499: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
 3500: 	    $updateCtr++;
 3501: 	} else {
 3502: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
 3503: 	    $noupdateCtr++;
 3504: 	}
 3505:         if ($aggregateflag) {
 3506:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3507: 				  $cdom,$cnum);
 3508:         }
 3509:     }
 3510:     if ($noupdate) {
 3511: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3512: 	my $numcols=scalar(@partid)*4+2;
 3513: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
 3514:     }
 3515:     $result .= '</table></td></tr></table>'."\n".
 3516: 	&show_grading_menu_form ($symb);
 3517:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
 3518: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
 3519: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
 3520:     return $title.$msg.$result;
 3521: }
 3522: 
 3523: sub split_part_type {
 3524:     my ($partstr) = @_;
 3525:     my ($temp,@allparts)=split(/_/,$partstr);
 3526:     my $type=pop(@allparts);
 3527:     my $part=join('_',@allparts);
 3528:     return ($part,$type);
 3529: }
 3530: 
 3531: #------------- end of section for handling grading by section/class ---------
 3532: #
 3533: #----------------------------------------------------------------------------
 3534: 
 3535: 
 3536: #----------------------------------------------------------------------------
 3537: #
 3538: #-------------------------- Next few routines handles grading by csv upload
 3539: #
 3540: #--- Javascript to handle csv upload
 3541: sub csvupload_javascript_reverse_associate {
 3542:     my $error1=&mt('You need to specify the username or ID');
 3543:     my $error2=&mt('You need to specify at least one grading field');
 3544:   return(<<ENDPICK);
 3545:   function verify(vf) {
 3546:     var foundsomething=0;
 3547:     var founduname=0;
 3548:     var foundID=0;
 3549:     for (i=0;i<=vf.nfields.value;i++) {
 3550:       tw=eval('vf.f'+i+'.selectedIndex');
 3551:       if (i==0 && tw!=0) { foundID=1; }
 3552:       if (i==1 && tw!=0) { founduname=1; }
 3553:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3554:     }
 3555:     if (founduname==0 && foundID==0) {
 3556: 	alert('$error1');
 3557: 	return;
 3558:     }
 3559:     if (foundsomething==0) {
 3560: 	alert('$error2');
 3561: 	return;
 3562:     }
 3563:     vf.submit();
 3564:   }
 3565:   function flip(vf,tf) {
 3566:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3567:     var i;
 3568:     for (i=0;i<=vf.nfields.value;i++) {
 3569:       //can not pick the same destination field for both name and domain
 3570:       if (((i ==0)||(i ==1)) && 
 3571:           ((tf==0)||(tf==1)) && 
 3572:           (i!=tf) &&
 3573:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3574:         eval('vf.f'+i+'.selectedIndex=0;')
 3575:       }
 3576:     }
 3577:   }
 3578: ENDPICK
 3579: }
 3580: 
 3581: sub csvupload_javascript_forward_associate {
 3582:     my $error1=&mt('You need to specify the username or ID');
 3583:     my $error2=&mt('You need to specify at least one grading field');
 3584:   return(<<ENDPICK);
 3585:   function verify(vf) {
 3586:     var foundsomething=0;
 3587:     var founduname=0;
 3588:     var foundID=0;
 3589:     for (i=0;i<=vf.nfields.value;i++) {
 3590:       tw=eval('vf.f'+i+'.selectedIndex');
 3591:       if (tw==1) { foundID=1; }
 3592:       if (tw==2) { founduname=1; }
 3593:       if (tw>3) { foundsomething=1; }
 3594:     }
 3595:     if (founduname==0 && foundID==0) {
 3596: 	alert('$error1');
 3597: 	return;
 3598:     }
 3599:     if (foundsomething==0) {
 3600: 	alert('$error2');
 3601: 	return;
 3602:     }
 3603:     vf.submit();
 3604:   }
 3605:   function flip(vf,tf) {
 3606:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3607:     var i;
 3608:     //can not pick the same destination field twice
 3609:     for (i=0;i<=vf.nfields.value;i++) {
 3610:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3611:         eval('vf.f'+i+'.selectedIndex=0;')
 3612:       }
 3613:     }
 3614:   }
 3615: ENDPICK
 3616: }
 3617: 
 3618: sub csvuploadmap_header {
 3619:     my ($request,$symb,$datatoken,$distotal)= @_;
 3620:     my $javascript;
 3621:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3622: 	$javascript=&csvupload_javascript_reverse_associate();
 3623:     } else {
 3624: 	$javascript=&csvupload_javascript_forward_associate();
 3625:     }
 3626: 
 3627:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3628:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3629:     my $ignore=&mt('Ignore First Line');
 3630:     $symb = &Apache::lonenc::check_encrypt($symb);
 3631:     $request->print(<<ENDPICK);
 3632: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3633: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3634: $result
 3635: <hr />
 3636: <h3>Identify fields</h3>
 3637: Total number of records found in file: $distotal <hr />
 3638: Enter as many fields as you can. The system will inform you and bring you back
 3639: to this page if the data selected is insufficient to run your class.<hr />
 3640: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3641: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3642: <input type="hidden" name="associate"  value="" />
 3643: <input type="hidden" name="phase"      value="three" />
 3644: <input type="hidden" name="datatoken"  value="$datatoken" />
 3645: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3646: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3647: <input type="hidden" name="upfile_associate" 
 3648:                                        value="$env{'form.upfile_associate'}" />
 3649: <input type="hidden" name="symb"       value="$symb" />
 3650: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3651: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3652: <input type="hidden" name="command"    value="csvuploadoptions" />
 3653: <hr />
 3654: <script type="text/javascript" language="Javascript">
 3655: $javascript
 3656: </script>
 3657: ENDPICK
 3658:     return '';
 3659: 
 3660: }
 3661: 
 3662: sub csvupload_fields {
 3663:     my ($symb) = @_;
 3664:     my (@parts) = &getpartlist($symb);
 3665:     my @fields=(['ID','Student ID'],
 3666: 		['username','Student Username'],
 3667: 		['domain','Student Domain']);
 3668:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3669:     foreach my $part (sort(@parts)) {
 3670: 	my @datum;
 3671: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3672: 	my $name=$part;
 3673: 	if  (!$display) { $display = $name; }
 3674: 	@datum=($name,$display);
 3675: 	if ($name=~/^stores_(.*)_awarded/) {
 3676: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3677: 	}
 3678: 	push(@fields,\@datum);
 3679:     }
 3680:     return (@fields);
 3681: }
 3682: 
 3683: sub csvuploadmap_footer {
 3684:     my ($request,$i,$keyfields) =@_;
 3685:     $request->print(<<ENDPICK);
 3686: </table>
 3687: <input type="hidden" name="nfields" value="$i" />
 3688: <input type="hidden" name="keyfields" value="$keyfields" />
 3689: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3690: </form>
 3691: ENDPICK
 3692: }
 3693: 
 3694: sub checkforfile_js {
 3695:     my $result =<<CSVFORMJS;
 3696: <script type="text/javascript" language="javascript">
 3697:     function checkUpload(formname) {
 3698: 	if (formname.upfile.value == "") {
 3699: 	    alert("Please use the browse button to select a file from your local directory.");
 3700: 	    return false;
 3701: 	}
 3702: 	formname.submit();
 3703:     }
 3704:     </script>
 3705: CSVFORMJS
 3706:     return $result;
 3707: }
 3708: 
 3709: sub upcsvScores_form {
 3710:     my ($request) = shift;
 3711:     my ($symb)=&get_symb($request);
 3712:     if (!$symb) {return '';}
 3713:     my $result=&checkforfile_js();
 3714:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3715:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3716:     $result.=$table;
 3717:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3718:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3719:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3720: 	'.</b></td></tr>'."\n";
 3721:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3722:     my $upload=&mt("Upload Scores");
 3723:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3724:     my $ignore=&mt('Ignore First Line');
 3725:     $symb = &Apache::lonenc::check_encrypt($symb);
 3726:     $result.=<<ENDUPFORM;
 3727: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3728: <input type="hidden" name="symb" value="$symb" />
 3729: <input type="hidden" name="command" value="csvuploadmap" />
 3730: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3731: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3732: $upfile_select
 3733: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3734: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3735: </form>
 3736: ENDUPFORM
 3737:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3738:                            &mt("How do I create a CSV file from a spreadsheet"))
 3739:     .'</td></tr></table>'."\n";
 3740:     $result.='</td></tr></table><br /><br />'."\n";
 3741:     $result.=&show_grading_menu_form($symb);
 3742:     return $result;
 3743: }
 3744: 
 3745: 
 3746: sub csvuploadmap {
 3747:     my ($request)= @_;
 3748:     my ($symb)=&get_symb($request);
 3749:     if (!$symb) {return '';}
 3750: 
 3751:     my $datatoken;
 3752:     if (!$env{'form.datatoken'}) {
 3753: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3754:     } else {
 3755: 	$datatoken=$env{'form.datatoken'};
 3756: 	&Apache::loncommon::load_tmp_file($request);
 3757:     }
 3758:     my @records=&Apache::loncommon::upfile_record_sep();
 3759:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3760:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3761:     my ($i,$keyfields);
 3762:     if (@records) {
 3763: 	my @fields=&csvupload_fields($symb);
 3764: 
 3765: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3766: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3767: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3768: 							  \@fields);
 3769: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3770: 	    chop($keyfields);
 3771: 	} else {
 3772: 	    unshift(@fields,['none','']);
 3773: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3774: 							    \@fields);
 3775:             foreach my $rec (@records) {
 3776:                 my %temp = &Apache::loncommon::record_sep($rec);
 3777:                 if (%temp) {
 3778:                     $keyfields=join(',',sort(keys(%temp)));
 3779:                     last;
 3780:                 }
 3781:             }
 3782: 	}
 3783:     }
 3784:     &csvuploadmap_footer($request,$i,$keyfields);
 3785:     $request->print(&show_grading_menu_form($symb));
 3786: 
 3787:     return '';
 3788: }
 3789: 
 3790: sub csvuploadoptions {
 3791:     my ($request)= @_;
 3792:     my ($symb)=&get_symb($request);
 3793:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3794:     my $ignore=&mt('Ignore First Line');
 3795:     $request->print(<<ENDPICK);
 3796: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3797: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3798: <input type="hidden" name="command"    value="csvuploadassign" />
 3799: <!--
 3800: <p>
 3801: <label>
 3802:    <input type="checkbox" name="show_full_results" />
 3803:    Show a table of all changes
 3804: </label>
 3805: </p>
 3806: -->
 3807: <p>
 3808: <label>
 3809:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3810:    Overwrite any existing score
 3811: </label>
 3812: </p>
 3813: ENDPICK
 3814:     my %fields=&get_fields();
 3815:     if (!defined($fields{'domain'})) {
 3816: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3817: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3818:     }
 3819:     foreach my $key (sort(keys(%env))) {
 3820: 	if ($key !~ /^form\.(.*)$/) { next; }
 3821: 	my $cleankey=$1;
 3822: 	if ($cleankey eq 'command') { next; }
 3823: 	$request->print('<input type="hidden" name="'.$cleankey.
 3824: 			'"  value="'.$env{$key}.'" />'."\n");
 3825:     }
 3826:     # FIXME do a check for any duplicated user ids...
 3827:     # FIXME do a check for any invalid user ids?...
 3828:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3829: <hr /></form>'."\n");
 3830:     $request->print(&show_grading_menu_form($symb));
 3831:     return '';
 3832: }
 3833: 
 3834: sub get_fields {
 3835:     my %fields;
 3836:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3837:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3838: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3839: 	    if ($env{'form.f'.$i} ne 'none') {
 3840: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3841: 	    }
 3842: 	} else {
 3843: 	    if ($env{'form.f'.$i} ne 'none') {
 3844: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3845: 	    }
 3846: 	}
 3847:     }
 3848:     return %fields;
 3849: }
 3850: 
 3851: sub csvuploadassign {
 3852:     my ($request)= @_;
 3853:     my ($symb)=&get_symb($request);
 3854:     if (!$symb) {return '';}
 3855:     my $error_msg = '';
 3856:     &Apache::loncommon::load_tmp_file($request);
 3857:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3858:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3859:     my %fields=&get_fields();
 3860:     $request->print('<h3>Assigning Grades</h3>');
 3861:     my $courseid=$env{'request.course.id'};
 3862:     my ($classlist) = &getclasslist('all',0);
 3863:     my @notallowed;
 3864:     my @skipped;
 3865:     my $countdone=0;
 3866:     foreach my $grade (@gradedata) {
 3867: 	my %entries=&Apache::loncommon::record_sep($grade);
 3868: 	my $domain;
 3869: 	if ($entries{$fields{'domain'}}) {
 3870: 	    $domain=$entries{$fields{'domain'}};
 3871: 	} else {
 3872: 	    $domain=$env{'form.default_domain'};
 3873: 	}
 3874: 	$domain=~s/\s//g;
 3875: 	my $username=$entries{$fields{'username'}};
 3876: 	$username=~s/\s//g;
 3877: 	if (!$username) {
 3878: 	    my $id=$entries{$fields{'ID'}};
 3879: 	    $id=~s/\s//g;
 3880: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3881: 	    $username=$ids{$id};
 3882: 	}
 3883: 	if (!exists($$classlist{"$username:$domain"})) {
 3884: 	    my $id=$entries{$fields{'ID'}};
 3885: 	    $id=~s/\s//g;
 3886: 	    if ($id) {
 3887: 		push(@skipped,"$id:$domain");
 3888: 	    } else {
 3889: 		push(@skipped,"$username:$domain");
 3890: 	    }
 3891: 	    next;
 3892: 	}
 3893: 	my $usec=$classlist->{"$username:$domain"}[5];
 3894: 	if (!&canmodify($usec)) {
 3895: 	    push(@notallowed,"$username:$domain");
 3896: 	    next;
 3897: 	}
 3898: 	my %points;
 3899: 	my %grades;
 3900: 	foreach my $dest (keys(%fields)) {
 3901: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 3902: 		$dest eq 'domain') { next; }
 3903: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 3904: 	    if ($dest=~/stores_(.*)_points/) {
 3905: 		my $part=$1;
 3906: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 3907: 					      $symb,$domain,$username);
 3908:                 if ($wgt) {
 3909:                     $entries{$fields{$dest}}=~s/\s//g;
 3910:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 3911:                     my $award='correct_by_override';
 3912:                     $grades{"resource.$part.awarded"}=$pcr;
 3913:                     $grades{"resource.$part.solved"}=$award;
 3914:                     $points{$part}=1;
 3915:                 } else {
 3916:                     $error_msg = "<br />" .
 3917:                         &mt("Some point values were assigned"
 3918:                             ." for problems with a weight "
 3919:                             ."of zero. These values were "
 3920:                             ."ignored.");
 3921:                 }
 3922: 	    } else {
 3923: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 3924: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 3925: 		my $store_key=$dest;
 3926: 		$store_key=~s/^stores/resource/;
 3927: 		$store_key=~s/_/\./g;
 3928: 		$grades{$store_key}=$entries{$fields{$dest}};
 3929: 	    }
 3930: 	}
 3931: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
 3932: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 3933: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
 3934: 					   $env{'request.course.id'},
 3935: 					   $domain,$username);
 3936: 	if ($result eq 'ok') {
 3937: 	    $request->print('.');
 3938: 	} else {
 3939: 	    $request->print("<p>
 3940:                               <span class=\"LC_error\">
 3941:                                  Failed to save student $username:$domain.
 3942:                                  Message when trying to save was ($result)
 3943:                               </span>
 3944:                              </p>" );
 3945: 	}
 3946: 	$request->rflush();
 3947: 	$countdone++;
 3948:     }
 3949:     $request->print("<br />Saved $countdone students\n");
 3950:     if (@skipped) {
 3951: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
 3952: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 3953:     }
 3954:     if (@notallowed) {
 3955: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
 3956: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 3957:     }
 3958:     $request->print("<br />\n");
 3959:     $request->print(&show_grading_menu_form($symb));
 3960:     return $error_msg;
 3961: }
 3962: #------------- end of section for handling csv file upload ---------
 3963: #
 3964: #-------------------------------------------------------------------
 3965: #
 3966: #-------------- Next few routines handle grading by page/sequence
 3967: #
 3968: #--- Select a page/sequence and a student to grade
 3969: sub pickStudentPage {
 3970:     my ($request) = shift;
 3971: 
 3972:     $request->print(<<LISTJAVASCRIPT);
 3973: <script type="text/javascript" language="javascript">
 3974: 
 3975: function checkPickOne(formname) {
 3976:     if (radioSelection(formname.student) == null) {
 3977: 	alert("Please select the student you wish to grade.");
 3978: 	return;
 3979:     }
 3980:     ptr = pullDownSelection(formname.selectpage);
 3981:     formname.page.value = formname["page"+ptr].value;
 3982:     formname.title.value = formname["title"+ptr].value;
 3983:     formname.submit();
 3984: }
 3985: 
 3986: </script>
 3987: LISTJAVASCRIPT
 3988:     &commonJSfunctions($request);
 3989:     my ($symb) = &get_symb($request);
 3990:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 3991:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 3992:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 3993: 
 3994:     my $result='<h3><span class="LC_info">&nbsp;'.
 3995: 	'Manual Grading by Page or Sequence</span></h3>';
 3996: 
 3997:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 3998:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
 3999:     my ($titles,$symbx) = &getSymbMap();
 4000:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4001: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4002: #    my $type=($curpage =~ /\.(page|sequence)/);
 4003:     my $ctr=0;
 4004:     foreach (@$titles) {
 4005: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4006: 	$result.='<option value="'.$ctr.'" '.
 4007: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4008: 	    '>'.$showtitle.'</option>'."\n";
 4009: 	$ctr++;
 4010:     }
 4011:     $result.= '</select>'."<br />\n";
 4012:     $ctr=0;
 4013:     foreach (@$titles) {
 4014: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4015: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4016: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4017: 	$ctr++;
 4018:     }
 4019:     $result.='<input type="hidden" name="page" />'."\n".
 4020: 	'<input type="hidden" name="title" />'."\n";
 4021: 
 4022:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
 4023: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
 4024: 
 4025:     $result.='&nbsp;<b>Submission Details: </b>'.
 4026: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
 4027: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
 4028: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
 4029:     
 4030:     $result.=&build_section_inputs();
 4031:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4032:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4033: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4034: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4035: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4036: 
 4037:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
 4038: 	'<input type="text" name="CODE" value="" /><br />'."\n";
 4039: 
 4040:     $result.='&nbsp;<input type="button" '.
 4041: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
 4042: 
 4043:     $request->print($result);
 4044: 
 4045:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
 4046: 	'<table border="0"><tr><td bgcolor="#777777">'.
 4047: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4048: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 4049: 	'<td>'.&nameUserString('header').'</td>'.
 4050: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 4051: 	'<td>'.&nameUserString('header').'</td></tr>';
 4052:  
 4053:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4054:     my $ptr = 1;
 4055:     foreach my $student (sort 
 4056: 			 {
 4057: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4058: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4059: 			     }
 4060: 			     return $a cmp $b;
 4061: 			 } (keys(%$fullname))) {
 4062: 	my ($uname,$udom) = split(/:/,$student);
 4063: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
 4064: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4065: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4066: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4067: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
 4068: 	$ptr++;
 4069:     }
 4070:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
 4071:     $studentTable.='</table></td></tr></table>'."\n";
 4072:     $studentTable.='<input type="button" '.
 4073: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
 4074: 
 4075:     $studentTable.=&show_grading_menu_form($symb);
 4076:     $request->print($studentTable);
 4077: 
 4078:     return '';
 4079: }
 4080: 
 4081: sub getSymbMap {
 4082:     my $navmap = Apache::lonnavmaps::navmap->new();
 4083: 
 4084:     my %symbx = ();
 4085:     my @titles = ();
 4086:     my $minder = 0;
 4087: 
 4088:     # Gather every sequence that has problems.
 4089:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4090: 					       1,0,1);
 4091:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4092: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4093: 	    my $title = $minder.'.'.
 4094: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4095: 	    push(@titles, $title); # minder in case two titles are identical
 4096: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4097: 	    $minder++;
 4098: 	}
 4099:     }
 4100:     return \@titles,\%symbx;
 4101: }
 4102: 
 4103: #
 4104: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4105: sub displayPage {
 4106:     my ($request) = shift;
 4107: 
 4108:     my ($symb) = &get_symb($request);
 4109:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4110:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4111:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4112:     my $pageTitle = $env{'form.page'};
 4113:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4114:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4115:     my $usec=$classlist->{$env{'form.student'}}[5];
 4116: 
 4117:     #need to make sure we have the correct data for later EXT calls, 
 4118:     #thus invalidate the cache
 4119:     &Apache::lonnet::devalidatecourseresdata(
 4120:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4121:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4122:     &Apache::lonnet::clear_EXT_cache_status();
 4123: 
 4124:     if (!&canview($usec)) {
 4125: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
 4126: 	$request->print(&show_grading_menu_form($symb));
 4127: 	return;
 4128:     }
 4129:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4130:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
 4131: 	'</h3>'."\n";
 4132:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4133: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
 4134:     } else {
 4135: 	delete($env{'form.CODE'});
 4136:     }
 4137:     &sub_page_js($request);
 4138:     $request->print($result);
 4139: 
 4140:     my $navmap = Apache::lonnavmaps::navmap->new();
 4141:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4142:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4143:     if (!$map) {
 4144: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
 4145: 	$request->print(&show_grading_menu_form($symb));
 4146: 	return; 
 4147:     }
 4148:     my $iterator = $navmap->getIterator($map->map_start(),
 4149: 					$map->map_finish());
 4150: 
 4151:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4152: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4153: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4154: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4155: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4156: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4157: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4158: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4159: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4160: 
 4161:     if (defined($env{'form.CODE'})) {
 4162: 	$studentTable.=
 4163: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4164:     }
 4165:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4166: 	'" src="'.$request->dir_config('lonIconsURL').
 4167: 	'/check.gif" height="16" border="0" />';
 4168: 
 4169:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
 4170: 	' symbol.'."\n".
 4171: 	'<table border="0"><tr><td bgcolor="#777777">'.
 4172: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4173: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 4174: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
 4175: 
 4176:     &Apache::lonxml::clear_problem_counter();
 4177:     my ($depth,$question,$prob) = (1,1,1);
 4178:     $iterator->next(); # skip the first BEGIN_MAP
 4179:     my $curRes = $iterator->next(); # for "current resource"
 4180:     while ($depth > 0) {
 4181:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4182:         if($curRes == $iterator->END_MAP) { $depth--; }
 4183: 
 4184:         if (ref($curRes) && $curRes->is_problem()) {
 4185: 	    my $parts = $curRes->parts();
 4186:             my $title = $curRes->compTitle();
 4187: 	    my $symbx = $curRes->symb();
 4188: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 4189: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 4190: 	    $studentTable.='<td valign="top">';
 4191: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4192: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4193: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4194: 					     undef,'both',\%form);
 4195: 	    } else {
 4196: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4197: 		$companswer =~ s|<form(.*?)>||g;
 4198: 		$companswer =~ s|</form>||g;
 4199: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4200: #		    $companswer =~ s/$1/ /ms;
 4201: #		    $request->print('match='.$1."<br />\n");
 4202: #		}
 4203: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4204: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
 4205: 	    }
 4206: 
 4207: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4208: 
 4209: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4210: 		if ($record{'version'} eq '') {
 4211: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
 4212: 		} else {
 4213: 		    my %responseType = ();
 4214: 		    foreach my $partid (@{$parts}) {
 4215: 			my @responseIds =$curRes->responseIds($partid);
 4216: 			my @responseType =$curRes->responseType($partid);
 4217: 			my %responseIds;
 4218: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4219: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4220: 			}
 4221: 			$responseType{$partid} = \%responseIds;
 4222: 		    }
 4223: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4224: 
 4225: 		}
 4226: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4227: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4228: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4229: 									$env{'request.course.id'},
 4230: 									'','.submission');
 4231:  
 4232: 	    }
 4233: 	    if (&canmodify($usec)) {
 4234: 		foreach my $partid (@{$parts}) {
 4235: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4236: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4237: 		    $question++;
 4238: 		}
 4239: 		$prob++;
 4240: 	    }
 4241: 	    $studentTable.='</td></tr>';
 4242: 
 4243: 	}
 4244:         $curRes = $iterator->next();
 4245:     }
 4246: 
 4247:     $studentTable.='</table></td></tr></table>'."\n".
 4248: 	'<input type="button" value="Save" '.
 4249: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4250: 	'</form>'."\n";
 4251:     $studentTable.=&show_grading_menu_form($symb);
 4252:     $request->print($studentTable);
 4253: 
 4254:     return '';
 4255: }
 4256: 
 4257: sub displaySubByDates {
 4258:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4259:     my $isCODE=0;
 4260:     my $isTask = ($symb =~/\.task$/);
 4261:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4262:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
 4263: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
 4264: 	'<td><b>Date/Time</b></td>'.
 4265: 	($isCODE?'<td><b>CODE</b></td>':'').
 4266: 	'<td><b>Submission</b></td>'.
 4267: 	'<td><b>Status&nbsp;</b></td></tr>';
 4268:     my ($version);
 4269:     my %mark;
 4270:     my %orders;
 4271:     $mark{'correct_by_student'} = $checkIcon;
 4272:     if (!exists($$record{'1:timestamp'})) {
 4273: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
 4274:     }
 4275: 
 4276:     my $interaction;
 4277:     for ($version=1;$version<=$$record{'version'};$version++) {
 4278: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
 4279: 	if (exists($$record{$version.':resource.0.version'})) {
 4280: 	    $interaction = $$record{$version.':resource.0.version'};
 4281: 	}
 4282: 
 4283: 	my $where = ($isTask ? "$version:resource.$interaction"
 4284: 		             : "$version:resource");
 4285: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
 4286: 	if ($isCODE) {
 4287: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4288: 	}
 4289: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4290: 	my @displaySub = ();
 4291: 	foreach my $partid (@{$parts}) {
 4292: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4293: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4294: 	    
 4295: 
 4296: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4297: 	    my $display_part=&get_display_part($partid,$symb);
 4298: 	    foreach my $matchKey (@matchKey) {
 4299: 		if (exists($$record{$version.':'.$matchKey}) &&
 4300: 		    $$record{$version.':'.$matchKey} ne '') {
 4301: 
 4302: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4303: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4304: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
 4305: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
 4306: 			$responseId.')</span>&nbsp;<b>';
 4307: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4308: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
 4309: 		    } else {
 4310: 			$displaySub[0].='Trial&nbsp;'.
 4311: 			    $$record{"$where.$partid.tries"};
 4312: 		    }
 4313: 		    my $responseType=($isTask ? 'Task'
 4314:                                               : $responseType->{$partid}->{$responseId});
 4315: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4316: 		    if (!exists($orders{$partid}->{$responseId})) {
 4317: 			$orders{$partid}->{$responseId}=
 4318: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
 4319: 		    }
 4320: 		    $displaySub[0].='</b>&nbsp; '.
 4321: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4322: 		}
 4323: 	    }
 4324: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4325: 		$displaySub[1].='Checked in by '.
 4326: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
 4327: 		    $$record{"$where.$partid.checkedin.slot"}.
 4328: 		    '<br />';
 4329: 	    }
 4330: 	    if (exists $$record{"$where.$partid.award"}) {
 4331: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
 4332: 		    lc($$record{"$where.$partid.award"}).' '.
 4333: 		    $mark{$$record{"$where.$partid.solved"}}.
 4334: 		    '<br />';
 4335: 	    }
 4336: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4337: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4338: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4339: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4340: 		$displaySub[2].=
 4341: 		    $$record{"$version:resource.$partid.regrader"}.
 4342: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4343: 	    }
 4344: 	}
 4345: 	# needed because old essay regrader has not parts info
 4346: 	if (exists $$record{"$version:resource.regrader"}) {
 4347: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4348: 	}
 4349: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4350: 	if ($displaySub[2]) {
 4351: 	    $studentTable.='Manually graded by '.$displaySub[2];
 4352: 	}
 4353: 	$studentTable.='&nbsp;</td></tr>';
 4354:     
 4355:     }
 4356:     $studentTable.='</table></td></tr></table>';
 4357:     return $studentTable;
 4358: }
 4359: 
 4360: sub updateGradeByPage {
 4361:     my ($request) = shift;
 4362: 
 4363:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4364:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4365:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4366:     my $pageTitle = $env{'form.page'};
 4367:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4368:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4369:     my $usec=$classlist->{$env{'form.student'}}[5];
 4370:     if (!&canmodify($usec)) {
 4371: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
 4372: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4373: 	return;
 4374:     }
 4375:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4376:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4377: 	'</h3>'."\n";
 4378: 
 4379:     $request->print($result);
 4380: 
 4381:     my $navmap = Apache::lonnavmaps::navmap->new();
 4382:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4383:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4384:     if (!$map) {
 4385: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
 4386: 	my ($symb)=&get_symb($request);
 4387: 	$request->print(&show_grading_menu_form($symb));
 4388: 	return; 
 4389:     }
 4390:     my $iterator = $navmap->getIterator($map->map_start(),
 4391: 					$map->map_finish());
 4392: 
 4393:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
 4394: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4395: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 4396: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
 4397: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
 4398: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
 4399: 
 4400:     $iterator->next(); # skip the first BEGIN_MAP
 4401:     my $curRes = $iterator->next(); # for "current resource"
 4402:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4403:     while ($depth > 0) {
 4404:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4405:         if($curRes == $iterator->END_MAP) { $depth--; }
 4406: 
 4407:         if (ref($curRes) && $curRes->is_problem()) {
 4408: 	    my $parts = $curRes->parts();
 4409:             my $title = $curRes->compTitle();
 4410: 	    my $symbx = $curRes->symb();
 4411: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 4412: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 4413: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4414: 
 4415: 	    my %newrecord=();
 4416: 	    my @displayPts=();
 4417:             my %aggregate = ();
 4418:             my $aggregateflag = 0;
 4419: 	    foreach my $partid (@{$parts}) {
 4420: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4421: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4422: 
 4423: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4424: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4425: 		my $partial = $newpts/$wgt;
 4426: 		my $score;
 4427: 		if ($partial > 0) {
 4428: 		    $score = 'correct_by_override';
 4429: 		} elsif ($newpts ne '') { #empty is taken as 0
 4430: 		    $score = 'incorrect_by_override';
 4431: 		}
 4432: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4433: 		if ($dropMenu eq 'excused') {
 4434: 		    $partial = '';
 4435: 		    $score = 'excused';
 4436: 		} elsif ($dropMenu eq 'reset status'
 4437: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4438: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4439: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4440: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4441: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4442: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4443: 		    $changeflag++;
 4444: 		    $newpts = '';
 4445:                     
 4446:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4447:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4448:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4449:                     if ($aggtries > 0) {
 4450:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4451:                         $aggregateflag = 1;
 4452:                     }
 4453: 		}
 4454: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4455: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4456: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4457: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4458: 		    '&nbsp;<br />';
 4459: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4460: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4461: 		    '&nbsp;<br />';
 4462: 		$question++;
 4463: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4464: 
 4465: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4466: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4467: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4468: 		    if (scalar(keys(%newrecord)) > 0);
 4469: 
 4470: 		$changeflag++;
 4471: 	    }
 4472: 	    if (scalar(keys(%newrecord)) > 0) {
 4473: 		my %record = 
 4474: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4475: 					     $udom,$uname);
 4476: 
 4477: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4478: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4479: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4480: 		    $newrecord{'resource.CODE'} = '';
 4481: 		}
 4482: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4483: 					$udom,$uname);
 4484: 		%record = &Apache::lonnet::restore($symbx,
 4485: 						   $env{'request.course.id'},
 4486: 						   $udom,$uname);
 4487: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4488: 					     $cdom,$cnum,$udom,$uname);
 4489: 	    }
 4490: 	    
 4491:             if ($aggregateflag) {
 4492:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4493:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4494:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4495:             }
 4496: 
 4497: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4498: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4499: 		'</tr>';
 4500: 
 4501: 	    $prob++;
 4502: 	}
 4503:         $curRes = $iterator->next();
 4504:     }
 4505: 
 4506:     $studentTable.='</td></tr></table></td></tr></table>';
 4507:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4508:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
 4509: 		  'The scores were changed for '.
 4510: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
 4511:     $request->print($grademsg.$studentTable);
 4512: 
 4513:     return '';
 4514: }
 4515: 
 4516: #-------- end of section for handling grading by page/sequence ---------
 4517: #
 4518: #-------------------------------------------------------------------
 4519: 
 4520: #--------------------Scantron Grading-----------------------------------
 4521: #
 4522: #------ start of section for handling grading by page/sequence ---------
 4523: 
 4524: =pod
 4525: 
 4526: =head1 Bubble sheet grading routines
 4527: 
 4528:   For this documentation:
 4529: 
 4530:    'scanline' refers to the full line of characters
 4531:    from the file that we are parsing that represents one entire sheet
 4532: 
 4533:    'bubble line' refers to the data
 4534:    representing the line of bubbles that are on the physical bubble sheet
 4535: 
 4536: 
 4537: The overall process is that a scanned in bubble sheet data is uploaded
 4538: into a course. When a user wants to grade, they select a
 4539: sequence/folder of resources, a file of bubble sheet info, and pick
 4540: one of the predefined configurations for what each scanline looks
 4541: like.
 4542: 
 4543: Next each scanline is checked for any errors of either 'missing
 4544: bubbles' (it's an error because it may have been mis-scanned
 4545: because too light bubbling), 'double bubble' (each bubble line should
 4546: have no more that one letter picked), invalid or duplicated CODE,
 4547: invalid student ID
 4548: 
 4549: If the CODE option is used that determines the randomization of the
 4550: homework problems, either way the student ID is looked up into a
 4551: username:domain.
 4552: 
 4553: During the validation phase the instructor can choose to skip scanlines. 
 4554: 
 4555: After the validation phase, there are now 3 bubble sheet files
 4556: 
 4557:   scantron_original_filename (unmodified original file)
 4558:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4559:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4560: 
 4561: Also there is a separate hash nohist_scantrondata that contains extra
 4562: correction information that isn't representable in the bubble sheet
 4563: file (see &scantron_getfile() for more information)
 4564: 
 4565: After all scanlines are either valid, marked as valid or skipped, then
 4566: foreach line foreach problem in the picked sequence, an ssi request is
 4567: made that simulates a user submitting their selected letter(s) against
 4568: the homework problem.
 4569: 
 4570: =over 4
 4571: 
 4572: 
 4573: 
 4574: =item defaultFormData
 4575: 
 4576:   Returns html hidden inputs used to hold context/default values.
 4577: 
 4578:  Arguments:
 4579:   $symb - $symb of the current resource 
 4580: 
 4581: =cut
 4582: 
 4583: sub defaultFormData {
 4584:     my ($symb)=@_;
 4585:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4586:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4587:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4588: }
 4589: 
 4590: 
 4591: =pod 
 4592: 
 4593: =item getSequenceDropDown
 4594: 
 4595:    Return html dropdown of possible sequences to grade
 4596:  
 4597:  Arguments:
 4598:    $symb - $symb of the current resource 
 4599: 
 4600: =cut
 4601: 
 4602: sub getSequenceDropDown {
 4603:     my ($symb)=@_;
 4604:     my $result='<select name="selectpage">'."\n";
 4605:     my ($titles,$symbx) = &getSymbMap();
 4606:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4607:     my $ctr=0;
 4608:     foreach (@$titles) {
 4609: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4610: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4611: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4612: 	    '>'.$showtitle.'</option>'."\n";
 4613: 	$ctr++;
 4614:     }
 4615:     $result.= '</select>';
 4616:     return $result;
 4617: }
 4618: 
 4619: 
 4620: =pod 
 4621: 
 4622: =item scantron_filenames
 4623: 
 4624:    Returns a list of the scantron files in the current course 
 4625: 
 4626: =cut
 4627: 
 4628: sub scantron_filenames {
 4629:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4630:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4631:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4632: 				    &propath($cdom,$cname));
 4633:     my @possiblenames;
 4634:     foreach my $filename (sort(@files)) {
 4635: 	($filename)=split(/&/,$filename);
 4636: 	if ($filename!~/^scantron_orig_/) { next ; }
 4637: 	$filename=~s/^scantron_orig_//;
 4638: 	push(@possiblenames,$filename);
 4639:     }
 4640:     return @possiblenames;
 4641: }
 4642: 
 4643: =pod 
 4644: 
 4645: =item scantron_uploads
 4646: 
 4647:    Returns  html drop-down list of scantron files in current course.
 4648: 
 4649:  Arguments:
 4650:    $file2grade - filename to set as selected in the dropdown
 4651: 
 4652: =cut
 4653: 
 4654: sub scantron_uploads {
 4655:     my ($file2grade) = @_;
 4656:     my $result=	'<select name="scantron_selectfile">';
 4657:     $result.="<option></option>";
 4658:     foreach my $filename (sort(&scantron_filenames())) {
 4659: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4660:     }
 4661:     $result.="</select>";
 4662:     return $result;
 4663: }
 4664: 
 4665: =pod 
 4666: 
 4667: =item scantron_scantab
 4668: 
 4669:   Returns html drop down of the scantron formats in the scantronformat.tab
 4670:   file.
 4671: 
 4672: =cut
 4673: 
 4674: sub scantron_scantab {
 4675:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4676:     my $result='<select name="scantron_format">'."\n";
 4677:     $result.='<option></option>'."\n";
 4678:     foreach my $line (<$fh>) {
 4679: 	my ($name,$descrip)=split(/:/,$line);
 4680: 	if ($name =~ /^\#/) { next; }
 4681: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4682:     }
 4683:     $result.='</select>'."\n";
 4684: 
 4685:     return $result;
 4686: }
 4687: 
 4688: =pod 
 4689: 
 4690: =item scantron_CODElist
 4691: 
 4692:   Returns html drop down of the saved CODE lists from current course,
 4693:   generated from earlier printings.
 4694: 
 4695: =cut
 4696: 
 4697: sub scantron_CODElist {
 4698:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4699:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4700:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4701:     my $namechoice='<option></option>';
 4702:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4703: 	if ($name =~ /^error: 2 /) { next; }
 4704: 	if ($name =~ /^type\0/) { next; }
 4705: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4706:     }
 4707:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4708:     return $namechoice;
 4709: }
 4710: 
 4711: =pod 
 4712: 
 4713: =item scantron_CODEunique
 4714: 
 4715:   Returns the html for "Each CODE to be used once" radio.
 4716: 
 4717: =cut
 4718: 
 4719: sub scantron_CODEunique {
 4720:     my $result='<span style="white-space: nowrap;">
 4721:                  <label><input type="radio" name="scantron_CODEunique"
 4722:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4723:                 </span>
 4724:                 <span style="white-space: nowrap;">
 4725:                  <label><input type="radio" name="scantron_CODEunique"
 4726:                         value="no" />'.&mt('No').' </label>
 4727:                 </span>';
 4728:     return $result;
 4729: }
 4730: 
 4731: =pod 
 4732: 
 4733: =item scantron_selectphase
 4734: 
 4735:   Generates the initial screen to start the bubble sheet process.
 4736:   Allows for - starting a grading run.
 4737:              - downloading existing scan data (original, corrected
 4738:                                                 or skipped info)
 4739: 
 4740:              - uploading new scan data
 4741: 
 4742:  Arguments:
 4743:   $r          - The Apache request object
 4744:   $file2grade - name of the file that contain the scanned data to score
 4745: 
 4746: =cut
 4747: 
 4748: sub scantron_selectphase {
 4749:     my ($r,$file2grade) = @_;
 4750:     my ($symb)=&get_symb($r);
 4751:     if (!$symb) {return '';}
 4752:     my $sequence_selector=&getSequenceDropDown($symb);
 4753:     my $default_form_data=&defaultFormData($symb);
 4754:     my $grading_menu_button=&show_grading_menu_form($symb);
 4755:     my $file_selector=&scantron_uploads($file2grade);
 4756:     my $format_selector=&scantron_scantab();
 4757:     my $CODE_selector=&scantron_CODElist();
 4758:     my $CODE_unique=&scantron_CODEunique();
 4759:     my $result;
 4760: 
 4761:     # Chunk of form to prompt for a file to grade and how:
 4762: 
 4763:     $result.= <<SCANTRONFORM;
 4764:     <table width="100%" border="0">
 4765:     <tr>
 4766:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 4767:       <td bgcolor="#777777">
 4768:        <input type="hidden" name="command" value="scantron_warning" />
 4769:         $default_form_data
 4770:         <table width="100%" border="0">
 4771:           <tr bgcolor="#e6ffff">
 4772:             <td colspan="2">
 4773:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
 4774:             </td>
 4775:           </tr>
 4776:           <tr bgcolor="#ffffe6">
 4777:             <td> Sequence to grade: </td><td> $sequence_selector </td>
 4778:           </tr>
 4779:           <tr bgcolor="#ffffe6">
 4780:             <td> Filename of scoring office file: </td><td> $file_selector </td>
 4781:           </tr>
 4782:           <tr bgcolor="#ffffe6">
 4783:             <td> Format of data file: </td><td> $format_selector </td>
 4784:           </tr>
 4785:           <tr bgcolor="#ffffe6">
 4786:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
 4787:           </tr>
 4788:           <tr bgcolor="#ffffe6">
 4789:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
 4790:           </tr>
 4791:           <tr bgcolor="#ffffe6">
 4792: 	    <td> Options: </td>
 4793:             <td>
 4794: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
 4795:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
 4796:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
 4797: 	    </td>
 4798:           </tr>
 4799:           <tr bgcolor="#ffffe6">
 4800:             <td colspan="2">
 4801:               <input type="submit" value="Grading: Validate Scantron Records" />
 4802:             </td>
 4803:           </tr>
 4804:         </table>
 4805:        </td>
 4806:      </form>
 4807:     </tr>
 4808: SCANTRONFORM
 4809:    
 4810:     $r->print($result);
 4811: 
 4812:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 4813:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 4814: 
 4815: 	# Chunk of form to prompt for a scantron file upload.
 4816: 
 4817:         $r->print(<<SCANTRONFORM);
 4818:     <tr>
 4819:       <td bgcolor="#777777">
 4820:         <table width="100%" border="0">
 4821:           <tr bgcolor="#e6ffff">
 4822:             <td>
 4823:               &nbsp;<b>Specify a Scantron data file to upload.</b>
 4824:             </td>
 4825:           </tr>
 4826:           <tr bgcolor="#ffffe6">
 4827:             <td>
 4828: SCANTRONFORM
 4829:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 4830:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4831:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 4832:     $r->print(<<UPLOAD);
 4833:               <script type="text/javascript" language="javascript">
 4834:     function checkUpload(formname) {
 4835: 	if (formname.upfile.value == "") {
 4836: 	    alert("Please use the browse button to select a file from your local directory.");
 4837: 	    return false;
 4838: 	}
 4839: 	formname.submit();
 4840:     }
 4841:               </script>
 4842: 
 4843:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 4844:                 $default_form_data
 4845:                 <input name='courseid' type='hidden' value='$cnum' />
 4846:                 <input name='domainid' type='hidden' value='$cdom' />
 4847:                 <input name='command' value='scantronupload_save' type='hidden' />
 4848:                 File to upload:<input type="file" name="upfile" size="50" />
 4849:                 <br />
 4850:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 4851:               </form>
 4852: UPLOAD
 4853: 
 4854:         $r->print(<<SCANTRONFORM);
 4855:             </td>
 4856:           </tr>
 4857:         </table>
 4858:       </td>
 4859:     </tr>
 4860: SCANTRONFORM
 4861:     }
 4862: 
 4863:     # Chunk of the form that prompts to view a scoring office file,
 4864:     # corrected file, skipped records in a file.
 4865: 
 4866:     $r->print(<<SCANTRONFORM);
 4867:     <tr>
 4868:       <form action='/adm/grades' name='scantron_download'>
 4869:         <td bgcolor="#777777">
 4870: 	  $default_form_data
 4871:           <input type="hidden" name="command" value="scantron_download" />
 4872:           <table width="100%" border="0">
 4873:             <tr bgcolor="#e6ffff">
 4874:               <td colspan="2">
 4875:                 &nbsp;<b>Download a scoring office file</b>
 4876:               </td>
 4877:             </tr>
 4878:             <tr bgcolor="#ffffe6">
 4879:               <td> Filename of scoring office file: </td><td> $file_selector </td>
 4880:             </tr>
 4881:             <tr bgcolor="#ffffe6">
 4882:               <td colspan="2">
 4883:                 <input type="submit" value="Download: Show List of Associated Files" />
 4884:               </td>
 4885:             </tr>
 4886:           </table>
 4887:         </td>
 4888:       </form>
 4889:     </tr>
 4890: SCANTRONFORM
 4891: 
 4892:     $r->print(<<SCANTRONFORM);
 4893:   </table>
 4894: $grading_menu_button
 4895: SCANTRONFORM
 4896: 
 4897:     return
 4898: }
 4899: 
 4900: =pod
 4901: 
 4902: =item get_scantron_config
 4903: 
 4904:    Parse and return the scantron configuration line selected as a
 4905:    hash of configuration file fields.
 4906: 
 4907:  Arguments:
 4908:     which - the name of the configuration to parse from the file.
 4909: 
 4910: 
 4911:  Returns:
 4912:             If the named configuration is not in the file, an empty
 4913:             hash is returned.
 4914:     a hash with the fields
 4915:       name         - internal name for the this configuration setup
 4916:       description  - text to display to operator that describes this config
 4917:       CODElocation - if 0 or the string 'none'
 4918:                           - no CODE exists for this config
 4919:                      if -1 || the string 'letter'
 4920:                           - a CODE exists for this config and is
 4921:                             a string of letters
 4922:                      Unsupported value (but planned for future support)
 4923:                           if a positive integer
 4924:                                - The CODE exists as the first n items from
 4925:                                  the question section of the form
 4926:                           if the string 'number'
 4927:                                - The CODE exists for this config and is
 4928:                                  a string of numbers
 4929:       CODEstart   - (only matter if a CODE exists) column in the line where
 4930:                      the CODE starts
 4931:       CODElength  - length of the CODE
 4932:       IDstart     - column where the student ID number starts
 4933:       IDlength    - length of the student ID info
 4934:       Qstart      - column where the information from the bubbled
 4935:                     'questions' start
 4936:       Qlength     - number of columns comprising a single bubble line from
 4937:                     the sheet. (usually either 1 or 10)
 4938:       Qon         - either a single character representing the character used
 4939:                     to signal a bubble was chosen in the positional setup, or
 4940:                     the string 'letter' if the letter of the chosen bubble is
 4941:                     in the final, or 'number' if a number representing the
 4942:                     chosen bubble is in the file (1->A 0->J)
 4943:       Qoff        - the character used to represent that a bubble was
 4944:                     left blank
 4945:       PaperID     - if the scanning process generates a unique number for each
 4946:                     sheet scanned the column that this ID number starts in
 4947:       PaperIDlength - number of columns that comprise the unique ID number
 4948:                       for the sheet of paper
 4949:       FirstName   - column that the first name starts in
 4950:       FirstNameLength - number of columns that the first name spans
 4951:  
 4952:       LastName    - column that the last name starts in
 4953:       LastNameLength - number of columns that the last name spans
 4954: 
 4955: =cut
 4956: 
 4957: sub get_scantron_config {
 4958:     my ($which) = @_;
 4959:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4960:     my %config;
 4961:     #FIXME probably should move to XML it has already gotten a bit much now
 4962:     foreach my $line (<$fh>) {
 4963: 	my ($name,$descrip)=split(/:/,$line);
 4964: 	if ($name ne $which ) { next; }
 4965: 	chomp($line);
 4966: 	my @config=split(/:/,$line);
 4967: 	$config{'name'}=$config[0];
 4968: 	$config{'description'}=$config[1];
 4969: 	$config{'CODElocation'}=$config[2];
 4970: 	$config{'CODEstart'}=$config[3];
 4971: 	$config{'CODElength'}=$config[4];
 4972: 	$config{'IDstart'}=$config[5];
 4973: 	$config{'IDlength'}=$config[6];
 4974: 	$config{'Qstart'}=$config[7];
 4975: 	$config{'Qlength'}=$config[8];
 4976: 	$config{'Qoff'}=$config[9];
 4977: 	$config{'Qon'}=$config[10];
 4978: 	$config{'PaperID'}=$config[11];
 4979: 	$config{'PaperIDlength'}=$config[12];
 4980: 	$config{'FirstName'}=$config[13];
 4981: 	$config{'FirstNamelength'}=$config[14];
 4982: 	$config{'LastName'}=$config[15];
 4983: 	$config{'LastNamelength'}=$config[16];
 4984: 	last;
 4985:     }
 4986:     return %config;
 4987: }
 4988: 
 4989: =pod 
 4990: 
 4991: =item username_to_idmap
 4992: 
 4993:     creates a hash keyed by student id with values of the corresponding
 4994:     student username:domain.
 4995: 
 4996:   Arguments:
 4997: 
 4998:     $classlist - reference to the class list hash. This is a hash
 4999:                  keyed by student name:domain  whose elements are references
 5000:                  to arrays containing various chunks of information
 5001:                  about the student. (See loncoursedata for more info).
 5002: 
 5003:   Returns
 5004:     %idmap - the constructed hash
 5005: 
 5006: =cut
 5007: 
 5008: sub username_to_idmap {
 5009:     my ($classlist)= @_;
 5010:     my %idmap;
 5011:     foreach my $student (keys(%$classlist)) {
 5012: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5013: 	    $student;
 5014:     }
 5015:     return %idmap;
 5016: }
 5017: 
 5018: =pod
 5019: 
 5020: =item scantron_fixup_scanline
 5021: 
 5022:    Process a requested correction to a scanline.
 5023: 
 5024:   Arguments:
 5025:     $scantron_config   - hash from &get_scantron_config()
 5026:     $scan_data         - hash of correction information 
 5027:                           (see &scantron_getfile())
 5028:     $line              - existing scanline
 5029:     $whichline         - line number of the passed in scanline
 5030:     $field             - type of change to process 
 5031:                          (either 
 5032:                           'ID'     -> correct the student ID number
 5033:                           'CODE'   -> correct the CODE
 5034:                           'answer' -> fixup the submitted answers)
 5035:     
 5036:    $args               - hash of additional info,
 5037:                           - 'ID' 
 5038:                                'newid' -> studentID to use in replacement
 5039:                                           of existing one
 5040:                           - 'CODE' 
 5041:                                'CODE_ignore_dup' - set to true if duplicates
 5042:                                                    should be ignored.
 5043: 	                       'CODE' - is new code or 'use_unfound'
 5044:                                         if the existing unfound code should
 5045:                                         be used as is
 5046:                           - 'answer'
 5047:                                'response' - new answer or 'none' if blank
 5048:                                'question' - the bubble line to change
 5049: 
 5050:   Returns:
 5051:     $line - the modified scanline
 5052: 
 5053:   Side effects: 
 5054:     $scan_data - may be updated
 5055: 
 5056: =cut
 5057: 
 5058: 
 5059: sub scantron_fixup_scanline {
 5060:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5061: 
 5062:     if ($field eq 'ID') {
 5063: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5064: 	    return ($line,1,'New value too large');
 5065: 	}
 5066: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5067: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5068: 				     $args->{'newid'});
 5069: 	}
 5070: 	substr($line,$$scantron_config{'IDstart'}-1,
 5071: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5072: 	if ($args->{'newid'}=~/^\s*$/) {
 5073: 	    &scan_data($scan_data,"$whichline.user",
 5074: 		       $args->{'username'}.':'.$args->{'domain'});
 5075: 	}
 5076:     } elsif ($field eq 'CODE') {
 5077: 	if ($args->{'CODE_ignore_dup'}) {
 5078: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5079: 	}
 5080: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5081: 	if ($args->{'CODE'} ne 'use_unfound') {
 5082: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5083: 		return ($line,1,'New CODE value too large');
 5084: 	    }
 5085: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5086: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5087: 	    }
 5088: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5089: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5090: 	}
 5091:     } elsif ($field eq 'answer') {
 5092: 	my $length=$scantron_config->{'Qlength'};
 5093: 	my $off=$scantron_config->{'Qoff'};
 5094: 	my $on=$scantron_config->{'Qon'};
 5095: 	my $answer=${off}x$length;
 5096: 	if ($args->{'response'} eq 'none') {
 5097: 	    &scan_data($scan_data,
 5098: 		       "$whichline.no_bubble.".$args->{'question'},'1');
 5099: 	} else {
 5100: 	    if ($on eq 'letter') {
 5101: 		my @alphabet=('A'..'Z');
 5102: 		$answer=$alphabet[$args->{'response'}];
 5103: 	    } elsif ($on eq 'number') {
 5104: 		$answer=$args->{'response'}+1;
 5105: 		if ($answer == 10) { $answer = '0'; }
 5106: 	    } else {
 5107: 		substr($answer,$args->{'response'},1)=$on;
 5108: 	    }
 5109: 	    &scan_data($scan_data,
 5110: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
 5111: 	}
 5112: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5113: 	substr($line,$where-1,$length)=$answer;
 5114:     }
 5115:     return $line;
 5116: }
 5117: 
 5118: =pod
 5119: 
 5120: =item scan_data
 5121: 
 5122:     Edit or look up  an item in the scan_data hash.
 5123: 
 5124:   Arguments:
 5125:     $scan_data  - The hash (see scantron_getfile)
 5126:     $key        - shorthand of the key to edit (actual key is
 5127:                   scantronfilename_key).
 5128:     $data        - New value of the hash entry.
 5129:     $delete      - If true, the entry is removed from the hash.
 5130: 
 5131:   Returns:
 5132:     The new value of the hash table field (undefined if deleted).
 5133: 
 5134: =cut
 5135: 
 5136: 
 5137: sub scan_data {
 5138:     my ($scan_data,$key,$value,$delete)=@_;
 5139:     my $filename=$env{'form.scantron_selectfile'};
 5140:     if (defined($value)) {
 5141: 	$scan_data->{$filename.'_'.$key} = $value;
 5142:     }
 5143:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5144:     return $scan_data->{$filename.'_'.$key};
 5145: }
 5146: 
 5147: =pod 
 5148: 
 5149: =item scantron_parse_scanline
 5150: 
 5151:   Decodes a scanline from the selected scantron file
 5152: 
 5153:  Arguments:
 5154:     line             - The text of the scantron file line to process
 5155:     whichline        - Line number
 5156:     scantron_config  - Hash describing the format of the scantron lines.
 5157:     scan_data        - Hash of extra information about the scanline
 5158:                        (see scantron_getfile for more information)
 5159:     just_header      - True if should not process question answers but only
 5160:                        the stuff to the left of the answers.
 5161:  Returns:
 5162:    Hash containing the result of parsing the scanline
 5163: 
 5164:    Keys are all proceeded by the string 'scantron.'
 5165: 
 5166:        CODE    - the CODE in use for this scanline
 5167:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5168:                  by the operator
 5169:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5170:                             CODEs were selected, but the usage has been
 5171:                             forced by the operator
 5172:        ID  - student ID
 5173:        PaperID - if used, the ID number printed on the sheet when the 
 5174:                  paper was scanned
 5175:        FirstName - first name from the sheet
 5176:        LastName  - last name from the sheet
 5177: 
 5178:      if just_header was not true these key may also exist
 5179: 
 5180:        missingerror - a list of bubble ranges that are considered to be answers
 5181:                       to a single question that don't have any bubbles filled in.
 5182:                       Of the form questionnumber:firstbubblenumber:count.
 5183:        doubleerror  - a list of bubble ranges that are considered to be answers
 5184:                       to a single question that have more than one bubble filled in.
 5185:                       Of the form questionnumber::firstbubblenumber:count
 5186:    
 5187:                 In the above, count is the number of bubble responses in the
 5188:                 input line needed to represent the possible answers to the question.
 5189:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5190:                 per line would have count = 2.
 5191: 
 5192:        maxquest     - the number of the last bubble line that was parsed
 5193: 
 5194:        (<number> starts at 1)
 5195:        <number>.answer - zero or more letters representing the selected
 5196:                          letters from the scanline for the bubble line 
 5197:                          <number>.
 5198:                          if blank there was either no bubble or there where
 5199:                          multiple bubbles, (consult the keys missingerror and
 5200:                          doubleerror if this is an error condition)
 5201: 
 5202: =cut
 5203: 
 5204: sub scantron_parse_scanline {
 5205:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5206:     my %record;
 5207:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5208:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5209:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5210: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5211: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5212: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5213: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5214: 	    $record{'scantron.CODE'}=substr($data,
 5215: 					    $$scantron_config{'CODEstart'}-1,
 5216: 					    $$scantron_config{'CODElength'});
 5217: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5218: 		$record{'scantron.useCODE'}=1;
 5219: 	    }
 5220: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5221: 		$record{'scantron.CODE_ignore_dup'}=1;
 5222: 	    }
 5223: 	} else {
 5224: 	    #FIXME interpret first N questions
 5225: 	}
 5226:     }
 5227:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5228: 				  $$scantron_config{'IDlength'});
 5229:     $record{'scantron.PaperID'}=
 5230: 	substr($data,$$scantron_config{'PaperID'}-1,
 5231: 	       $$scantron_config{'PaperIDlength'});
 5232:     $record{'scantron.FirstName'}=
 5233: 	substr($data,$$scantron_config{'FirstName'}-1,
 5234: 	       $$scantron_config{'FirstNamelength'});
 5235:     $record{'scantron.LastName'}=
 5236: 	substr($data,$$scantron_config{'LastName'}-1,
 5237: 	       $$scantron_config{'LastNamelength'});
 5238:     if ($just_header) { return \%record; }
 5239: 
 5240:     my @alphabet=('A'..'Z');
 5241:     my $questnum=0;
 5242:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5243: 
 5244:     while ($questions) {
 5245: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5246: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
 5247: 
 5248: 
 5249: 
 5250: 	$questnum++;
 5251: 	my $currentquest = substr($questions,0,$answer_length);
 5252: 	$questions       = substr($questions,0,$answer_length)='';
 5253: 	if (length($currentquest) < $answer_length) { next; }
 5254: 
 5255: 	# Qon letter implies for each slot in currentquest we have:
 5256: 	#    ? or * for doubles a letter in A-Z for a bubble and
 5257:         #    about anything else (esp. a value of Qoff for missing
 5258: 	#    bubbles.
 5259: 
 5260: 
 5261: 	if ($$scantron_config{'Qon'} eq 'letter') {
 5262: 
 5263: 	    if ($currentquest =~ /\?/
 5264: 		|| $currentquest =~ /\*/
 5265: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
 5266: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5267: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
 5268: 		    $record{"scantron.$ansnum.answer"}='';
 5269: 		    $ansnum++;
 5270: 		}
 5271: 
 5272: 	    } elsif (!defined($currentquest)
 5273: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
 5274: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
 5275: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5276: 		    $record{"scantron.$ansnum.answer"}='';
 5277: 		    $ansnum++;
 5278: 
 5279: 		}
 5280: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5281: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5282: 		    $ansnum += $answers_needed;
 5283: 		}
 5284: 
 5285: 	    } else {
 5286: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5287: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
 5288: 		    $ansnum++;
 5289: 		}
 5290: 	    }
 5291: 
 5292: 	# Qon 'number' implies each slot gives a digit that indexes the
 5293: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
 5294:         #    and *? for double bubbles on a line.
 5295: 	#    these answers are also stored as letters.
 5296: 
 5297: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
 5298: 	    if ($currentquest =~ /\?/
 5299: 		|| $currentquest =~ /\*/
 5300: 		|| (&occurence_count($currentquest, '\d') > 1)) {
 5301: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5302: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5303: 		    $record{"scantron.$ansnum.answer"}='';
 5304: 		    $ansnum++;
 5305: 		}
 5306: 
 5307: 	    } elsif (!defined($currentquest)
 5308: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
 5309: 		     || (&occurence_count($currentquest, '\d') == 0)) {
 5310: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5311: 		    $record{"scantron.$ansnum.answer"}='';
 5312: 		    $ansnum++;
 5313: 
 5314: 		}
 5315: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5316: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5317: 		    $ansnum += $answers_needed;
 5318: 		}
 5319: 
 5320: 	    } else {
 5321: 		$currentquest = &digits_to_letters($currentquest);
 5322: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
 5323: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
 5324: 		    $ansnum++;
 5325: 		}
 5326: 	    }
 5327: 	} else {
 5328: 
 5329: 	    # Otherwise there's a positional notation;
 5330: 	    # each bubble line requires Qlength items, and there are filled in
 5331: 	    # bubbles for each case where there 'Qon' characters.
 5332: 	    #
 5333: 
 5334: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
 5335: 
 5336: 	    # If the split only  giveas us one element.. the full length of the
 5337: 	    # answser string, no bubbles are filled in:
 5338: 
 5339: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5340: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5341: 		    $record{"scantron.$ansnum.answer"}='';
 5342: 		    $ansnum++;
 5343: 
 5344: 		}
 5345: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5346: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5347: 		}
 5348: 	    } elsif (scalar(@array) lt 2) {
 5349: 
 5350: 		my $location      = [length($array[0])];
 5351: 		my $line_num      = $location / $$scantron_config{'Qlength'};
 5352: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
 5353: 
 5354: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5355: 		    if ($ans eq $line_num) {
 5356: 			$record{"scantron.$ansnum.answer"} = $bubble;
 5357: 		    } else {
 5358: 			$record{"scantron.$ansnum.answer"} = ' ';
 5359: 		    }
 5360: 		    $ansnum++;
 5361: 		}
 5362: 	    }
 5363: 	    #  If there's more than one instance of a bubble character
 5364: 	    #  That's a double bubble; with positional notation we can
 5365: 	    #  record all the bubbles filled in as well as the 
 5366: 	    #  fact this response consists of multiple bubbles.
 5367: 	    #
 5368: 	    else {
 5369: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5370: 
 5371: 		my $first_answer = $ansnum;
 5372: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
 5373: 		    $record{"scantron.$ansnum.answer"} = '';
 5374: 		    $ans++;
 5375: 		}
 5376: 
 5377: 		my @ans=@array;
 5378: 		my $i=length($ans[0]);shift(@ans);
 5379: 		while ($#ans) {
 5380: 		    $i+=length($ans[0])+1;
 5381: 		    my $line   = $i/$$scantron_config{'Qlength'} + $first_answer;
 5382: 		    my $bubble = $i%$$scantron_config{'Qlength'};
 5383: 
 5384: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
 5385: 		    shift(@ans);
 5386: 		}
 5387: 	    }
 5388: 	}
 5389:     }
 5390:     $record{'scantron.maxquest'}=$questnum;
 5391:     return \%record;
 5392: }
 5393: 
 5394: =pod
 5395: 
 5396: =item scantron_add_delay
 5397: 
 5398:    Adds an error message that occurred during the grading phase to a
 5399:    queue of messages to be shown after grading pass is complete
 5400: 
 5401:  Arguments:
 5402:    $delayqueue  - arrary ref of hash ref of error messages
 5403:    $scanline    - the scanline that caused the error
 5404:    $errormesage - the error message
 5405:    $errorcode   - a numeric code for the error
 5406: 
 5407:  Side Effects:
 5408:    updates the $delayqueue to have a new hash ref of the error
 5409: 
 5410: =cut
 5411: 
 5412: sub scantron_add_delay {
 5413:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5414:     push(@$delayqueue,
 5415: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5416: 	  'ecode' => $errorcode }
 5417: 	 );
 5418: }
 5419: 
 5420: =pod
 5421: 
 5422: =item scantron_find_student
 5423: 
 5424:    Finds the username for the current scanline
 5425: 
 5426:   Arguments:
 5427:    $scantron_record - hash result from scantron_parse_scanline
 5428:    $scan_data       - hash of correction information 
 5429:                       (see &scantron_getfile() form more information)
 5430:    $idmap           - hash from &username_to_idmap()
 5431:    $line            - number of current scanline
 5432:  
 5433:   Returns:
 5434:    Either 'username:domain' or undef if unknown
 5435: 
 5436: =cut
 5437: 
 5438: sub scantron_find_student {
 5439:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5440:     my $scanID=$$scantron_record{'scantron.ID'};
 5441:     if ($scanID =~ /^\s*$/) {
 5442:  	return &scan_data($scan_data,"$line.user");
 5443:     }
 5444:     foreach my $id (keys(%$idmap)) {
 5445:  	if (lc($id) eq lc($scanID)) {
 5446:  	    return $$idmap{$id};
 5447:  	}
 5448:     }
 5449:     return undef;
 5450: }
 5451: 
 5452: =pod
 5453: 
 5454: =item scantron_filter
 5455: 
 5456:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5457:    hidden resources was selected
 5458: 
 5459: =cut
 5460: 
 5461: sub scantron_filter {
 5462:     my ($curres)=@_;
 5463: 
 5464:     if (ref($curres) && $curres->is_problem()) {
 5465: 	# if the user has asked to not have either hidden
 5466: 	# or 'randomout' controlled resources to be graded
 5467: 	# don't include them
 5468: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5469: 	    && $curres->randomout) {
 5470: 	    return 0;
 5471: 	}
 5472: 	return 1;
 5473:     }
 5474:     return 0;
 5475: }
 5476: 
 5477: =pod
 5478: 
 5479: =item scantron_process_corrections
 5480: 
 5481:    Gets correction information out of submitted form data and corrects
 5482:    the scanline
 5483: 
 5484: =cut
 5485: 
 5486: sub scantron_process_corrections {
 5487:     my ($r) = @_;
 5488:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5489:     my ($scanlines,$scan_data)=&scantron_getfile();
 5490:     my $classlist=&Apache::loncoursedata::get_classlist();
 5491:     my $which=$env{'form.scantron_line'};
 5492:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5493:     my ($skip,$err,$errmsg);
 5494:     if ($env{'form.scantron_skip_record'}) {
 5495: 	$skip=1;
 5496:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5497: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5498: 	    $env{'form.scantron_domain'};
 5499: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5500: 	($line,$err,$errmsg)=
 5501: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5502: 				     'ID',{'newid'=>$newid,
 5503: 				    'username'=>$env{'form.scantron_username'},
 5504: 				    'domain'=>$env{'form.scantron_domain'}});
 5505:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5506: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5507: 	my $newCODE;
 5508: 	my %args;
 5509: 	if      ($resolution eq 'use_unfound') {
 5510: 	    $newCODE='use_unfound';
 5511: 	} elsif ($resolution eq 'use_found') {
 5512: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5513: 	} elsif ($resolution eq 'use_typed') {
 5514: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5515: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5516: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5517: 	}
 5518: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5519: 	    $args{'CODE_ignore_dup'}=1;
 5520: 	}
 5521: 	$args{'CODE'}=$newCODE;
 5522: 	($line,$err,$errmsg)=
 5523: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5524: 				     'CODE',\%args);
 5525:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5526: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5527: 	    ($line,$err,$errmsg)=
 5528: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5529: 					 $which,'answer',
 5530: 					 { 'question'=>$question,
 5531: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
 5532: 	    if ($err) { last; }
 5533: 	}
 5534:     }
 5535:     if ($err) {
 5536: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5537:     } else {
 5538: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5539: 	&scantron_putfile($scanlines,$scan_data);
 5540:     }
 5541: }
 5542: 
 5543: =pod
 5544: 
 5545: =item reset_skipping_status
 5546: 
 5547:    Forgets the current set of remember skipped scanlines (and thus
 5548:    reverts back to considering all lines in the
 5549:    scantron_skipped_<filename> file)
 5550: 
 5551: =cut
 5552: 
 5553: sub reset_skipping_status {
 5554:     my ($scanlines,$scan_data)=&scantron_getfile();
 5555:     &scan_data($scan_data,'remember_skipping',undef,1);
 5556:     &scantron_putfile(undef,$scan_data);
 5557: }
 5558: 
 5559: =pod
 5560: 
 5561: =item start_skipping
 5562: 
 5563:    Marks a scanline to be skipped. 
 5564: 
 5565: =cut
 5566: 
 5567: sub start_skipping {
 5568:     my ($scan_data,$i)=@_;
 5569:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5570:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5571: 	$remembered{$i}=2;
 5572:     } else {
 5573: 	$remembered{$i}=1;
 5574:     }
 5575:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5576: }
 5577: 
 5578: =pod
 5579: 
 5580: =item should_be_skipped
 5581: 
 5582:    Checks whether a scanline should be skipped.
 5583: 
 5584: =cut
 5585: 
 5586: sub should_be_skipped {
 5587:     my ($scanlines,$scan_data,$i)=@_;
 5588:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5589: 	# not redoing old skips
 5590: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5591: 	return 0;
 5592:     }
 5593:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5594: 
 5595:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5596: 	return 0;
 5597:     }
 5598:     return 1;
 5599: }
 5600: 
 5601: =pod
 5602: 
 5603: =item remember_current_skipped
 5604: 
 5605:    Discovers what scanlines are in the scantron_skipped_<filename>
 5606:    file and remembers them into scan_data for later use.
 5607: 
 5608: =cut
 5609: 
 5610: sub remember_current_skipped {
 5611:     my ($scanlines,$scan_data)=&scantron_getfile();
 5612:     my %to_remember;
 5613:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 5614: 	if ($scanlines->{'skipped'}[$i]) {
 5615: 	    $to_remember{$i}=1;
 5616: 	}
 5617:     }
 5618: 
 5619:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 5620:     &scantron_putfile(undef,$scan_data);
 5621: }
 5622: 
 5623: =pod
 5624: 
 5625: =item check_for_error
 5626: 
 5627:     Checks if there was an error when attempting to remove a specific
 5628:     scantron_.. bubble sheet data file. Prints out an error if
 5629:     something went wrong.
 5630: 
 5631: =cut
 5632: 
 5633: sub check_for_error {
 5634:     my ($r,$result)=@_;
 5635:     if ($result ne 'ok' && $result ne 'not_found' ) {
 5636: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
 5637:     }
 5638: }
 5639: 
 5640: =pod
 5641: 
 5642: =item scantron_warning_screen
 5643: 
 5644:    Interstitial screen to make sure the operator has selected the
 5645:    correct options before we start the validation phase.
 5646: 
 5647: =cut
 5648: 
 5649: sub scantron_warning_screen {
 5650:     my ($button_text)=@_;
 5651:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 5652:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5653:     my $CODElist;
 5654:     if ($scantron_config{'CODElocation'} &&
 5655: 	$scantron_config{'CODEstart'} &&
 5656: 	$scantron_config{'CODElength'}) {
 5657: 	$CODElist=$env{'form.scantron_CODElist'};
 5658: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 5659: 	$CODElist=
 5660: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
 5661: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 5662:     }
 5663:     return (<<STUFF);
 5664: <p>
 5665: <span class="LC_warning">Please double check the information
 5666:                  below before clicking on '$button_text'</span>
 5667: </p>
 5668: <table>
 5669: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
 5670: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
 5671: $CODElist
 5672: </table>
 5673: <br />
 5674: <p> If this information is correct, please click on '$button_text'.</p>
 5675: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
 5676: 
 5677: <br />
 5678: STUFF
 5679: }
 5680: 
 5681: =pod
 5682: 
 5683: =item scantron_do_warning
 5684: 
 5685:    Check if the operator has picked something for all required
 5686:    fields. Error out if something is missing.
 5687: 
 5688: =cut
 5689: 
 5690: sub scantron_do_warning {
 5691:     my ($r)=@_;
 5692:     my ($symb)=&get_symb($r);
 5693:     if (!$symb) {return '';}
 5694:     my $default_form_data=&defaultFormData($symb);
 5695:     $r->print(&scantron_form_start().$default_form_data);
 5696:     if ( $env{'form.selectpage'} eq '' ||
 5697: 	 $env{'form.scantron_selectfile'} eq '' ||
 5698: 	 $env{'form.scantron_format'} eq '' ) {
 5699: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
 5700: 	if ( $env{'form.selectpage'} eq '') {
 5701: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
 5702: 	} 
 5703: 	if ( $env{'form.scantron_selectfile'} eq '') {
 5704: 	    $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
 5705: 	} 
 5706: 	if ( $env{'form.scantron_format'} eq '') {
 5707: 	    $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
 5708: 	} 
 5709:     } else {
 5710: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 5711: 	$r->print(<<STUFF);
 5712: $warning
 5713: <input type="submit" name="submit" value="Grading: Validate Records" />
 5714: <input type="hidden" name="command" value="scantron_validate" />
 5715: STUFF
 5716:     }
 5717:     $r->print("</form><br />".&show_grading_menu_form($symb));
 5718:     return '';
 5719: }
 5720: 
 5721: =pod
 5722: 
 5723: =item scantron_form_start
 5724: 
 5725:     html hidden input for remembering all selected grading options
 5726: 
 5727: =cut
 5728: 
 5729: sub scantron_form_start {
 5730:     my ($max_bubble)=@_;
 5731:     my $result= <<SCANTRONFORM;
 5732: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 5733:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 5734:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 5735:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 5736:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 5737:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 5738:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 5739:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 5740:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 5741:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 5742: SCANTRONFORM
 5743: 
 5744:   my $line = 0;
 5745:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 5746: 	&Apache::lonnet::logthis("Saving chunk for $line");
 5747:        my $chunk =
 5748: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 5749:        $chunk .=
 5750: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 5751:        $result .= $chunk;
 5752:        $line++;
 5753:    }
 5754:     return $result;
 5755: }
 5756: 
 5757: =pod
 5758: 
 5759: =item scantron_validate_file
 5760: 
 5761:     Dispatch routine for doing validation of a bubble sheet data file.
 5762: 
 5763:     Also processes any necessary information resets that need to
 5764:     occur before validation begins (ignore previous corrections,
 5765:     restarting the skipped records processing)
 5766: 
 5767: =cut
 5768: 
 5769: sub scantron_validate_file {
 5770:     my ($r) = @_;
 5771:     my ($symb)=&get_symb($r);
 5772:     if (!$symb) {return '';}
 5773:     my $default_form_data=&defaultFormData($symb);
 5774:     
 5775:     # do the detection of only doing skipped records first befroe we delete
 5776:     # them when doing the corrections reset
 5777:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 5778: 	&reset_skipping_status();
 5779:     }
 5780:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 5781: 	&remember_current_skipped();
 5782: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 5783:     }
 5784: 
 5785:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 5786: 	&check_for_error($r,&scantron_remove_file('corrected'));
 5787: 	&check_for_error($r,&scantron_remove_file('skipped'));
 5788: 	&check_for_error($r,&scantron_remove_scan_data());
 5789: 	$env{'form.scantron_options_ignore'}='done';
 5790:     }
 5791: 
 5792:     if ($env{'form.scantron_corrections'}) {
 5793: 	&scantron_process_corrections($r);
 5794:     }
 5795:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
 5796:     #get the student pick code ready
 5797:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 5798:     my $max_bubble=&scantron_get_maxbubble();
 5799:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 5800:     $r->print($result);
 5801:     
 5802:     my @validate_phases=( 'sequence',
 5803: 			  'ID',
 5804: 			  'CODE',
 5805: 			  'doublebubble',
 5806: 			  'missingbubbles');
 5807:     if (!$env{'form.validatepass'}) {
 5808: 	$env{'form.validatepass'} = 0;
 5809:     }
 5810:     my $currentphase=$env{'form.validatepass'};
 5811: 
 5812:     &Apache::lonnet::logthis("Phase: $currentphase");
 5813: 
 5814:     my $stop=0;
 5815:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 5816: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
 5817: 	$r->rflush();
 5818: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 5819: 	{
 5820: 	    no strict 'refs';
 5821: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 5822: 	}
 5823:     }
 5824:     if (!$stop) {
 5825: 	my $warning=&scantron_warning_screen('Start Grading');
 5826: 	$r->print(<<STUFF);
 5827: Validation process complete.<br />
 5828: $warning
 5829: <input type="submit" name="submit" value="Start Grading" />
 5830: <input type="hidden" name="command" value="scantron_process" />
 5831: STUFF
 5832: 
 5833:     } else {
 5834: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 5835: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 5836:     }
 5837:     if ($stop) {
 5838: 	if ($validate_phases[$currentphase] eq 'sequence') {
 5839: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
 5840: 	    $r->print(' this error <br />');
 5841: 
 5842: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
 5843: 	} else {
 5844: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
 5845: 	    $r->print(' using corrected info <br />');
 5846: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
 5847: 	    $r->print(" this scanline saving it for later.");
 5848: 	}
 5849:     }
 5850:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 5851:     return '';
 5852: }
 5853: 
 5854: 
 5855: =pod
 5856: 
 5857: =item scantron_remove_file
 5858: 
 5859:    Removes the requested bubble sheet data file, makes sure that
 5860:    scantron_original_<filename> is never removed
 5861: 
 5862: 
 5863: =cut
 5864: 
 5865: sub scantron_remove_file {
 5866:     my ($which)=@_;
 5867:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5868:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5869:     my $file='scantron_';
 5870:     if ($which eq 'corrected' || $which eq 'skipped') {
 5871: 	$file.=$which.'_';
 5872:     } else {
 5873: 	return 'refused';
 5874:     }
 5875:     $file.=$env{'form.scantron_selectfile'};
 5876:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 5877: }
 5878: 
 5879: 
 5880: =pod
 5881: 
 5882: =item scantron_remove_scan_data
 5883: 
 5884:    Removes all scan_data correction for the requested bubble sheet
 5885:    data file.  (In the case that both the are doing skipped records we need
 5886:    to remember the old skipped lines for the time being so that element
 5887:    persists for a while.)
 5888: 
 5889: =cut
 5890: 
 5891: sub scantron_remove_scan_data {
 5892:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5893:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5894:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 5895:     my @todelete;
 5896:     my $filename=$env{'form.scantron_selectfile'};
 5897:     foreach my $key (@keys) {
 5898: 	if ($key=~/^\Q$filename\E_/) {
 5899: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 5900: 		$key=~/remember_skipping/) {
 5901: 		next;
 5902: 	    }
 5903: 	    push(@todelete,$key);
 5904: 	}
 5905:     }
 5906:     my $result;
 5907:     if (@todelete) {
 5908: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
 5909:     }
 5910:     return $result;
 5911: }
 5912: 
 5913: 
 5914: =pod
 5915: 
 5916: =item scantron_getfile
 5917: 
 5918:     Fetches the requested bubble sheet data file (all 3 versions), and
 5919:     the scan_data hash
 5920:   
 5921:   Arguments:
 5922:     None
 5923: 
 5924:   Returns:
 5925:     2 hash references
 5926: 
 5927:      - first one has 
 5928:          orig      -
 5929:          corrected -
 5930:          skipped   -  each of which points to an array ref of the specified
 5931:                       file broken up into individual lines
 5932:          count     - number of scanlines
 5933:  
 5934:      - second is the scan_data hash possible keys are
 5935:        ($number refers to scanline numbered $number and thus the key affects
 5936:         only that scanline
 5937:         $bubline refers to the specific bubble line element and the aspects
 5938:         refers to that specific bubble line element)
 5939: 
 5940:        $number.user - username:domain to use
 5941:        $number.CODE_ignore_dup 
 5942:                     - ignore the duplicate CODE error 
 5943:        $number.useCODE
 5944:                     - use the CODE in the scanline as is
 5945:        $number.no_bubble.$bubline
 5946:                     - it is valid that there is no bubbled in bubble
 5947:                       at $number $bubline
 5948:        remember_skipping
 5949:                     - a frozen hash containing keys of $number and values
 5950:                       of either 
 5951:                         1 - we are on a 'do skipped records pass' and plan
 5952:                             on processing this line
 5953:                         2 - we are on a 'do skipped records pass' and this
 5954:                             scanline has been marked to skip yet again
 5955: 
 5956: =cut
 5957: 
 5958: sub scantron_getfile {
 5959:     #FIXME really would prefer a scantron directory
 5960:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5961:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5962:     my $lines;
 5963:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5964: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 5965:     my %scanlines;
 5966:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 5967:     my $temp=$scanlines{'orig'};
 5968:     $scanlines{'count'}=$#$temp;
 5969: 
 5970:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5971: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 5972:     if ($lines eq '-1') {
 5973: 	$scanlines{'corrected'}=[];
 5974:     } else {
 5975: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 5976:     }
 5977:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5978: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 5979:     if ($lines eq '-1') {
 5980: 	$scanlines{'skipped'}=[];
 5981:     } else {
 5982: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 5983:     }
 5984:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 5985:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 5986:     my %scan_data = @tmp;
 5987:     return (\%scanlines,\%scan_data);
 5988: }
 5989: 
 5990: =pod
 5991: 
 5992: =item lonnet_putfile
 5993: 
 5994:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 5995: 
 5996:  Arguments:
 5997:    $contents - data to store
 5998:    $filename - filename to store $contents into
 5999: 
 6000:  Returns:
 6001:    result value from &Apache::lonnet::finishuserfileupload
 6002: 
 6003: =cut
 6004: 
 6005: sub lonnet_putfile {
 6006:     my ($contents,$filename)=@_;
 6007:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6008:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6009:     $env{'form.sillywaytopassafilearound'}=$contents;
 6010:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6011: 
 6012: }
 6013: 
 6014: =pod
 6015: 
 6016: =item scantron_putfile
 6017: 
 6018:     Stores the current version of the bubble sheet data files, and the
 6019:     scan_data hash. (Does not modify the original version only the
 6020:     corrected and skipped versions.
 6021: 
 6022:  Arguments:
 6023:     $scanlines - hash ref that looks like the first return value from
 6024:                  &scantron_getfile()
 6025:     $scan_data - hash ref that looks like the second return value from
 6026:                  &scantron_getfile()
 6027: 
 6028: =cut
 6029: 
 6030: sub scantron_putfile {
 6031:     my ($scanlines,$scan_data) = @_;
 6032:     #FIXME really would prefer a scantron directory
 6033:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6034:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6035:     if ($scanlines) {
 6036: 	my $prefix='scantron_';
 6037: # no need to update orig, shouldn't change
 6038: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6039: #		    $env{'form.scantron_selectfile'});
 6040: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6041: 			$prefix.'corrected_'.
 6042: 			$env{'form.scantron_selectfile'});
 6043: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6044: 			$prefix.'skipped_'.
 6045: 			$env{'form.scantron_selectfile'});
 6046:     }
 6047:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6048: }
 6049: 
 6050: =pod
 6051: 
 6052: =item scantron_get_line
 6053: 
 6054:    Returns the correct version of the scanline
 6055: 
 6056:  Arguments:
 6057:     $scanlines - hash ref that looks like the first return value from
 6058:                  &scantron_getfile()
 6059:     $scan_data - hash ref that looks like the second return value from
 6060:                  &scantron_getfile()
 6061:     $i         - number of the requested line (starts at 0)
 6062: 
 6063:  Returns:
 6064:    A scanline, (either the original or the corrected one if it
 6065:    exists), or undef if the requested scanline should be
 6066:    skipped. (Either because it's an skipped scanline, or it's an
 6067:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6068:    pass.
 6069: 
 6070: =cut
 6071: 
 6072: sub scantron_get_line {
 6073:     my ($scanlines,$scan_data,$i)=@_;
 6074:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6075:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6076:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6077:     return $scanlines->{'orig'}[$i]; 
 6078: }
 6079: 
 6080: =pod
 6081: 
 6082: =item scantron_todo_count
 6083: 
 6084:     Counts the number of scanlines that need processing.
 6085: 
 6086:  Arguments:
 6087:     $scanlines - hash ref that looks like the first return value from
 6088:                  &scantron_getfile()
 6089:     $scan_data - hash ref that looks like the second return value from
 6090:                  &scantron_getfile()
 6091: 
 6092:  Returns:
 6093:     $count - number of scanlines to process
 6094: 
 6095: =cut
 6096: 
 6097: sub get_todo_count {
 6098:     my ($scanlines,$scan_data)=@_;
 6099:     my $count=0;
 6100:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6101: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6102: 	if ($line=~/^[\s\cz]*$/) { next; }
 6103: 	$count++;
 6104:     }
 6105:     return $count;
 6106: }
 6107: 
 6108: =pod
 6109: 
 6110: =item scantron_put_line
 6111: 
 6112:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6113:     data file.
 6114: 
 6115:  Arguments:
 6116:     $scanlines - hash ref that looks like the first return value from
 6117:                  &scantron_getfile()
 6118:     $scan_data - hash ref that looks like the second return value from
 6119:                  &scantron_getfile()
 6120:     $i         - line number to update
 6121:     $newline   - contents of the updated scanline
 6122:     $skip      - if true make the line for skipping and update the
 6123:                  'skipped' file
 6124: 
 6125: =cut
 6126: 
 6127: sub scantron_put_line {
 6128:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6129:     if ($skip) {
 6130: 	$scanlines->{'skipped'}[$i]=$newline;
 6131: 	&start_skipping($scan_data,$i);
 6132: 	return;
 6133:     }
 6134:     $scanlines->{'corrected'}[$i]=$newline;
 6135: }
 6136: 
 6137: =pod
 6138: 
 6139: =item scantron_clear_skip
 6140: 
 6141:    Remove a line from the 'skipped' file
 6142: 
 6143:  Arguments:
 6144:     $scanlines - hash ref that looks like the first return value from
 6145:                  &scantron_getfile()
 6146:     $scan_data - hash ref that looks like the second return value from
 6147:                  &scantron_getfile()
 6148:     $i         - line number to update
 6149: 
 6150: =cut
 6151: 
 6152: sub scantron_clear_skip {
 6153:     my ($scanlines,$scan_data,$i)=@_;
 6154:     if (exists($scanlines->{'skipped'}[$i])) {
 6155: 	undef($scanlines->{'skipped'}[$i]);
 6156: 	return 1;
 6157:     }
 6158:     return 0;
 6159: }
 6160: 
 6161: =pod
 6162: 
 6163: =item scantron_filter_not_exam
 6164: 
 6165:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6166:    filter out resources that are not marked as 'exam' mode
 6167: 
 6168: =cut
 6169: 
 6170: sub scantron_filter_not_exam {
 6171:     my ($curres)=@_;
 6172:     
 6173:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6174: 	# if the user has asked to not have either hidden
 6175: 	# or 'randomout' controlled resources to be graded
 6176: 	# don't include them
 6177: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6178: 	    && $curres->randomout) {
 6179: 	    return 0;
 6180: 	}
 6181: 	return 1;
 6182:     }
 6183:     return 0;
 6184: }
 6185: 
 6186: =pod
 6187: 
 6188: =item scantron_validate_sequence
 6189: 
 6190:     Validates the selected sequence, checking for resource that are
 6191:     not set to exam mode.
 6192: 
 6193: =cut
 6194: 
 6195: sub scantron_validate_sequence {
 6196:     my ($r,$currentphase) = @_;
 6197: 
 6198:     my $navmap=Apache::lonnavmaps::navmap->new();
 6199:     my (undef,undef,$sequence)=
 6200: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6201: 
 6202:     my $map=$navmap->getResourceByUrl($sequence);
 6203: 
 6204:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6205:                                     value="ignore" />');
 6206:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6207: 	my @resources=
 6208: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6209: 	if (@resources) {
 6210: 	    $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>");
 6211: 	    return (1,$currentphase);
 6212: 	}
 6213:     }
 6214: 
 6215:     return (0,$currentphase+1);
 6216: }
 6217: 
 6218: =pod
 6219: 
 6220: =item scantron_validate_ID
 6221: 
 6222:    Validates all scanlines in the selected file to not have any
 6223:    invalid or underspecified student IDs
 6224: 
 6225: =cut
 6226: 
 6227: sub scantron_validate_ID {
 6228:     my ($r,$currentphase) = @_;
 6229:     
 6230:     #get student info
 6231:     my $classlist=&Apache::loncoursedata::get_classlist();
 6232:     my %idmap=&username_to_idmap($classlist);
 6233: 
 6234:     #get scantron line setup
 6235:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6236:     my ($scanlines,$scan_data)=&scantron_getfile();
 6237:     
 6238:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6239: 
 6240:     my %found=('ids'=>{},'usernames'=>{});
 6241:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6242: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6243: 	if ($line=~/^[\s\cz]*$/) { next; }
 6244: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6245: 						 $scan_data);
 6246: 	my $id=$$scan_record{'scantron.ID'};
 6247: 	my $found;
 6248: 	foreach my $checkid (keys(%idmap)) {
 6249: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6250: 	}
 6251: 	if ($found) {
 6252: 	    my $username=$idmap{$found};
 6253: 	    if ($found{'ids'}{$found}) {
 6254: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6255: 					 $line,'duplicateID',$found);
 6256: 		return(1,$currentphase);
 6257: 	    } elsif ($found{'usernames'}{$username}) {
 6258: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6259: 					 $line,'duplicateID',$username);
 6260: 		return(1,$currentphase);
 6261: 	    }
 6262: 	    #FIXME store away line we previously saw the ID on to use above
 6263: 	    $found{'ids'}{$found}++;
 6264: 	    $found{'usernames'}{$username}++;
 6265: 	} else {
 6266: 	    if ($id =~ /^\s*$/) {
 6267: 		my $username=&scan_data($scan_data,"$i.user");
 6268: 		if (defined($username) && $found{'usernames'}{$username}) {
 6269: 		    &scantron_get_correction($r,$i,$scan_record,
 6270: 					     \%scantron_config,
 6271: 					     $line,'duplicateID',$username);
 6272: 		    return(1,$currentphase);
 6273: 		} elsif (!defined($username)) {
 6274: 		    &scantron_get_correction($r,$i,$scan_record,
 6275: 					     \%scantron_config,
 6276: 					     $line,'incorrectID');
 6277: 		    return(1,$currentphase);
 6278: 		}
 6279: 		$found{'usernames'}{$username}++;
 6280: 	    } else {
 6281: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6282: 					 $line,'incorrectID');
 6283: 		return(1,$currentphase);
 6284: 	    }
 6285: 	}
 6286:     }
 6287: 
 6288:     return (0,$currentphase+1);
 6289: }
 6290: 
 6291: =pod
 6292: 
 6293: =item scantron_get_correction
 6294: 
 6295:    Builds the interface screen to interact with the operator to fix a
 6296:    specific error condition in a specific scanline
 6297: 
 6298:  Arguments:
 6299:     $r           - Apache request object
 6300:     $i           - number of the current scanline
 6301:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6302:     $scan_config - hash ref as returned from &get_scantron_config()
 6303:     $line        - full contents of the current scanline
 6304:     $error       - error condition, valid values are
 6305:                    'incorrectCODE', 'duplicateCODE',
 6306:                    'doublebubble', 'missingbubble',
 6307:                    'duplicateID', 'incorrectID'
 6308:     $arg         - extra information needed
 6309:        For errors:
 6310:          - duplicateID   - paper number that this studentID was seen before on
 6311:          - duplicateCODE - array ref of the paper numbers this CODE was
 6312:                            seen on before
 6313:          - incorrectCODE - current incorrect CODE 
 6314:          - doublebubble  - array ref of the bubble lines that have double
 6315:                            bubble errors
 6316:          - missingbubble - array ref of the bubble lines that have missing
 6317:                            bubble errors
 6318: 
 6319: =cut
 6320: 
 6321: sub scantron_get_correction {
 6322:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6323: 
 6324: #FIXME in the case of a duplicated ID the previous line, probaly need
 6325: #to show both the current line and the previous one and allow skipping
 6326: #the previous one or the current one
 6327: 
 6328:     $r->print("<p><b>An error was detected ($error)</b>");
 6329:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6330: 	$r->print(" for PaperID <tt>".
 6331: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
 6332:     } else {
 6333: 	$r->print(" in scanline $i <pre>".
 6334: 		  $line."</pre> \n");
 6335:     }
 6336:     my $message="<p>The ID on the form is  <tt>".
 6337: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
 6338: 	"The name on the paper is ".
 6339: 	$$scan_record{'scantron.LastName'}.",".
 6340: 	$$scan_record{'scantron.FirstName'}."</p>";
 6341: 
 6342:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6343:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6344:     if ($error =~ /ID$/) {
 6345: 	if ($error eq 'incorrectID') {
 6346: 	    $r->print("The encoded ID is not in the classlist</p>\n");
 6347: 	} elsif ($error eq 'duplicateID') {
 6348: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
 6349: 	}
 6350: 	$r->print($message);
 6351: 	$r->print("<p>How should I handle this? <br /> \n");
 6352: 	$r->print("\n<ul><li> ");
 6353: 	#FIXME it would be nice if this sent back the user ID and
 6354: 	#could do partial userID matches
 6355: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6356: 				       'scantron_username','scantron_domain'));
 6357: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6358: 	$r->print("\n@".
 6359: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6360: 
 6361: 	$r->print('</li>');
 6362:     } elsif ($error =~ /CODE$/) {
 6363: 	if ($error eq 'incorrectCODE') {
 6364: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
 6365: 	} elsif ($error eq 'duplicateCODE') {
 6366: 	    $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");
 6367: 	}
 6368: 	$r->print("<p>The CODE on the form is  <tt>'".
 6369: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
 6370: 	$r->print($message);
 6371: 	$r->print("<p>How should I handle this? <br /> \n");
 6372: 	$r->print("\n<br /> ");
 6373: 	my $i=0;
 6374: 	if ($error eq 'incorrectCODE' 
 6375: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6376: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6377: 	    if ($closest > 0) {
 6378: 		foreach my $testcode (@{$closest}) {
 6379: 		    my $checked='';
 6380: 		    if (!$i) { $checked=' checked="checked" '; }
 6381: 		    $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' />");
 6382: 		    $r->print("\n<br />");
 6383: 		    $i++;
 6384: 		}
 6385: 	    }
 6386: 	}
 6387: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6388: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6389: 	    $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>");
 6390: 	    $r->print("\n<br />");
 6391: 	}
 6392: 
 6393: 	$r->print(<<ENDSCRIPT);
 6394: <script type="text/javascript">
 6395: function change_radio(field) {
 6396:     var slct=document.scantronupload.scantron_CODE_resolution;
 6397:     var i;
 6398:     for (i=0;i<slct.length;i++) {
 6399:         if (slct[i].value==field) { slct[i].checked=true; }
 6400:     }
 6401: }
 6402: </script>
 6403: ENDSCRIPT
 6404: 	my $href="/adm/pickcode?".
 6405: 	   "form=".&escape("scantronupload").
 6406: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6407: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6408: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6409: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6410: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6411: 	    $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')\" />");
 6412: 	    $r->print("\n<br />");
 6413: 	}
 6414: 	$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.");
 6415: 	$r->print("\n<br /><br />");
 6416:     } elsif ($error eq 'doublebubble') {
 6417: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
 6418: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6419: 		  join(',',@{$arg}).'" />');
 6420: 	$r->print($message);
 6421: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 6422: 	foreach my $question (@{$arg}) {
 6423: 
 6424: 	    my $selected  = &get_response_bubbles($scan_record, $question);
 6425: 	    &scantron_bubble_selector($r,$scan_config,$question,
 6426: 				      split('',$selected));
 6427: 	}
 6428:     } elsif ($error eq 'missingbubble') {
 6429: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
 6430: 	$r->print($message);
 6431: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 6432: 	$r->print("Some questions have no scanned bubbles\n");
 6433: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6434: 		  join(',',@{$arg}).'" />');
 6435: 	foreach my $question (@{$arg}) {
 6436: 	    my $selected = &get_response_bubbles($scan_record, $question);
 6437: 	    &scantron_bubble_selector($r,$scan_config,$question);
 6438: 	}
 6439:     } else {
 6440: 	$r->print("\n<ul>");
 6441:     }
 6442:     $r->print("\n</li></ul>");
 6443: 
 6444: }
 6445: 
 6446: =pod
 6447: 
 6448: =item scantron_bubble_selector
 6449:   
 6450:    Generates the html radiobuttons to correct a single bubble line
 6451:    possibly showing the existing the selected bubbles if known
 6452: 
 6453:  Arguments:
 6454:     $r           - Apache request object
 6455:     $scan_config - hash from &get_scantron_config()
 6456:     $quest       - number of the bubble line to make a corrector for
 6457:     $selected    - array of letters of previously selected bubbles
 6458: 
 6459: =cut
 6460: 
 6461: sub scantron_bubble_selector {
 6462:     my ($r,$scan_config,$quest,@selected)=@_;
 6463:     my $max=$$scan_config{'Qlength'};
 6464: 
 6465:     my $scmode=$$scan_config{'Qon'};
 6466: 
 6467: 
 6468:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 6469: 
 6470:     my $response = $quest-1;
 6471:     my $lines = $bubble_lines_per_response{$response};
 6472:     &Apache::lonnet::logthis("Question $quest, lines: $lines");
 6473: 
 6474:     my $total_lines = $lines*2;
 6475:     my @alphabet=('A'..'Z');
 6476:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
 6477: 
 6478:     for (my $l = 0; $l < $lines; $l++) {
 6479: 	if ($l != 0) {
 6480: 	    $r->print('<tr>');
 6481: 	}
 6482: 
 6483: 	# FIXME:  This loop probably has to be considerably more clever for
 6484: 	#  multiline bubbles: User can multibubble by having bubbles in
 6485: 	#  several lines.  User can skip lines legitimately etc. etc.
 6486: 
 6487: 	for (my $i=0;$i<$max;$i++) {
 6488: 	    $r->print("\n".'<td align="center">');
 6489: 	    if ($selected[0] eq $alphabet[$i]) { 
 6490: 		$r->print('X'); 
 6491: 		shift(@selected) ;
 6492: 	    } else { 
 6493: 		$r->print('&nbsp;'); 
 6494: 	    }
 6495: 	    $r->print('</td>');
 6496: 	    
 6497: 	}
 6498: 
 6499: 	if ($l == 0) {
 6500: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
 6501: 
 6502: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
 6503: 	      $quest.'" value="none" /> No bubble </label></td>');
 6504: 	
 6505: 	}
 6506: 
 6507: 	$r->print('</tr><tr>');
 6508: 
 6509: 	# FIXME: This may have to be a bit more clever for
 6510: 	#        multiline questions (different values e.g..).
 6511: 
 6512: 	for (my $i=0;$i<$max;$i++) {
 6513: 	    $r->print("\n".
 6514: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
 6515: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 6516: 	}
 6517: 	$r->print('</tr>');
 6518: 
 6519: 	    
 6520:     }
 6521:     $r->print('</table>');
 6522: }
 6523: 
 6524: =pod
 6525: 
 6526: =item num_matches
 6527: 
 6528:    Counts the number of characters that are the same between the two arguments.
 6529: 
 6530:  Arguments:
 6531:    $orig - CODE from the scanline
 6532:    $code - CODE to match against
 6533: 
 6534:  Returns:
 6535:    $count - integer count of the number of same characters between the
 6536:             two arguments
 6537: 
 6538: =cut
 6539: 
 6540: sub num_matches {
 6541:     my ($orig,$code) = @_;
 6542:     my @code=split(//,$code);
 6543:     my @orig=split(//,$orig);
 6544:     my $same=0;
 6545:     for (my $i=0;$i<scalar(@code);$i++) {
 6546: 	if ($code[$i] eq $orig[$i]) { $same++; }
 6547:     }
 6548:     return $same;
 6549: }
 6550: 
 6551: =pod
 6552: 
 6553: =item scantron_get_closely_matching_CODEs
 6554: 
 6555:    Cycles through all CODEs and finds the set that has the greatest
 6556:    number of same characters as the provided CODE
 6557: 
 6558:  Arguments:
 6559:    $allcodes - hash ref returned by &get_codes()
 6560:    $CODE     - CODE from the current scanline
 6561: 
 6562:  Returns:
 6563:    2 element list
 6564:     - first elements is number of how closely matching the best fit is 
 6565:       (5 means best set has 5 matching characters)
 6566:     - second element is an arrary ref containing the set of valid CODEs
 6567:       that best fit the passed in CODE
 6568: 
 6569: =cut
 6570: 
 6571: sub scantron_get_closely_matching_CODEs {
 6572:     my ($allcodes,$CODE)=@_;
 6573:     my @CODEs;
 6574:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 6575: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 6576:     }
 6577: 
 6578:     return ($#CODEs,$CODEs[-1]);
 6579: }
 6580: 
 6581: =pod
 6582: 
 6583: =item get_codes
 6584: 
 6585:    Builds a hash which has keys of all of the valid CODEs from the selected
 6586:    set of remembered CODEs.
 6587: 
 6588:  Arguments:
 6589:   $old_name - name of the set of remembered CODEs
 6590:   $cdom     - domain of the course
 6591:   $cnum     - internal course name
 6592: 
 6593:  Returns:
 6594:   %allcodes - keys are the valid CODEs, values are all 1
 6595: 
 6596: =cut
 6597: 
 6598: sub get_codes {
 6599:     my ($old_name, $cdom, $cnum) = @_;
 6600:     if (!$old_name) {
 6601: 	$old_name=$env{'form.scantron_CODElist'};
 6602:     }
 6603:     if (!$cdom) {
 6604: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 6605:     }
 6606:     if (!$cnum) {
 6607: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 6608:     }
 6609:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 6610: 				    $cdom,$cnum);
 6611:     my %allcodes;
 6612:     if ($result{"type\0$old_name"} eq 'number') {
 6613: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 6614:     } else {
 6615: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 6616:     }
 6617:     return %allcodes;
 6618: }
 6619: 
 6620: =pod
 6621: 
 6622: =item scantron_validate_CODE
 6623: 
 6624:    Validates all scanlines in the selected file to not have any
 6625:    invalid or underspecified CODEs and that none of the codes are
 6626:    duplicated if this was requested.
 6627: 
 6628: =cut
 6629: 
 6630: sub scantron_validate_CODE {
 6631:     my ($r,$currentphase) = @_;
 6632:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6633:     if ($scantron_config{'CODElocation'} &&
 6634: 	$scantron_config{'CODEstart'} &&
 6635: 	$scantron_config{'CODElength'}) {
 6636: 	if (!defined($env{'form.scantron_CODElist'})) {
 6637: 	    &FIXME_blow_up()
 6638: 	}
 6639:     } else {
 6640: 	return (0,$currentphase+1);
 6641:     }
 6642:     
 6643:     my %usedCODEs;
 6644: 
 6645:     my %allcodes=&get_codes();
 6646: 
 6647:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 6648: 
 6649:     my ($scanlines,$scan_data)=&scantron_getfile();
 6650:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6651: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6652: 	if ($line=~/^[\s\cz]*$/) { next; }
 6653: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6654: 						 $scan_data);
 6655: 	my $CODE=$$scan_record{'scantron.CODE'};
 6656: 	my $error=0;
 6657: 	if (!&Apache::lonnet::validCODE($CODE)) {
 6658: 	    &scantron_get_correction($r,$i,$scan_record,
 6659: 				     \%scantron_config,
 6660: 				     $line,'incorrectCODE',\%allcodes);
 6661: 	    return(1,$currentphase);
 6662: 	}
 6663: 	if (%allcodes && !exists($allcodes{$CODE}) 
 6664: 	    && !$$scan_record{'scantron.useCODE'}) {
 6665: 	    &scantron_get_correction($r,$i,$scan_record,
 6666: 				     \%scantron_config,
 6667: 				     $line,'incorrectCODE',\%allcodes);
 6668: 	    return(1,$currentphase);
 6669: 	}
 6670: 	if (exists($usedCODEs{$CODE}) 
 6671: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 6672: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 6673: 	    &scantron_get_correction($r,$i,$scan_record,
 6674: 				     \%scantron_config,
 6675: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 6676: 	    return(1,$currentphase);
 6677: 	}
 6678: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 6679:     }
 6680:     return (0,$currentphase+1);
 6681: }
 6682: 
 6683: =pod
 6684: 
 6685: =item scantron_validate_doublebubble
 6686: 
 6687:    Validates all scanlines in the selected file to not have any
 6688:    bubble lines with multiple bubbles marked.
 6689: 
 6690: =cut
 6691: 
 6692: sub scantron_validate_doublebubble {
 6693:     my ($r,$currentphase) = @_;
 6694:     #get student info
 6695:     my $classlist=&Apache::loncoursedata::get_classlist();
 6696:     my %idmap=&username_to_idmap($classlist);
 6697: 
 6698:     #get scantron line setup
 6699:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6700:     my ($scanlines,$scan_data)=&scantron_getfile();
 6701: 
 6702:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 6703: 
 6704:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6705: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6706: 	if ($line=~/^[\s\cz]*$/) { next; }
 6707: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6708: 						 $scan_data);
 6709: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 6710: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 6711: 				 'doublebubble',
 6712: 				 $$scan_record{'scantron.doubleerror'});
 6713:     	return (1,$currentphase);
 6714:     }
 6715:     return (0,$currentphase+1);
 6716: }
 6717: 
 6718: =pod
 6719: 
 6720: =item scantron_get_maxbubble
 6721: 
 6722:    Returns the maximum number of bubble lines that are expected to
 6723:    occur. Does this by walking the selected sequence rendering the
 6724:    resource and then checking &Apache::lonxml::get_problem_counter()
 6725:    for what the current value of the problem counter is.
 6726: 
 6727:    Caches the results to $env{'form.scantron_maxbubble'},
 6728:    $env{'form.scantron.bubble_lines.n'} and 
 6729:    $env{'form.scantron.first_bubble_line.n'}
 6730:    which are the total number of bubble, lines, the number of bubble
 6731:    lines for reponse n and number of the first bubble line for response n.
 6732: 
 6733: =cut
 6734: 
 6735: sub scantron_get_maxbubble {    
 6736:     &Apache::lonnet::logthis("get_max_bubble");
 6737:     if (defined($env{'form.scantron_maxbubble'}) &&
 6738: 	$env{'form.scantron_maxbubble'}) {
 6739: 	&Apache::lonnet::logthis("cached");
 6740: 	&restore_bubble_lines();
 6741: 	return $env{'form.scantron_maxbubble'};
 6742:     }
 6743:     &Apache::lonnet::logthis("computing");
 6744: 
 6745:     my (undef, undef, $sequence) =
 6746: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6747: 
 6748:     my $navmap=Apache::lonnavmaps::navmap->new();
 6749:     my $map=$navmap->getResourceByUrl($sequence);
 6750:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 6751: 
 6752:     &Apache::lonxml::clear_problem_counter();
 6753: 
 6754:     my $uname       = $env{'form.student'};
 6755:     my $udom        = $env{'form.userdom'};
 6756:     my $cid         = $env{'request.course.id'};
 6757:     my $total_lines = 0;
 6758:     %bubble_lines_per_response = ();
 6759:     %first_bubble_line         = ();
 6760: 
 6761:   
 6762:     my $response_number = 0;
 6763:     my $bubble_line     = 0;
 6764:     foreach my $resource (@resources) {
 6765: 	my $symb = $resource->symb();
 6766: 	&Apache::lonxml::clear_bubble_lines_for_part();
 6767: 	my $result=&Apache::lonnet::ssi($resource->src(),
 6768: 					('symb' => $resource->symb()),
 6769: 					('grade_target' => 'analyze'),
 6770: 					('grade_courseid' => $cid),
 6771: 					('grade_domain' => $udom),
 6772: 					('grade_username' => $uname));
 6773: 	my (undef, $an) =
 6774: 	    split(/_HASH_REF__/,$result, 2);
 6775: 
 6776: 	my %analysis = &Apache::lonnet::str2hash($an);
 6777: 
 6778: 
 6779: 
 6780: 	foreach my $part_id (@{$analysis{'parts'}}) {
 6781: 	    my ($trash, $part) = split(/\./, $part_id);
 6782: 
 6783: 	    my $lines = $analysis{"$part_id.bubble_lines"}[0];
 6784: 
 6785: 	    # TODO - make this a persistent hash not an array.
 6786: 
 6787: 
 6788: 	    $first_bubble_line{$response_number}           = $bubble_line;
 6789: 	    $bubble_lines_per_response{$response_number}   = $lines;
 6790: 	    $response_number++;
 6791: 
 6792: 	    $bubble_line +=  $lines;
 6793: 	    $total_lines +=  $lines;
 6794: 	}
 6795: 
 6796:     }
 6797:     &Apache::lonnet::delenv('scantron\.');
 6798: 
 6799:     &save_bubble_lines();
 6800:     $env{'form.scantron_maxbubble'} =
 6801: 	$total_lines;
 6802:     return $env{'form.scantron_maxbubble'};
 6803: }
 6804: 
 6805: =pod
 6806: 
 6807: =item scantron_validate_missingbubbles
 6808: 
 6809:    Validates all scanlines in the selected file to not have any
 6810:     answers that don't have bubbles that have not been verified
 6811:     to be bubble free.
 6812: 
 6813: =cut
 6814: 
 6815: sub scantron_validate_missingbubbles {
 6816:     my ($r,$currentphase) = @_;
 6817:     #get student info
 6818:     my $classlist=&Apache::loncoursedata::get_classlist();
 6819:     my %idmap=&username_to_idmap($classlist);
 6820: 
 6821:     #get scantron line setup
 6822:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6823:     my ($scanlines,$scan_data)=&scantron_getfile();
 6824:     my $max_bubble=&scantron_get_maxbubble();
 6825:     if (!$max_bubble) { $max_bubble=2**31; }
 6826:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6827: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6828: 	if ($line=~/^[\s\cz]*$/) { next; }
 6829: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6830: 						 $scan_data);
 6831: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 6832: 	my @to_correct;
 6833: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 6834: 	    if ($missing > $max_bubble) { next; }
 6835: 	    push(@to_correct,$missing);
 6836: 	}
 6837: 	if (@to_correct) {
 6838: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6839: 				     $line,'missingbubble',\@to_correct);
 6840: 	    return (1,$currentphase);
 6841: 	}
 6842: 
 6843:     }
 6844:     return (0,$currentphase+1);
 6845: }
 6846: 
 6847: =pod
 6848: 
 6849: =item scantron_process_students
 6850: 
 6851:    Routine that does the actual grading of the bubble sheet information.
 6852: 
 6853:    The parsed scanline hash is added to %env 
 6854: 
 6855:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 6856:    foreach resource , with the form data of
 6857: 
 6858: 	'submitted'     =>'scantron' 
 6859: 	'grade_target'  =>'grade',
 6860: 	'grade_username'=> username of student
 6861: 	'grade_domain'  => domain of student
 6862: 	'grade_courseid'=> of course
 6863: 	'grade_symb'    => symb of resource to grade
 6864: 
 6865:     This triggers a grading pass. The problem grading code takes care
 6866:     of converting the bubbled letter information (now in %env) into a
 6867:     valid submission.
 6868: 
 6869: =cut
 6870: 
 6871: sub scantron_process_students {
 6872:     my ($r) = @_;
 6873:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6874:     my ($symb)=&get_symb($r);
 6875:     if (!$symb) {return '';}
 6876:     my $default_form_data=&defaultFormData($symb);
 6877: 
 6878:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6879:     my ($scanlines,$scan_data)=&scantron_getfile();
 6880:     my $classlist=&Apache::loncoursedata::get_classlist();
 6881:     my %idmap=&username_to_idmap($classlist);
 6882:     my $navmap=Apache::lonnavmaps::navmap->new();
 6883:     my $map=$navmap->getResourceByUrl($sequence);
 6884:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 6885: #    $r->print("geto ".scalar(@resources)."<br />");
 6886:     my $result= <<SCANTRONFORM;
 6887: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6888:   <input type="hidden" name="command" value="scantron_configphase" />
 6889:   $default_form_data
 6890: SCANTRONFORM
 6891:     $r->print($result);
 6892: 
 6893:     my @delayqueue;
 6894:     my %completedstudents;
 6895:     
 6896:     my $count=&get_todo_count($scanlines,$scan_data);
 6897:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 6898:  				    'Scantron Progress',$count,
 6899: 				    'inline',undef,'scantronupload');
 6900:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 6901: 					  'Processing first student');
 6902:     my $start=&Time::HiRes::time();
 6903:     my $i=-1;
 6904:     my ($uname,$udom,$started);
 6905: 
 6906:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 6907: 
 6908:     while ($i<$scanlines->{'count'}) {
 6909:  	($uname,$udom)=('','');
 6910:  	$i++;
 6911:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6912:  	if ($line=~/^[\s\cz]*$/) { next; }
 6913: 	if ($started) {
 6914: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 6915: 						     'last student');
 6916: 	}
 6917: 	$started=1;
 6918:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6919:  						 $scan_data);
 6920:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 6921:  					      \%idmap,$i)) {
 6922:   	    &scantron_add_delay(\@delayqueue,$line,
 6923:  				'Unable to find a student that matches',1);
 6924:  	    next;
 6925:   	}
 6926:  	if (exists $completedstudents{$uname}) {
 6927:  	    &scantron_add_delay(\@delayqueue,$line,
 6928:  				'Student '.$uname.' has multiple sheets',2);
 6929:  	    next;
 6930:  	}
 6931:   	($uname,$udom)=split(/:/,$uname);
 6932: 
 6933: 	&Apache::lonxml::clear_problem_counter();
 6934:   	&Apache::lonnet::appenv(%$scan_record);
 6935: 
 6936: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 6937: 	    &scantron_putfile($scanlines,$scan_data);
 6938: 	}
 6939: 	
 6940: 	my $i=0;
 6941: 	foreach my $resource (@resources) {
 6942: 	    $i++;
 6943: 	    my %form=('submitted'     =>'scantron',
 6944: 		      'grade_target'  =>'grade',
 6945: 		      'grade_username'=>$uname,
 6946: 		      'grade_domain'  =>$udom,
 6947: 		      'grade_courseid'=>$env{'request.course.id'},
 6948: 		      'grade_symb'    =>$resource->symb());
 6949: 	    if (exists($scan_record->{'scantron.CODE'})
 6950: 		&& 
 6951: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
 6952: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 6953: 	    } else {
 6954: 		$form{'CODE'}='';
 6955: 	    }
 6956: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
 6957: 	    if ($result ne '') {
 6958: 	    }
 6959: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 6960: 	}
 6961: 	$completedstudents{$uname}={'line'=>$line};
 6962: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 6963:     } continue {
 6964: 	&Apache::lonxml::clear_problem_counter();
 6965: 	&Apache::lonnet::delenv('scantron\.');
 6966:     }
 6967:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 6968: #    my $lasttime = &Time::HiRes::time()-$start;
 6969: #    $r->print("<p>took $lasttime</p>");
 6970: 
 6971:     $r->print("</form>");
 6972:     $r->print(&show_grading_menu_form($symb));
 6973:     return '';
 6974: }
 6975: 
 6976: =pod
 6977: 
 6978: =item scantron_upload_scantron_data
 6979: 
 6980:     Creates the screen for adding a new bubble sheet data file to a course.
 6981: 
 6982: =cut
 6983: 
 6984: sub scantron_upload_scantron_data {
 6985:     my ($r)=@_;
 6986:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 6987:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 6988: 							  'domainid',
 6989: 							  'coursename');
 6990:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 6991: 						   'domainid');
 6992:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 6993:     $r->print(<<UPLOAD);
 6994: <script type="text/javascript" language="javascript">
 6995:     function checkUpload(formname) {
 6996: 	if (formname.upfile.value == "") {
 6997: 	    alert("Please use the browse button to select a file from your local directory.");
 6998: 	    return false;
 6999: 	}
 7000: 	formname.submit();
 7001:     }
 7002: </script>
 7003: 
 7004: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 7005: $default_form_data
 7006: <table>
 7007: <tr><td>$select_link </td></tr>
 7008: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
 7009: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
 7010: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
 7011: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
 7012: </table>
 7013: <input name='command' value='scantronupload_save' type='hidden' />
 7014: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 7015: </form>
 7016: UPLOAD
 7017:     return '';
 7018: }
 7019: 
 7020: =pod
 7021: 
 7022: =item scantron_upload_scantron_data_save
 7023: 
 7024:    Adds a provided bubble information data file to the course if user
 7025:    has the correct privileges to do so.  
 7026: 
 7027: =cut
 7028: 
 7029: sub scantron_upload_scantron_data_save {
 7030:     my($r)=@_;
 7031:     my ($symb)=&get_symb($r,1);
 7032:     my $doanotherupload=
 7033: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7034: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7035: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
 7036: 	'</form>'."\n";
 7037:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7038: 	!&Apache::lonnet::allowed('usc',
 7039: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7040: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
 7041: 	if ($symb) {
 7042: 	    $r->print(&show_grading_menu_form($symb));
 7043: 	} else {
 7044: 	    $r->print($doanotherupload);
 7045: 	}
 7046: 	return '';
 7047:     }
 7048:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7049:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
 7050:     my $fname=$env{'form.upfile.filename'};
 7051:     #FIXME
 7052:     #copied from lonnet::userfileupload()
 7053:     #make that function able to target a specified course
 7054:     # Replace Windows backslashes by forward slashes
 7055:     $fname=~s/\\/\//g;
 7056:     # Get rid of everything but the actual filename
 7057:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7058:     # Replace spaces by underscores
 7059:     $fname=~s/\s+/\_/g;
 7060:     # Replace all other weird characters by nothing
 7061:     $fname=~s/[^\w\.\-]//g;
 7062:     # See if there is anything left
 7063:     unless ($fname) { return 'error: no uploaded file'; }
 7064:     my $uploadedfile=$fname;
 7065:     $fname='scantron_orig_'.$fname;
 7066:     if (length($env{'form.upfile'}) < 2) {
 7067: 	$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.");
 7068:     } else {
 7069: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7070: 	if ($result =~ m|^/uploaded/|) {
 7071: 	    $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
 7072: 	} else {
 7073: 	    $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>");
 7074: 	}
 7075:     }
 7076:     if ($symb) {
 7077: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7078:     } else {
 7079: 	$r->print($doanotherupload);
 7080:     }
 7081:     return '';
 7082: }
 7083: 
 7084: =pod
 7085: 
 7086: =item valid_file
 7087: 
 7088:    Validates that the requested bubble data file exists in the course.
 7089: 
 7090: =cut
 7091: 
 7092: sub valid_file {
 7093:     my ($requested_file)=@_;
 7094:     foreach my $filename (sort(&scantron_filenames())) {
 7095: 	if ($requested_file eq $filename) { return 1; }
 7096:     }
 7097:     return 0;
 7098: }
 7099: 
 7100: =pod
 7101: 
 7102: =item scantron_download_scantron_data
 7103: 
 7104:    Shows a list of the three internal files (original, corrected,
 7105:    skipped) for a specific bubble sheet data file that exists in the
 7106:    course.
 7107: 
 7108: =cut
 7109: 
 7110: sub scantron_download_scantron_data {
 7111:     my ($r)=@_;
 7112:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7113:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7114:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7115:     my $file=$env{'form.scantron_selectfile'};
 7116:     if (! &valid_file($file)) {
 7117: 	$r->print(<<ERROR);
 7118: 	<p>
 7119: 	    The requested file name was invalid.
 7120:         </p>
 7121: ERROR
 7122: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7123: 	return;
 7124:     }
 7125:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7126:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7127:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7128:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7129:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7130:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7131:     $r->print(<<DOWNLOAD);
 7132:     <p>
 7133: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
 7134:     </p>
 7135:     <p>
 7136: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
 7137:     </p>
 7138:     <p>
 7139: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
 7140:     </p>
 7141: DOWNLOAD
 7142:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7143:     return '';
 7144: }
 7145: 
 7146: =pod
 7147: 
 7148: =back
 7149: 
 7150: =cut
 7151: 
 7152: #-------- end of section for handling grading scantron forms -------
 7153: #
 7154: #-------------------------------------------------------------------
 7155: 
 7156: #-------------------------- Menu interface -------------------------
 7157: #
 7158: #--- Show a Grading Menu button - Calls the next routine ---
 7159: sub show_grading_menu_form {
 7160:     my ($symb)=@_;
 7161:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 7162: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7163: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 7164: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 7165: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
 7166: 	'</form>'."\n";
 7167:     return $result;
 7168: }
 7169: 
 7170: # -- Retrieve choices for grading form
 7171: sub savedState {
 7172:     my %savedState = ();
 7173:     if ($env{'form.saveState'}) {
 7174: 	foreach (split(/:/,$env{'form.saveState'})) {
 7175: 	    my ($key,$value) = split(/=/,$_,2);
 7176: 	    $savedState{$key} = $value;
 7177: 	}
 7178:     }
 7179:     return \%savedState;
 7180: }
 7181: 
 7182: sub grading_menu {
 7183:     my ($request) = @_;
 7184:     my ($symb)=&get_symb($request);
 7185:     if (!$symb) {return '';}
 7186:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7187:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7188: 
 7189:     #
 7190:     # Define menu data
 7191:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 7192:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 7193:     $request->print($table);
 7194:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 7195:                   'handgrade'=>$hdgrade,
 7196:                   'probTitle'=>$probTitle,
 7197:                   'command'=>'submit_options',
 7198:                   'saveState'=>"",
 7199:                   'gradingMenu'=>1,
 7200:                   'showgrading'=>"yes");
 7201:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7202:     my @menu = ({ url => $url,
 7203:                      name => &mt('Manual Grading/View Submissions'),
 7204:                      short_description => 
 7205:     &mt('Start the process of hand grading submissions.'),
 7206:                  });
 7207:     $fields{'command'} = 'csvform';
 7208:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7209:     push (@menu, { url => $url,
 7210:                    name => &mt('Upload Scores'),
 7211:                    short_description => 
 7212:             &mt('Specify a file containing the class scores for current resource.')});
 7213:     $fields{'command'} = 'processclicker';
 7214:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7215:     push (@menu, { url => $url,
 7216:                    name => &mt('Process Clicker'),
 7217:                    short_description => 
 7218:             &mt('Specify a file containing the clicker information for this resource.')});
 7219:     $fields{'command'} = 'scantron_selectphase';
 7220:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7221:     push (@menu, { url => $url,
 7222:                    name => &mt('Grade Scantron Forms'),
 7223:                    short_description => 
 7224:             &mt('')});
 7225:     $fields{'command'} = 'verify';
 7226:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7227:     push (@menu, { url => "",
 7228:                    jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
 7229:                    name => &mt('Verify Receipt'),
 7230:                    short_description => 
 7231:             &mt('')});
 7232:     $fields{'command'} = 'manage';
 7233:     $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
 7234:     push (@menu, { url => $url,
 7235:                    name => &mt('Manage Access Times'),
 7236:                    short_description => 
 7237:             &mt('')});
 7238:     $fields{'command'} = 'view';
 7239:     $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
 7240:     push (@menu, { url => $url,
 7241:                    name => &mt('View Saved CODEs'),
 7242:                    short_description => 
 7243:             &mt('')});
 7244: 
 7245:     #
 7246:     # Create the menu
 7247:     my $Str;
 7248:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 7249:     $Str .= '<form method="post" action="" name="gradingMenu">';
 7250:     $Str .= '<input type="hidden" name="command" value="" />'.
 7251:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7252: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7253: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
 7254: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7255: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7256: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7257: 
 7258:     foreach my $menudata (@menu) {
 7259:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 7260:             $Str .='    <h3><a '.
 7261:                 $menudata->{'jscript'}.
 7262:                 ' href="'.
 7263:                 $menudata->{'url'}.'" >'.
 7264:                 $menudata->{'name'}."</a></h3>\n";
 7265:         } else {
 7266:             $Str .='    <h3><a '.
 7267:                 $menudata->{'jscript'}.
 7268:                 ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
 7269:                 $menudata->{'name'}."</a></h3>\n";
 7270:             $Str .= ('&nbsp;'x8).
 7271:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
 7272:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 7273:         }
 7274:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 7275:             "\n";
 7276:     }
 7277:     $Str .="</dl>\n";
 7278:     $Str .="</form>\n";
 7279:     $request->print(<<GRADINGMENUJS);
 7280: <script type="text/javascript" language="javascript">
 7281:     function checkChoice(formname,val,cmdx) {
 7282: 	if (val <= 2) {
 7283: 	    var cmd = radioSelection(formname.radioChoice);
 7284: 	    var cmdsave = cmd;
 7285: 	} else {
 7286: 	    cmd = cmdx;
 7287: 	    cmdsave = 'submission';
 7288: 	}
 7289: 	formname.command.value = cmd;
 7290: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 7291: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 7292: 	if (val < 5) formname.submit();
 7293: 	if (val == 5) {
 7294: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7295: 	    formname.submit();
 7296: 	}
 7297: 	if (val < 7) formname.submit();
 7298:     }
 7299:     function checkChoice2(formname,val,cmdx) {
 7300: 	if (val <= 2) {
 7301: 	    var cmd = radioSelection(formname.radioChoice);
 7302: 	    var cmdsave = cmd;
 7303: 	} else {
 7304: 	    cmd = cmdx;
 7305: 	    cmdsave = 'submission';
 7306: 	}
 7307: 	formname.command.value = cmd;
 7308: 	if (val < 5) formname.submit();
 7309: 	if (val == 5) {
 7310: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7311: 	    formname.submit();
 7312: 	}
 7313: 	if (val < 7) formname.submit();
 7314:     }
 7315: 
 7316:     function checkReceiptNo(formname,nospace) {
 7317: 	var receiptNo = formname.receipt.value;
 7318: 	var checkOpt = false;
 7319: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7320: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7321: 	if (checkOpt) {
 7322: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7323: 	    formname.receipt.value = "";
 7324: 	    formname.receipt.focus();
 7325: 	    return false;
 7326: 	}
 7327: 	return true;
 7328:     }
 7329: </script>
 7330: GRADINGMENUJS
 7331:     &commonJSfunctions($request);
 7332:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
 7333:     $result.=$table;
 7334:     my (undef,$sections) = &getclasslist('all','0');
 7335:     my $savedState = &savedState();
 7336:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 7337:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 7338:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 7339:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 7340: 
 7341:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 7342: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7343: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7344: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
 7345: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7346: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7347: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7348: 
 7349:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
 7350: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
 7351: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
 7352: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
 7353: 
 7354:     $result.='<table width="100%" border="0">';
 7355:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
 7356:     $result.='<td><b>'.&mt('Sections').'</b></td>';
 7357: #    $result.='<td>Groups</td>';
 7358:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
 7359:     $result.='</tr>';
 7360:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
 7361: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
 7362:     if (ref($sections)) {
 7363: 	foreach (sort (@$sections)) {
 7364: 	    $result.='<option value="'.$_.'" '.
 7365: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
 7366: 	}
 7367:     }
 7368:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 7369:     return $Str;    
 7370: }
 7371: 
 7372: 
 7373: #--- Displays the submissions first page -------
 7374: sub submit_options {
 7375:     my ($request) = @_;
 7376:     my ($symb)=&get_symb($request);
 7377:     if (!$symb) {return '';}
 7378:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7379: 
 7380:     $request->print(<<GRADINGMENUJS);
 7381: <script type="text/javascript" language="javascript">
 7382:     function checkChoice(formname,val,cmdx) {
 7383: 	if (val <= 2) {
 7384: 	    var cmd = radioSelection(formname.radioChoice);
 7385: 	    var cmdsave = cmd;
 7386: 	} else {
 7387: 	    cmd = cmdx;
 7388: 	    cmdsave = 'submission';
 7389: 	}
 7390: 	formname.command.value = cmd;
 7391: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 7392: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 7393: 	if (val < 5) formname.submit();
 7394: 	if (val == 5) {
 7395: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7396: 	    formname.submit();
 7397: 	}
 7398: 	if (val < 7) formname.submit();
 7399:     }
 7400: 
 7401:     function checkReceiptNo(formname,nospace) {
 7402: 	var receiptNo = formname.receipt.value;
 7403: 	var checkOpt = false;
 7404: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7405: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7406: 	if (checkOpt) {
 7407: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7408: 	    formname.receipt.value = "";
 7409: 	    formname.receipt.focus();
 7410: 	    return false;
 7411: 	}
 7412: 	return true;
 7413:     }
 7414: </script>
 7415: GRADINGMENUJS
 7416:     &commonJSfunctions($request);
 7417:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
 7418:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7419:     $result.=$table;
 7420:     my (undef,$sections) = &getclasslist('all','0');
 7421:     my $savedState = &savedState();
 7422:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 7423:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 7424:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 7425:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 7426: 
 7427:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 7428: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7429: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7430: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 7431: 	'<input type="hidden" name="command"     value="" />'."\n".
 7432: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7433: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7434: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7435: 
 7436:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
 7437: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
 7438: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
 7439: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
 7440: 
 7441:     $result.='<table width="100%" border="0">';
 7442:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
 7443:     $result.='<td><b>'.&mt('Sections').'</b></td>';
 7444:     $result.='<td><b>'.&mt('Groups').'</b></td>';
 7445:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
 7446:     $result.='</tr>';
 7447:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
 7448: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
 7449:     if (ref($sections)) {
 7450: 	foreach (sort (@$sections)) {
 7451: 	    $result.='<option value="'.$_.'" '.
 7452: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
 7453: 	}
 7454:     }
 7455:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 7456:     $result.= '</td><td>'."\n";
 7457:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
 7458:     $result.='</td><td>'."\n";
 7459:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
 7460: 
 7461:     $result.='</td></tr>';
 7462: 
 7463:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
 7464: 	'<input type="radio" name="radioChoice" value="submission" '.
 7465: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
 7466: 	'</label> <select name="submitonly">'.
 7467: 	'<option value="yes" '.
 7468: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
 7469: 	'<option value="queued" '.
 7470: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
 7471: 	'<option value="graded" '.
 7472: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
 7473: 	'<option value="incorrect" '.
 7474: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
 7475: 	'<option value="all" '.
 7476: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
 7477: 
 7478:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7479: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
 7480: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 7481: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
 7482: 
 7483:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
 7484: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
 7485: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 7486: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
 7487: 
 7488:     $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
 7489: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
 7490: 	'</td></tr></table>'."\n";
 7491: 
 7492:     $result.='</td>'; #<td valign="top">';
 7493: 
 7494: #    $result.='<table width="100%" border="0">';
 7495: #    $result.='<tr bgcolor="#ffffe6"><td>'.
 7496: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
 7497: #	' '.&mt('scores from file').' </td></tr>'."\n";
 7498: #
 7499: #    $result.='<tr bgcolor="#ffffe6"><td>'.
 7500: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
 7501: #        ' '.&mt('clicker file').' </td></tr>'."\n";
 7502: #
 7503: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7504: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
 7505: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
 7506: #
 7507: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
 7508: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 7509: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
 7510: #	    ' '.&mt('receipt').': '.
 7511: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
 7512: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
 7513: #	    '</td></tr>'."\n";
 7514: #    } 
 7515: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7516: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
 7517: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
 7518: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7519: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
 7520: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
 7521: #
 7522: #    $result.='</table>'."\n".'</td>';
 7523:     $result.= '</tr></table>'."\n".
 7524: 	'</td></tr></table></form>'."\n";
 7525:     return $result;
 7526: }
 7527: 
 7528: sub reset_perm {
 7529:     undef(%perm);
 7530: }
 7531: 
 7532: sub init_perm {
 7533:     &reset_perm();
 7534:     foreach my $test_perm ('vgr','mgr','opa') {
 7535: 
 7536: 	my $scope = $env{'request.course.id'};
 7537: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 7538: 
 7539: 	    $scope .= '/'.$env{'request.course.sec'};
 7540: 	    if ( $perm{$test_perm}=
 7541: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 7542: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 7543: 	    } else {
 7544: 		delete($perm{$test_perm});
 7545: 	    }
 7546: 	}
 7547:     }
 7548: }
 7549: 
 7550: sub gather_clicker_ids {
 7551:     my %clicker_ids;
 7552: 
 7553:     my $classlist = &Apache::loncoursedata::get_classlist();
 7554: 
 7555:     # Set up a couple variables.
 7556:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 7557:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 7558:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 7559: 
 7560:     foreach my $student (keys(%$classlist)) {
 7561:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 7562:         my $username = $classlist->{$student}->[$username_idx];
 7563:         my $domain   = $classlist->{$student}->[$domain_idx];
 7564:         my $clickers =
 7565: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 7566:         foreach my $id (split(/\,/,$clickers)) {
 7567:             $id=~s/^[\#0]+//;
 7568:             $id=~s/[\-\:]//g;
 7569:             if (exists($clicker_ids{$id})) {
 7570: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 7571:             } else {
 7572: 		$clicker_ids{$id}=$username.':'.$domain;
 7573:             }
 7574:         }
 7575:     }
 7576:     return %clicker_ids;
 7577: }
 7578: 
 7579: sub gather_adv_clicker_ids {
 7580:     my %clicker_ids;
 7581:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 7582:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7583:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 7584:     foreach my $element (sort(keys(%coursepersonnel))) {
 7585:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 7586:             my ($puname,$pudom)=split(/\:/,$person);
 7587:             my $clickers =
 7588: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 7589:             foreach my $id (split(/\,/,$clickers)) {
 7590: 		$id=~s/^[\#0]+//;
 7591:                 $id=~s/[\-\:]//g;
 7592: 		if (exists($clicker_ids{$id})) {
 7593: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 7594: 		} else {
 7595: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 7596: 		}
 7597:             }
 7598:         }
 7599:     }
 7600:     return %clicker_ids;
 7601: }
 7602: 
 7603: sub clicker_grading_parameters {
 7604:     return ('gradingmechanism' => 'scalar',
 7605:             'upfiletype' => 'scalar',
 7606:             'specificid' => 'scalar',
 7607:             'pcorrect' => 'scalar',
 7608:             'pincorrect' => 'scalar');
 7609: }
 7610: 
 7611: sub process_clicker {
 7612:     my ($r)=@_;
 7613:     my ($symb)=&get_symb($r);
 7614:     if (!$symb) {return '';}
 7615:     my $result=&checkforfile_js();
 7616:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 7617:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 7618:     $result.=$table;
 7619:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 7620:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 7621:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 7622:         '.</b></td></tr>'."\n";
 7623:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 7624: # Attempt to restore parameters from last session, set defaults if not present
 7625:     my %Saveable_Parameters=&clicker_grading_parameters();
 7626:     &Apache::loncommon::restore_course_settings('grades_clicker',
 7627:                                                  \%Saveable_Parameters);
 7628:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 7629:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 7630:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 7631:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 7632: 
 7633:     my %checked;
 7634:     foreach my $gradingmechanism ('attendance','personnel','specific') {
 7635:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 7636:           $checked{$gradingmechanism}="checked='checked'";
 7637:        }
 7638:     }
 7639: 
 7640:     my $upload=&mt("Upload File");
 7641:     my $type=&mt("Type");
 7642:     my $attendance=&mt("Award points just for participation");
 7643:     my $personnel=&mt("Correctness determined from response by course personnel");
 7644:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 7645:     my $pcorrect=&mt("Percentage points for correct solution");
 7646:     my $pincorrect=&mt("Percentage points for incorrect solution");
 7647:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 7648: 						   ('iclicker' => 'i>clicker',
 7649:                                                     'interwrite' => 'interwrite PRS'));
 7650:     $symb = &Apache::lonenc::check_encrypt($symb);
 7651:     $result.=<<ENDUPFORM;
 7652: <script type="text/javascript">
 7653: function sanitycheck() {
 7654: // Accept only integer percentages
 7655:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 7656:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 7657: // Find out grading choice
 7658:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 7659:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 7660:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 7661:       }
 7662:    }
 7663: // By default, new choice equals user selection
 7664:    newgradingchoice=gradingchoice;
 7665: // Not good to give more points for false answers than correct ones
 7666:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 7667:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 7668:    }
 7669: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 7670:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 7671:       document.forms.gradesupload.pcorrect.value=100;
 7672:       document.forms.gradesupload.pincorrect.value=100;
 7673:    }
 7674: // If the values are different, cannot be attendance only
 7675:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 7676:        (gradingchoice=='attendance')) {
 7677:        newgradingchoice='personnel';
 7678:    }
 7679: // Change grading choice to new one
 7680:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 7681:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 7682:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 7683:       } else {
 7684:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 7685:       }
 7686:    }
 7687: // Remember the old state
 7688:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 7689: }
 7690: </script>
 7691: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 7692: <input type="hidden" name="symb" value="$symb" />
 7693: <input type="hidden" name="command" value="processclickerfile" />
 7694: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 7695: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 7696: <input type="file" name="upfile" size="50" />
 7697: <br /><label>$type: $selectform</label>
 7698: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 7699: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 7700: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 7701: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 7702: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 7703: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 7704: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 7705: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 7706: </form>
 7707: ENDUPFORM
 7708:     $result.='</td></tr></table>'."\n".
 7709:              '</td></tr></table><br /><br />'."\n";
 7710:     $result.=&show_grading_menu_form($symb);
 7711:     return $result;
 7712: }
 7713: 
 7714: sub process_clicker_file {
 7715:     my ($r)=@_;
 7716:     my ($symb)=&get_symb($r);
 7717:     if (!$symb) {return '';}
 7718: 
 7719:     my %Saveable_Parameters=&clicker_grading_parameters();
 7720:     &Apache::loncommon::store_course_settings('grades_clicker',
 7721:                                               \%Saveable_Parameters);
 7722: 
 7723:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 7724:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 7725: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 7726: 	return $result.&show_grading_menu_form($symb);
 7727:     }
 7728:     my %clicker_ids=&gather_clicker_ids();
 7729:     my %correct_ids;
 7730:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 7731: 	%correct_ids=&gather_adv_clicker_ids();
 7732:     }
 7733:     if ($env{'form.gradingmechanism'} eq 'specific') {
 7734: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 7735: 	   $correct_id=~tr/a-z/A-Z/;
 7736: 	   $correct_id=~s/\s//gs;
 7737: 	   $correct_id=~s/^[\#0]+//;
 7738:            $correct_id=~s/[\-\:]//g;
 7739:            if ($correct_id) {
 7740: 	      $correct_ids{$correct_id}='specified';
 7741:            }
 7742:         }
 7743:     }
 7744:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 7745: 	$result.=&mt('Score based on attendance only');
 7746:     } else {
 7747: 	my $number=0;
 7748: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 7749: 	foreach my $id (sort(keys(%correct_ids))) {
 7750: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 7751: 	    if ($correct_ids{$id} eq 'specified') {
 7752: 		$result.=&mt('specified');
 7753: 	    } else {
 7754: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 7755: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 7756: 	    }
 7757: 	    $number++;
 7758: 	}
 7759:         $result.="</p>\n";
 7760: 	if ($number==0) {
 7761: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 7762: 	    return $result.&show_grading_menu_form($symb);
 7763: 	}
 7764:     }
 7765:     if (length($env{'form.upfile'}) < 2) {
 7766:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 7767: 		     '<span class="LC_error">',
 7768: 		     '</span>',
 7769: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 7770:         return $result.&show_grading_menu_form($symb);
 7771:     }
 7772: 
 7773: # Were able to get all the info needed, now analyze the file
 7774: 
 7775:     $result.=&Apache::loncommon::studentbrowser_javascript();
 7776:     $symb = &Apache::lonenc::check_encrypt($symb);
 7777:     my $heading=&mt('Scanning clicker file');
 7778:     $result.=(<<ENDHEADER);
 7779: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 7780: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 7781: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 7782: <form method="post" action="/adm/grades" name="clickeranalysis">
 7783: <input type="hidden" name="symb" value="$symb" />
 7784: <input type="hidden" name="command" value="assignclickergrades" />
 7785: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 7786: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 7787: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 7788: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 7789: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 7790: ENDHEADER
 7791:     my %responses;
 7792:     my @questiontitles;
 7793:     my $errormsg='';
 7794:     my $number=0;
 7795:     if ($env{'form.upfiletype'} eq 'iclicker') {
 7796: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 7797:     }
 7798:     if ($env{'form.upfiletype'} eq 'interwrite') {
 7799:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 7800:     }
 7801:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 7802:              '<input type="hidden" name="number" value="'.$number.'" />'.
 7803:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
 7804:              '<input type="hidden" name="number" value="'.$number.'" />'.
 7805:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 7806:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 7807:              '<br />';
 7808: # Remember Question Titles
 7809: # FIXME: Possibly need delimiter other than ":"
 7810:     for (my $i=0;$i<$number;$i++) {
 7811:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 7812:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 7813:     }
 7814:     my $correct_count=0;
 7815:     my $student_count=0;
 7816:     my $unknown_count=0;
 7817: # Match answers with usernames
 7818: # FIXME: Possibly need delimiter other than ":"
 7819:     foreach my $id (keys(%responses)) {
 7820:        if ($correct_ids{$id}) {
 7821:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 7822:           $correct_count++;
 7823:        } elsif ($clicker_ids{$id}) {
 7824:           if ($clicker_ids{$id}=~/\,/) {
 7825: # More than one user with the same clicker!
 7826:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 7827:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 7828:                            "<select name='multi".$id."'>";
 7829:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 7830:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 7831:              }
 7832:              $result.='</select>';
 7833:              $unknown_count++;
 7834:           } else {
 7835: # Good: found one and only one user with the right clicker
 7836:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 7837:              $student_count++;
 7838:           }
 7839:        } else {
 7840:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 7841:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 7842:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 7843:                    "\n".&mt("Domain").": ".
 7844:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 7845:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 7846:           $unknown_count++;
 7847:        }
 7848:     }
 7849:     $result.='<hr />'.
 7850:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 7851:     if ($env{'form.gradingmechanism'} ne 'attendance') {
 7852:        if ($correct_count==0) {
 7853:           $errormsg.="Found no correct answers answers for grading!";
 7854:        } elsif ($correct_count>1) {
 7855:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 7856:        }
 7857:     }
 7858:     if ($number<1) {
 7859:        $errormsg.="Found no questions.";
 7860:     }
 7861:     if ($errormsg) {
 7862:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 7863:     } else {
 7864:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 7865:     }
 7866:     $result.='</form></td></tr></table>'."\n".
 7867:              '</td></tr></table><br /><br />'."\n";
 7868:     return $result.&show_grading_menu_form($symb);
 7869: }
 7870: 
 7871: sub iclicker_eval {
 7872:     my ($questiontitles,$responses)=@_;
 7873:     my $number=0;
 7874:     my $errormsg='';
 7875:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 7876:         my %components=&Apache::loncommon::record_sep($line);
 7877:         my @entries=map {$components{$_}} (sort(keys(%components)));
 7878: 	if ($entries[0] eq 'Question') {
 7879: 	    for (my $i=3;$i<$#entries;$i+=6) {
 7880: 		$$questiontitles[$number]=$entries[$i];
 7881: 		$number++;
 7882: 	    }
 7883: 	}
 7884: 	if ($entries[0]=~/^\#/) {
 7885: 	    my $id=$entries[0];
 7886: 	    my @idresponses;
 7887: 	    $id=~s/^[\#0]+//;
 7888: 	    for (my $i=0;$i<$number;$i++) {
 7889: 		my $idx=3+$i*6;
 7890: 		push(@idresponses,$entries[$idx]);
 7891: 	    }
 7892: 	    $$responses{$id}=join(',',@idresponses);
 7893: 	}
 7894:     }
 7895:     return ($errormsg,$number);
 7896: }
 7897: 
 7898: sub interwrite_eval {
 7899:     my ($questiontitles,$responses)=@_;
 7900:     my $number=0;
 7901:     my $errormsg='';
 7902:     my $skipline=1;
 7903:     my $questionnumber=0;
 7904:     my %idresponses=();
 7905:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 7906:         my %components=&Apache::loncommon::record_sep($line);
 7907:         my @entries=map {$components{$_}} (sort(keys(%components)));
 7908:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 7909:         if ($entries[1] eq 'Response') { $skipline=1; }
 7910:         next if $skipline;
 7911:         if ($entries[0]!=$questionnumber) {
 7912:            $questionnumber=$entries[0];
 7913:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 7914:            $number++;
 7915:         }
 7916:         my $id=$entries[4];
 7917:         $id=~s/^[\#0]+//;
 7918:         $id=~s/^v\d*\://i;
 7919:         $id=~s/[\-\:]//g;
 7920:         $idresponses{$id}[$number]=$entries[6];
 7921:     }
 7922:     foreach my $id (keys %idresponses) {
 7923:        $$responses{$id}=join(',',@{$idresponses{$id}});
 7924:        $$responses{$id}=~s/^\s*\,//;
 7925:     }
 7926:     return ($errormsg,$number);
 7927: }
 7928: 
 7929: sub assign_clicker_grades {
 7930:     my ($r)=@_;
 7931:     my ($symb)=&get_symb($r);
 7932:     if (!$symb) {return '';}
 7933: # See which part we are saving to
 7934:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 7935: # FIXME: This should probably look for the first handgradeable part
 7936:     my $part=$$partlist[0];
 7937: # Start screen output
 7938:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 7939: 
 7940:     my $heading=&mt('Assigning grades based on clicker file');
 7941:     $result.=(<<ENDHEADER);
 7942: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 7943: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 7944: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 7945: ENDHEADER
 7946: # Get correct result
 7947: # FIXME: Possibly need delimiter other than ":"
 7948:     my @correct=();
 7949:     my $gradingmechanism=$env{'form.gradingmechanism'};
 7950:     my $number=$env{'form.number'};
 7951:     if ($gradingmechanism ne 'attendance') {
 7952:        foreach my $key (keys(%env)) {
 7953:           if ($key=~/^form\.correct\:/) {
 7954:              my @input=split(/\,/,$env{$key});
 7955:              for (my $i=0;$i<=$#input;$i++) {
 7956:                  if (($correct[$i]) && ($input[$i]) &&
 7957:                      ($correct[$i] ne $input[$i])) {
 7958:                     $result.='<br /><span class="LC_warning">'.
 7959:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 7960:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 7961:                  } elsif ($input[$i]) {
 7962:                     $correct[$i]=$input[$i];
 7963:                  }
 7964:              }
 7965:           }
 7966:        }
 7967:        for (my $i=0;$i<$number;$i++) {
 7968:           if (!$correct[$i]) {
 7969:              $result.='<br /><span class="LC_error">'.
 7970:                       &mt('No correct result given for question "[_1]"!',
 7971:                           $env{'form.question:'.$i}).'</span>';
 7972:           }
 7973:        }
 7974:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 7975:     }
 7976: # Start grading
 7977:     my $pcorrect=$env{'form.pcorrect'};
 7978:     my $pincorrect=$env{'form.pincorrect'};
 7979:     my $storecount=0;
 7980:     foreach my $key (keys(%env)) {
 7981:        my $user='';
 7982:        if ($key=~/^form\.student\:(.*)$/) {
 7983:           $user=$1;
 7984:        }
 7985:        if ($key=~/^form\.unknown\:(.*)$/) {
 7986:           my $id=$1;
 7987:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 7988:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 7989:           } elsif ($env{'form.multi'.$id}) {
 7990:              $user=$env{'form.multi'.$id};
 7991:           }
 7992:        }
 7993:        if ($user) { 
 7994:           my @answer=split(/\,/,$env{$key});
 7995:           my $sum=0;
 7996:           for (my $i=0;$i<$number;$i++) {
 7997:              if ($answer[$i]) {
 7998:                 if ($gradingmechanism eq 'attendance') {
 7999:                    $sum+=$pcorrect;
 8000:                 } else {
 8001:                    if ($answer[$i] eq $correct[$i]) {
 8002:                       $sum+=$pcorrect;
 8003:                    } else {
 8004:                       $sum+=$pincorrect;
 8005:                    }
 8006:                 }
 8007:              }
 8008:           }
 8009:           my $ave=$sum/(100*$number);
 8010: # Store
 8011:           my ($username,$domain)=split(/\:/,$user);
 8012:           my %grades=();
 8013:           $grades{"resource.$part.solved"}='correct_by_override';
 8014:           $grades{"resource.$part.awarded"}=$ave;
 8015:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8016:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8017:                                                  $env{'request.course.id'},
 8018:                                                  $domain,$username);
 8019:           if ($returncode ne 'ok') {
 8020:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8021:           } else {
 8022:              $storecount++;
 8023:           }
 8024:        }
 8025:     }
 8026: # We are done
 8027:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 8028:              '</td></tr></table>'."\n".
 8029:              '</td></tr></table><br /><br />'."\n";
 8030:     return $result.&show_grading_menu_form($symb);
 8031: }
 8032: 
 8033: sub handler {
 8034:     my $request=$_[0];
 8035: 
 8036:     &reset_caches();
 8037:     if ($env{'browser.mathml'}) {
 8038: 	&Apache::loncommon::content_type($request,'text/xml');
 8039:     } else {
 8040: 	&Apache::loncommon::content_type($request,'text/html');
 8041:     }
 8042:     $request->send_http_header;
 8043:     return '' if $request->header_only;
 8044:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8045:     my $symb=&get_symb($request,1);
 8046:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8047:     my $command=$commands[0];
 8048: 
 8049:     if ($#commands > 0) {
 8050: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8051:     }
 8052: 
 8053: 
 8054:     $request->print(&Apache::loncommon::start_page('Grading'));
 8055:     if ($symb eq '' && $command eq '') {
 8056: 	if ($env{'user.adv'}) {
 8057: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8058: 		($env{'form.codethree'})) {
 8059: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8060: 		    $env{'form.codethree'};
 8061: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8062: 		    &Apache::lonnet::checkin($token);
 8063: 		if ($tsymb) {
 8064: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8065: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8066: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
 8067: 					  ('grade_username' => $tuname,
 8068: 					   'grade_domain' => $tudom,
 8069: 					   'grade_courseid' => $tcrsid,
 8070: 					   'grade_symb' => $tsymb)));
 8071: 		    } else {
 8072: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8073: 		    }
 8074: 		} else {
 8075: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8076: 		}
 8077: 	    } else {
 8078: 		$request->print(&Apache::lonxml::tokeninputfield());
 8079: 	    }
 8080: 	}
 8081:     } else {
 8082: 	&init_perm();
 8083: 	if ($command eq 'submission' && $perm{'vgr'}) {
 8084: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 8085: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 8086: 	    &pickStudentPage($request);
 8087: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 8088: 	    &displayPage($request);
 8089: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 8090: 	    &updateGradeByPage($request);
 8091: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 8092: 	    &processGroup($request);
 8093: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 8094: 	    $request->print(&grading_menu($request));
 8095: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 8096: 	    $request->print(&submit_options($request));
 8097: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 8098: 	    $request->print(&viewgrades($request));
 8099: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 8100: 	    $request->print(&processHandGrade($request));
 8101: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 8102: 	    $request->print(&editgrades($request));
 8103: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 8104: 	    $request->print(&verifyreceipt($request));
 8105:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 8106:             $request->print(&process_clicker($request));
 8107:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 8108:             $request->print(&process_clicker_file($request));
 8109:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 8110:             $request->print(&assign_clicker_grades($request));
 8111: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 8112: 	    $request->print(&upcsvScores_form($request));
 8113: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 8114: 	    $request->print(&csvupload($request));
 8115: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 8116: 	    $request->print(&csvuploadmap($request));
 8117: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 8118: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 8119: 		$request->print(&csvuploadoptions($request));
 8120: 	    } else {
 8121: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 8122: 		    $env{'form.upfile_associate'} = 'reverse';
 8123: 		} else {
 8124: 		    $env{'form.upfile_associate'} = 'forward';
 8125: 		}
 8126: 		$request->print(&csvuploadmap($request));
 8127: 	    }
 8128: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 8129: 	    $request->print(&csvuploadassign($request));
 8130: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 8131: 	    &Apache::lonnet::logthis("Selecting pyhase");
 8132: 	    $request->print(&scantron_selectphase($request));
 8133:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 8134:  	    $request->print(&scantron_do_warning($request));
 8135: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 8136: 	    $request->print(&scantron_validate_file($request));
 8137: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 8138: 	    $request->print(&scantron_process_students($request));
 8139:  	} elsif ($command eq 'scantronupload' && 
 8140:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8141: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8142:  	    $request->print(&scantron_upload_scantron_data($request)); 
 8143:  	} elsif ($command eq 'scantronupload_save' &&
 8144:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8145: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8146:  	    $request->print(&scantron_upload_scantron_data_save($request));
 8147:  	} elsif ($command eq 'scantron_download' &&
 8148: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 8149:  	    $request->print(&scantron_download_scantron_data($request));
 8150: 	} elsif ($command) {
 8151: 	    $request->print("Access Denied ($command)");
 8152: 	}
 8153:     }
 8154:     $request->print(&Apache::loncommon::end_page());
 8155:     &reset_caches();
 8156:     return '';
 8157: }
 8158: 
 8159: 1;
 8160: 
 8161: __END__;

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