File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.552: download - view: text, annotated - select for diffs
Wed Feb 18 07:06:12 2009 UTC (15 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Starting with lonnet.pm rev 1.981, default for &lonnet::delenv() has been to \Q escape arg in regexp used to identify items in environment to delete.
  - No longer need to escape special characters in arg passed to lonnet::delenv().
- Call to lonnet::delenv() in rat/lonuserstate now includes second arg, because in this case first arg is to be treated as a regexp (so \Q escape is not wanted).

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.552 2009/02/18 07:06:12 raeburn 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: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use String::Similarity;
   47: use LONCAPA;
   48: 
   49: use POSIX qw(floor);
   50: 
   51: 
   52: 
   53: my %perm=();
   54: 
   55: #  These variables are used to recover from ssi errors
   56: 
   57: my $ssi_retries = 5;
   58: my $ssi_error;
   59: my $ssi_error_resource;
   60: my $ssi_error_message;
   61: 
   62: 
   63: sub ssi_with_retries {
   64:     my ($resource, $retries, %form) = @_;
   65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   66:     if ($response->is_error) {
   67: 	$ssi_error          = 1;
   68: 	$ssi_error_resource = $resource;
   69: 	$ssi_error_message  = $response->code . " " . $response->message;
   70:     }
   71: 
   72:     return $content;
   73: 
   74: }
   75: #
   76: #  Prodcuces an ssi retry failure error message to the user:
   77: #
   78: 
   79: sub ssi_print_error {
   80:     my ($r) = @_;
   81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   82:     $r->print('
   83: <br />
   84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   85: <p>
   86: '.&mt('Unable to retrieve a resource from a server:').'<br />
   87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   88: '.&mt('Error:').' '.$ssi_error_message.'
   89: </p>
   90: <p>'.
   91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   93: '</p>');
   94:     return;
   95: }
   96: 
   97: #
   98: # --- Retrieve the parts from the metadata file.---
   99: sub getpartlist {
  100:     my ($symb) = @_;
  101: 
  102:     my $navmap   = Apache::lonnavmaps::navmap->new();
  103:     my $res      = $navmap->getBySymb($symb);
  104:     my $partlist = $res->parts();
  105:     my $url      = $res->src();
  106:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  107: 
  108:     my @stores;
  109:     foreach my $part (@{ $partlist }) {
  110: 	foreach my $key (@metakeys) {
  111: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  112: 	}
  113:     }
  114:     return @stores;
  115: }
  116: 
  117: # --- Get the symbolic name of a problem and the url
  118: sub get_symb {
  119:     my ($request,$silent) = @_;
  120:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  121:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  122:     if ($symb eq '') { 
  123: 	if (!$silent) {
  124: 	    $request->print("Unable to handle ambiguous references:$url:.");
  125: 	    return ();
  126: 	}
  127:     }
  128:     &Apache::lonenc::check_decrypt(\$symb);
  129:     return ($symb);
  130: }
  131: 
  132: #--- Format fullname, username:domain if different for display
  133: #--- Use anywhere where the student names are listed
  134: sub nameUserString {
  135:     my ($type,$fullname,$uname,$udom) = @_;
  136:     if ($type eq 'header') {
  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  138:     } else {
  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  141:     }
  142: }
  143: 
  144: #--- Get the partlist and the response type for a given problem. ---
  145: #--- Indicate if a response type is coded handgraded or not. ---
  146: sub response_type {
  147:     my ($symb) = shift;
  148: 
  149:     my $navmap = Apache::lonnavmaps::navmap->new();
  150:     my $res = $navmap->getBySymb($symb);
  151:     my $partlist = $res->parts();
  152:     my %vPart = 
  153: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  154:     my (%response_types,%handgrade);
  155:     foreach my $part (@{ $partlist }) {
  156: 	next if (%vPart && !exists($vPart{$part}));
  157: 
  158: 	my @types = $res->responseType($part);
  159: 	my @ids = $res->responseIds($part);
  160: 	for (my $i=0; $i < scalar(@ids); $i++) {
  161: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  162: 	    $handgrade{$part.'_'.$ids[$i]} = 
  163: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  164: 				     '.handgrade',$symb);
  165: 	}
  166:     }
  167:     return ($partlist,\%handgrade,\%response_types);
  168: }
  169: 
  170: sub flatten_responseType {
  171:     my ($responseType) = @_;
  172:     my @part_response_id =
  173: 	map { 
  174: 	    my $part = $_;
  175: 	    map {
  176: 		[$part,$_]
  177: 		} sort(keys(%{ $responseType->{$part} }));
  178: 	} sort(keys(%$responseType));
  179:     return @part_response_id;
  180: }
  181: 
  182: sub get_display_part {
  183:     my ($partID,$symb)=@_;
  184:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  185:     if (defined($display) and $display ne '') {
  186: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  187:     } else {
  188: 	$display=$partID;
  189:     }
  190:     return $display;
  191: }
  192: 
  193: #--- Show resource title
  194: #--- and parts and response type
  195: sub showResourceInfo {
  196:     my ($symb,$probTitle,$checkboxes) = @_;
  197:     my $col=3;
  198:     if ($checkboxes) { $col=4; }
  199:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  200:     $result .='<table border="0">';
  201:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  202:     my %resptype = ();
  203:     my $hdgrade='no';
  204:     my %partsseen;
  205:     foreach my $partID (sort(keys(%$responseType))) {
  206: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  207: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  208: 	    my $responsetype = $responseType->{$partID}->{$resID};
  209: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  210: 	    $result.='<tr>';
  211: 	    if ($checkboxes) {
  212: 		if (exists($partsseen{$partID})) {
  213: 		    $result.="<td>&nbsp;</td>";
  214: 		} else {
  215: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  216: 		}
  217: 		$partsseen{$partID}=1;
  218: 	    }
  219: 	    my $display_part=&get_display_part($partID,$symb);
  220: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
  221:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
  222: 		'<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
  223: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  224: 	}
  225:     }
  226:     $result.='</table>'."\n";
  227:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  228: }
  229: 
  230: sub reset_caches {
  231:     &reset_analyze_cache();
  232:     &reset_perm();
  233: }
  234: 
  235: {
  236:     my %analyze_cache;
  237: 
  238:     sub reset_analyze_cache {
  239: 	undef(%analyze_cache);
  240:     }
  241: 
  242:     sub get_analyze {
  243: 	my ($symb,$uname,$udom,$no_increment)=@_;
  244: 	my $key = "$symb\0$uname\0$udom";
  245: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  246: 
  247: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  248: 	$url=&Apache::lonnet::clutter($url);
  249: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
  250: 					   ('grade_target' => 'analyze',
  251: 					    'grade_domain' => $udom,
  252: 					    'grade_symb' => $symb,
  253: 					    'grade_courseid' => 
  254: 					    $env{'request.course.id'},
  255: 					    'grade_username' => $uname,
  256:                                             'grade_noincrement' => $no_increment));
  257: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  258: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  259: 	return $analyze_cache{$key} = \%analyze;
  260:     }
  261: 
  262:     sub get_order {
  263: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  264: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  265: 	return $analyze->{"$partid.$respid.shown"};
  266:     }
  267: 
  268:     sub get_radiobutton_correct_foil {
  269: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  270: 	my $analyze = &get_analyze($symb,$uname,$udom);
  271: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  272: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  273: 		return $foil;
  274: 	    }
  275: 	}
  276:     }
  277: }
  278: 
  279: #--- Clean response type for display
  280: #--- Currently filters option/rank/radiobutton/match/essay/Task
  281: #        response types only.
  282: sub cleanRecord {
  283:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  284: 	$uname,$udom) = @_;
  285:     my $grayFont = '<span class="LC_internal_info">';
  286:     if ($response =~ /^(option|rank)$/) {
  287: 	my %answer=&Apache::lonnet::str2hash($answer);
  288: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  289: 	my ($toprow,$bottomrow);
  290: 	foreach my $foil (@$order) {
  291: 	    if ($grading{$foil} == 1) {
  292: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  293: 	    } else {
  294: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  295: 	    }
  296: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  297: 	}
  298: 	return '<blockquote><table border="1">'.
  299: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  300: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  301: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  302:     } elsif ($response eq 'match') {
  303: 	my %answer=&Apache::lonnet::str2hash($answer);
  304: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  305: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  306: 	my ($toprow,$middlerow,$bottomrow);
  307: 	foreach my $foil (@$order) {
  308: 	    my $item=shift(@items);
  309: 	    if ($grading{$foil} == 1) {
  310: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  311: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  312: 	    } else {
  313: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  314: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  315: 	    }
  316: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  317: 	}
  318: 	return '<blockquote><table border="1">'.
  319: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  320: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  321: 	    $middlerow.'</tr>'.
  322: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  323: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  324:     } elsif ($response eq 'radiobutton') {
  325: 	my %answer=&Apache::lonnet::str2hash($answer);
  326: 	my ($toprow,$bottomrow);
  327: 	my $correct = 
  328: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  329: 	foreach my $foil (@$order) {
  330: 	    if (exists($answer{$foil})) {
  331: 		if ($foil eq $correct) {
  332: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  333: 		} else {
  334: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  335: 		}
  336: 	    } else {
  337: 		$toprow.='<td>'.&mt('false').'</td>';
  338: 	    }
  339: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  340: 	}
  341: 	return '<blockquote><table border="1">'.
  342: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  343: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  344: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  345:     } elsif ($response eq 'essay') {
  346: 	if (! exists ($env{'form.'.$symb})) {
  347: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  348: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  349: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  350: 
  351: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  352: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  353: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  354: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  355: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  356: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  357: 	}
  358: 	$answer =~ s-\n-<br />-g;
  359: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  360:     } elsif ( $response eq 'organic') {
  361: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  362: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  363: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  364: 	return $result;
  365:     } elsif ( $response eq 'Task') {
  366: 	if ( $answer eq 'SUBMITTED') {
  367: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  368: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  369: 	    return $result;
  370: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  371: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  372: 			       keys(%{$record}));
  373: 	    return join('<br />',($version,@matches));
  374: 			       
  375: 			       
  376: 	} else {
  377: 	    my $result =
  378: 		'<p>'
  379: 		.&mt('Overall result: [_1]',
  380: 		     $record->{$version."resource.$respid.$partid.status"})
  381: 		.'</p>';
  382: 	    
  383: 	    $result .= '<ul>';
  384: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  385: 			     keys(%{$record}));
  386: 	    foreach my $grade (sort(@grade)) {
  387: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  388: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  389: 				     $dim, $record->{$grade}).
  390: 			  '</li>';
  391: 	    }
  392: 	    $result.='</ul>';
  393: 	    return $result;
  394: 	}
  395:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  396: 	$answer = 
  397: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  398: 							      $answer);
  399:     }
  400:     return $answer;
  401: }
  402: 
  403: #-- A couple of common js functions
  404: sub commonJSfunctions {
  405:     my $request = shift;
  406:     $request->print(<<COMMONJSFUNCTIONS);
  407: <script type="text/javascript" language="javascript">
  408:     function radioSelection(radioButton) {
  409: 	var selection=null;
  410: 	if (radioButton.length > 1) {
  411: 	    for (var i=0; i<radioButton.length; i++) {
  412: 		if (radioButton[i].checked) {
  413: 		    return radioButton[i].value;
  414: 		}
  415: 	    }
  416: 	} else {
  417: 	    if (radioButton.checked) return radioButton.value;
  418: 	}
  419: 	return selection;
  420:     }
  421: 
  422:     function pullDownSelection(selectOne) {
  423: 	var selection="";
  424: 	if (selectOne.length > 1) {
  425: 	    for (var i=0; i<selectOne.length; i++) {
  426: 		if (selectOne[i].selected) {
  427: 		    return selectOne[i].value;
  428: 		}
  429: 	    }
  430: 	} else {
  431:             // only one value it must be the selected one
  432: 	    return selectOne.value;
  433: 	}
  434:     }
  435: </script>
  436: COMMONJSFUNCTIONS
  437: }
  438: 
  439: #--- Dumps the class list with usernames,list of sections,
  440: #--- section, ids and fullnames for each user.
  441: sub getclasslist {
  442:     my ($getsec,$filterlist,$getgroup) = @_;
  443:     my @getsec;
  444:     my @getgroup;
  445:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  446:     if (!ref($getsec)) {
  447: 	if ($getsec ne '' && $getsec ne 'all') {
  448: 	    @getsec=($getsec);
  449: 	}
  450:     } else {
  451: 	@getsec=@{$getsec};
  452:     }
  453:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  454:     if (!ref($getgroup)) {
  455: 	if ($getgroup ne '' && $getgroup ne 'all') {
  456: 	    @getgroup=($getgroup);
  457: 	}
  458:     } else {
  459: 	@getgroup=@{$getgroup};
  460:     }
  461:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  462: 
  463:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  464:     # Bail out if we were unable to get the classlist
  465:     return if (! defined($classlist));
  466:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  467:     #
  468:     my %sections;
  469:     my %fullnames;
  470:     foreach my $student (keys(%$classlist)) {
  471:         my $end      = 
  472:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  473:         my $start    = 
  474:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  475:         my $id       = 
  476:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  477:         my $section  = 
  478:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  479:         my $fullname = 
  480:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  481:         my $status   = 
  482:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  483:         my $group   = 
  484:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  485: 	# filter students according to status selected
  486: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  487: 	    if (!($stu_status =~ $status)) {
  488: 		delete($classlist->{$student});
  489: 		next;
  490: 	    }
  491: 	}
  492: 	# filter students according to groups selected
  493: 	my @stu_groups = split(/,/,$group);
  494: 	if (@getgroup) {
  495: 	    my $exclude = 1;
  496: 	    foreach my $grp (@getgroup) {
  497: 	        foreach my $stu_group (@stu_groups) {
  498: 	            if ($stu_group eq $grp) {
  499: 	                $exclude = 0;
  500:     	            } 
  501: 	        }
  502:     	        if (($grp eq 'none') && !$group) {
  503:         	        $exclude = 0;
  504:         	}
  505: 	    }
  506: 	    if ($exclude) {
  507: 	        delete($classlist->{$student});
  508: 	    }
  509: 	}
  510: 	$section = ($section ne '' ? $section : 'none');
  511: 	if (&canview($section)) {
  512: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  513: 		$sections{$section}++;
  514: 		if ($classlist->{$student}) {
  515: 		    $fullnames{$student}=$fullname;
  516: 		}
  517: 	    } else {
  518: 		delete($classlist->{$student});
  519: 	    }
  520: 	} else {
  521: 	    delete($classlist->{$student});
  522: 	}
  523:     }
  524:     my %seen = ();
  525:     my @sections = sort(keys(%sections));
  526:     return ($classlist,\@sections,\%fullnames);
  527: }
  528: 
  529: sub canmodify {
  530:     my ($sec)=@_;
  531:     if ($perm{'mgr'}) {
  532: 	if (!defined($perm{'mgr_section'})) {
  533: 	    # can modify whole class
  534: 	    return 1;
  535: 	} else {
  536: 	    if ($sec eq $perm{'mgr_section'}) {
  537: 		#can modify the requested section
  538: 		return 1;
  539: 	    } else {
  540: 		# can't modify the request section
  541: 		return 0;
  542: 	    }
  543: 	}
  544:     }
  545:     #can't modify
  546:     return 0;
  547: }
  548: 
  549: sub canview {
  550:     my ($sec)=@_;
  551:     if ($perm{'vgr'}) {
  552: 	if (!defined($perm{'vgr_section'})) {
  553: 	    # can modify whole class
  554: 	    return 1;
  555: 	} else {
  556: 	    if ($sec eq $perm{'vgr_section'}) {
  557: 		#can modify the requested section
  558: 		return 1;
  559: 	    } else {
  560: 		# can't modify the request section
  561: 		return 0;
  562: 	    }
  563: 	}
  564:     }
  565:     #can't modify
  566:     return 0;
  567: }
  568: 
  569: #--- Retrieve the grade status of a student for all the parts
  570: sub student_gradeStatus {
  571:     my ($symb,$udom,$uname,$partlist) = @_;
  572:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  573:     my %partstatus = ();
  574:     foreach (@$partlist) {
  575: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  576: 	$status              = 'nothing' if ($status eq '');
  577: 	$partstatus{$_}      = $status;
  578: 	my $subkey           = "resource.$_.submitted_by";
  579: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  580:     }
  581:     return %partstatus;
  582: }
  583: 
  584: # hidden form and javascript that calls the form
  585: # Use by verifyscript and viewgrades
  586: # Shows a student's view of problem and submission
  587: sub jscriptNform {
  588:     my ($symb) = @_;
  589:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  590:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  591: 	'    function viewOneStudent(user,domain) {'."\n".
  592: 	'	document.onestudent.student.value = user;'."\n".
  593: 	'	document.onestudent.userdom.value = domain;'."\n".
  594: 	'	document.onestudent.submit();'."\n".
  595: 	'    }'."\n".
  596: 	'</script>'."\n";
  597:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  598: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  599: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  600: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  601: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  602: 	'<input type="hidden" name="command" value="submission" />'."\n".
  603: 	'<input type="hidden" name="student" value="" />'."\n".
  604: 	'<input type="hidden" name="userdom" value="" />'."\n".
  605: 	'</form>'."\n";
  606:     return $jscript;
  607: }
  608: 
  609: 
  610: 
  611: # Given the score (as a number [0-1] and the weight) what is the final
  612: # point value? This function will round to the nearest tenth, third,
  613: # or quarter if one of those is within the tolerance of .00001.
  614: sub compute_points {
  615:     my ($score, $weight) = @_;
  616:     
  617:     my $tolerance = .00001;
  618:     my $points = $score * $weight;
  619: 
  620:     # Check for nearness to 1/x.
  621:     my $check_for_nearness = sub {
  622:         my ($factor) = @_;
  623:         my $num = ($points * $factor) + $tolerance;
  624:         my $floored_num = floor($num);
  625:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  626:             return $floored_num / $factor;
  627:         }
  628:         return $points;
  629:     };
  630: 
  631:     $points = $check_for_nearness->(10);
  632:     $points = $check_for_nearness->(3);
  633:     $points = $check_for_nearness->(4);
  634:     
  635:     return $points;
  636: }
  637: 
  638: #------------------ End of general use routines --------------------
  639: 
  640: #
  641: # Find most similar essay
  642: #
  643: 
  644: sub most_similar {
  645:     my ($uname,$udom,$uessay,$old_essays)=@_;
  646: 
  647: # ignore spaces and punctuation
  648: 
  649:     $uessay=~s/\W+/ /gs;
  650: 
  651: # ignore empty submissions (occuring when only files are sent)
  652: 
  653:     unless ($uessay=~/\w+/) { return ''; }
  654: 
  655: # these will be returned. Do not care if not at least 50 percent similar
  656:     my $limit=0.6;
  657:     my $sname='';
  658:     my $sdom='';
  659:     my $scrsid='';
  660:     my $sessay='';
  661: # go through all essays ...
  662:     foreach my $tkey (keys(%$old_essays)) {
  663: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  664: # ... except the same student
  665:         next if (($tname eq $uname) && ($tdom eq $udom));
  666: 	my $tessay=$old_essays->{$tkey};
  667: 	$tessay=~s/\W+/ /gs;
  668: # String similarity gives up if not even limit
  669: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  670: # Found one
  671: 	if ($tsimilar>$limit) {
  672: 	    $limit=$tsimilar;
  673: 	    $sname=$tname;
  674: 	    $sdom=$tdom;
  675: 	    $scrsid=$tcrsid;
  676: 	    $sessay=$old_essays->{$tkey};
  677: 	}
  678:     }
  679:     if ($limit>0.6) {
  680:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  681:     } else {
  682:        return ('','','','',0);
  683:     }
  684: }
  685: 
  686: #-------------------------------------------------------------------
  687: 
  688: #------------------------------------ Receipt Verification Routines
  689: #
  690: #--- Check whether a receipt number is valid.---
  691: sub verifyreceipt {
  692:     my $request  = shift;
  693: 
  694:     my $courseid = $env{'request.course.id'};
  695:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  696: 	$env{'form.receipt'};
  697:     $receipt     =~ s/[^\-\d]//g;
  698:     my ($symb)   = &get_symb($request);
  699: 
  700:     my $title.=
  701: 	'<h3><span class="LC_info">'.
  702: 	&mt('Verifying Submission Receipt [_1]',$receipt).
  703: 	'</span></h3>'."\n".
  704: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  705: 	'</h4>'."\n";
  706: 
  707:     my ($string,$contents,$matches) = ('','',0);
  708:     my (undef,undef,$fullname) = &getclasslist('all','0');
  709:     
  710:     my $receiptparts=0;
  711:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  712: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  713:     my $parts=['0'];
  714:     if ($receiptparts) { ($parts)=&response_type($symb); }
  715:     
  716:     my $header = 
  717: 	&Apache::loncommon::start_data_table().
  718: 	&Apache::loncommon::start_data_table_header_row().
  719: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  720: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  721: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  722:     if ($receiptparts) {
  723: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  724:     }
  725:     $header.=
  726: 	&Apache::loncommon::end_data_table_header_row();
  727: 
  728:     foreach (sort 
  729: 	     {
  730: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  731: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  732: 		 }
  733: 		 return $a cmp $b;
  734: 	     } (keys(%$fullname))) {
  735: 	my ($uname,$udom)=split(/\:/);
  736: 	foreach my $part (@$parts) {
  737: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  738: 		$contents.=
  739: 		    &Apache::loncommon::start_data_table_row().
  740: 		    '<td>&nbsp;'."\n".
  741: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  742: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  743: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  744: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  745: 		if ($receiptparts) {
  746: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  747: 		}
  748: 		$contents.= 
  749: 		    &Apache::loncommon::end_data_table_row()."\n";
  750: 		
  751: 		$matches++;
  752: 	    }
  753: 	}
  754:     }
  755:     if ($matches == 0) {
  756: 	$string = $title.&mt('No match found for the above receipt.');
  757:     } else {
  758: 	$string = &jscriptNform($symb).$title.
  759: 	    '<p>'.
  760: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  761: 	    '</p>'.
  762: 	    $header.
  763: 	    $contents.
  764: 	    &Apache::loncommon::end_data_table()."\n";
  765:     }
  766:     return $string.&show_grading_menu_form($symb);
  767: }
  768: 
  769: #--- This is called by a number of programs.
  770: #--- Called from the Grading Menu - View/Grade an individual student
  771: #--- Also called directly when one clicks on the subm button 
  772: #    on the problem page.
  773: sub listStudents {
  774:     my ($request) = shift;
  775: 
  776:     my ($symb) = &get_symb($request);
  777:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  778:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  779:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  780:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  781:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  782:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  783:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  784: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  785: 
  786:     my $result='<h3><span class="LC_info">&nbsp;'
  787: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  788: 	.'</span></h3>';
  789: 
  790:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  791: 
  792:     my %lt = ( 'multiple' =>
  793: 	       &mt("Please select a student or group of students before clicking on the Next button."),
  794: 	       'single'   =>
  795: 	       &mt("Please select the student before clicking on the Next button."),
  796: 	       );
  797:     %lt = &Apache::lonlocal::texthash(%lt);
  798:     $request->print(<<LISTJAVASCRIPT);
  799: <script type="text/javascript" language="javascript">
  800:     function checkSelect(checkBox) {
  801: 	var ctr=0;
  802: 	var sense="";
  803: 	if (checkBox.length > 1) {
  804: 	    for (var i=0; i<checkBox.length; i++) {
  805: 		if (checkBox[i].checked) {
  806: 		    ctr++;
  807: 		}
  808: 	    }
  809: 	    sense = '$lt{'multiple'}';
  810: 	} else {
  811: 	    if (checkBox.checked) {
  812: 		ctr = 1;
  813: 	    }
  814: 	    sense = '$lt{'single'}';
  815: 	}
  816: 	if (ctr == 0) {
  817: 	    alert(sense);
  818: 	    return false;
  819: 	}
  820: 	document.gradesub.submit();
  821:     }
  822: 
  823:     function reLoadList(formname) {
  824: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  825: 	formname.command.value = 'submission';
  826: 	formname.submit();
  827:     }
  828: </script>
  829: LISTJAVASCRIPT
  830: 
  831:     &commonJSfunctions($request);
  832:     $request->print($result);
  833: 
  834:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  835:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  836:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  837: 	"\n".$table;
  838: 	
  839:     $gradeTable .= 
  840: 	'&nbsp;<b>'.&mt('View Problem Text').': </b>'.
  841: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
  842: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
  843: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n";
  844:     $gradeTable .= 
  845: 	'&nbsp;<b>'.&mt('View Answer').': </b>'.
  846: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
  847: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
  848: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n";
  849: 
  850:     my $submission_options;
  851:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  852: 	$submission_options.=
  853: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  854:     }
  855:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  856:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  857:     $env{'form.Status'} = $saveStatus;
  858:     $submission_options.=
  859: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  860: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  861: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  862: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  863:     $gradeTable .= 
  864: 	'&nbsp;<b>'.&mt('Submissions').': </b>'.$submission_options.'<br />'."\n";
  865: 
  866:     $gradeTable .= 
  867:         '&nbsp;<b>'.&mt('Grading Increments').': </b>'.
  868: 	    '<select name="increment">'.
  869: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
  870: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
  871: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
  872: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
  873: 	    '</select>';
  874:     
  875:     $gradeTable .= 
  876:         &build_section_inputs().
  877: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  878: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  879: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  880: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  881: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  882: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  883: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  884: 
  885:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  886: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  887:     } else {
  888: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
  889: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
  890:     }
  891: 
  892:     $gradeTable.=&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.").'<br />'."\n".
  893: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  894: 
  895: # checkall buttons
  896:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  897:     $gradeTable.='<input type="button" '."\n".
  898: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  899: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  900:     $gradeTable.=&check_buttons();
  901:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
  902:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  903:     $gradeTable.= &Apache::loncommon::start_data_table().
  904: 	&Apache::loncommon::start_data_table_header_row();
  905:     my $loop = 0;
  906:     while ($loop < 2) {
  907: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  908: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  909: 	if ($env{'form.showgrading'} eq 'yes' 
  910: 	    && $submitonly ne 'queued'
  911: 	    && $submitonly ne 'all') {
  912: 	    foreach my $part (sort(@$partlist)) {
  913: 		my $display_part=
  914: 		    &get_display_part((split(/_/,$part))[0],$symb);
  915: 		$gradeTable.=
  916: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  917: 	    }
  918: 	} elsif ($submitonly eq 'queued') {
  919: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  920: 	}
  921: 	$loop++;
  922: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  923:     }
  924:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  925: 
  926:     my $ctr = 0;
  927:     foreach my $student (sort 
  928: 			 {
  929: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  930: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  931: 			     }
  932: 			     return $a cmp $b;
  933: 			 }
  934: 			 (keys(%$fullname))) {
  935: 	my ($uname,$udom) = split(/:/,$student);
  936: 
  937: 	my %status = ();
  938: 
  939: 	if ($submitonly eq 'queued') {
  940: 	    my %queue_status = 
  941: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  942: 							$udom,$uname);
  943: 	    next if (!defined($queue_status{'gradingqueue'}));
  944: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  945: 	}
  946: 
  947: 	if ($env{'form.showgrading'} eq 'yes' 
  948: 	    && $submitonly ne 'queued'
  949: 	    && $submitonly ne 'all') {
  950: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  951: 	    my $submitted = 0;
  952: 	    my $graded = 0;
  953: 	    my $incorrect = 0;
  954: 	    foreach (keys(%status)) {
  955: 		$submitted = 1 if ($status{$_} ne 'nothing');
  956: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  957: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  958: 		
  959: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  960: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  961: 		    $submitted = 0;
  962: 		    my ($part)=split(/\./,$partid);
  963: 		    $gradeTable.='<input type="hidden" name="'.
  964: 			$student.':'.$part.':submitted_by" value="'.
  965: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
  966: 		}
  967: 	    }
  968: 	    
  969: 	    next if (!$submitted && ($submitonly eq 'yes' ||
  970: 				     $submitonly eq 'incorrect' ||
  971: 				     $submitonly eq 'graded'));
  972: 	    next if (!$graded && ($submitonly eq 'graded'));
  973: 	    next if (!$incorrect && $submitonly eq 'incorrect');
  974: 	}
  975: 
  976: 	$ctr++;
  977: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  978:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  979: 	if ( $perm{'vgr'} eq 'F' ) {
  980: 	    if ($ctr%2 ==1) {
  981: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
  982: 	    }
  983: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
  984:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
  985:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
  986: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
  987: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
  988: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
  989: 
  990: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
  991: 		foreach (sort(keys(%status))) {
  992: 		    next if ($_ =~ /^resource.*?submitted_by$/);
  993: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
  994: 		}
  995: 	    }
  996: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
  997: 	    if ($ctr%2 ==0) {
  998: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
  999: 	    }
 1000: 	}
 1001:     }
 1002:     if ($ctr%2 ==1) {
 1003: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1004: 	    if ($env{'form.showgrading'} eq 'yes' 
 1005: 		&& $submitonly ne 'queued'
 1006: 		&& $submitonly ne 'all') {
 1007: 		foreach (@$partlist) {
 1008: 		    $gradeTable.='<td>&nbsp;</td>';
 1009: 		}
 1010: 	    } elsif ($submitonly eq 'queued') {
 1011: 		$gradeTable.='<td>&nbsp;</td>';
 1012: 	    }
 1013: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1014:     }
 1015: 
 1016:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1017: 	'<input type="button" '.
 1018: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1019: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1020:     if ($ctr == 0) {
 1021: 	my $num_students=(scalar(keys(%$fullname)));
 1022: 	if ($num_students eq 0) {
 1023: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1024: 	} else {
 1025: 	    my $submissions='submissions';
 1026: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1027: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1028: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1029: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1030: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1031: 		    $num_students).
 1032: 		'</span><br />';
 1033: 	}
 1034:     } elsif ($ctr == 1) {
 1035: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1036:     }
 1037:     $gradeTable.=&show_grading_menu_form($symb);
 1038:     $request->print($gradeTable);
 1039:     return '';
 1040: }
 1041: 
 1042: #---- Called from the listStudents routine
 1043: 
 1044: sub check_script {
 1045:     my ($form, $type)=@_;
 1046:     my $chkallscript='<script type="text/javascript">
 1047:     function checkall() {
 1048:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1049:             ele = document.forms.'.$form.'.elements[i];
 1050:             if (ele.name == "'.$type.'") {
 1051:             document.forms.'.$form.'.elements[i].checked=true;
 1052:                                        }
 1053:         }
 1054:     }
 1055: 
 1056:     function checksec() {
 1057:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1058:             ele = document.forms.'.$form.'.elements[i];
 1059:            string = document.forms.'.$form.'.chksec.value;
 1060:            if
 1061:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1062:               document.forms.'.$form.'.elements[i].checked=true;
 1063:             }
 1064:         }
 1065:     }
 1066: 
 1067: 
 1068:     function uncheckall() {
 1069:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1070:             ele = document.forms.'.$form.'.elements[i];
 1071:             if (ele.name == "'.$type.'") {
 1072:             document.forms.'.$form.'.elements[i].checked=false;
 1073:                                        }
 1074:         }
 1075:     }
 1076: 
 1077: </script>'."\n";
 1078:     return $chkallscript;
 1079: }
 1080: 
 1081: sub check_buttons {
 1082:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1083:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1084:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1085:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1086:     return $buttons;
 1087: }
 1088: 
 1089: #     Displays the submissions for one student or a group of students
 1090: sub processGroup {
 1091:     my ($request)  = shift;
 1092:     my $ctr        = 0;
 1093:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1094:     my $total      = scalar(@stuchecked)-1;
 1095: 
 1096:     foreach my $student (@stuchecked) {
 1097: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1098: 	$env{'form.student'}        = $uname;
 1099: 	$env{'form.userdom'}        = $udom;
 1100: 	$env{'form.fullname'}       = $fullname;
 1101: 	&submission($request,$ctr,$total);
 1102: 	$ctr++;
 1103:     }
 1104:     return '';
 1105: }
 1106: 
 1107: #------------------------------------------------------------------------------------
 1108: #
 1109: #-------------------------- Next few routines handles grading by student, essentially
 1110: #                           handles essay response type problem/part
 1111: #
 1112: #--- Javascript to handle the submission page functionality ---
 1113: sub sub_page_js {
 1114:     my $request = shift;
 1115: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1116:     $request->print(<<SUBJAVASCRIPT);
 1117: <script type="text/javascript" language="javascript">
 1118:     function updateRadio(formname,id,weight) {
 1119: 	var gradeBox = formname["GD_BOX"+id];
 1120: 	var radioButton = formname["RADVAL"+id];
 1121: 	var oldpts = formname["oldpts"+id].value;
 1122: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1123: 	gradeBox.value = pts;
 1124: 	var resetbox = false;
 1125: 	if (isNaN(pts) || pts < 0) {
 1126: 	    alert("$alertmsg"+pts);
 1127: 	    for (var i=0; i<radioButton.length; i++) {
 1128: 		if (radioButton[i].checked) {
 1129: 		    gradeBox.value = i;
 1130: 		    resetbox = true;
 1131: 		}
 1132: 	    }
 1133: 	    if (!resetbox) {
 1134: 		formtextbox.value = "";
 1135: 	    }
 1136: 	    return;
 1137: 	}
 1138: 
 1139: 	if (pts > weight) {
 1140: 	    var resp = confirm("You entered a value ("+pts+
 1141: 			       ") greater than the weight for the part. Accept?");
 1142: 	    if (resp == false) {
 1143: 		gradeBox.value = oldpts;
 1144: 		return;
 1145: 	    }
 1146: 	}
 1147: 
 1148: 	for (var i=0; i<radioButton.length; i++) {
 1149: 	    radioButton[i].checked=false;
 1150: 	    if (pts == i && pts != "") {
 1151: 		radioButton[i].checked=true;
 1152: 	    }
 1153: 	}
 1154: 	updateSelect(formname,id);
 1155: 	formname["stores"+id].value = "0";
 1156:     }
 1157: 
 1158:     function writeBox(formname,id,pts) {
 1159: 	var gradeBox = formname["GD_BOX"+id];
 1160: 	if (checkSolved(formname,id) == 'update') {
 1161: 	    gradeBox.value = pts;
 1162: 	} else {
 1163: 	    var oldpts = formname["oldpts"+id].value;
 1164: 	    gradeBox.value = oldpts;
 1165: 	    var radioButton = formname["RADVAL"+id];
 1166: 	    for (var i=0; i<radioButton.length; i++) {
 1167: 		radioButton[i].checked=false;
 1168: 		if (i == oldpts) {
 1169: 		    radioButton[i].checked=true;
 1170: 		}
 1171: 	    }
 1172: 	}
 1173: 	formname["stores"+id].value = "0";
 1174: 	updateSelect(formname,id);
 1175: 	return;
 1176:     }
 1177: 
 1178:     function clearRadBox(formname,id) {
 1179: 	if (checkSolved(formname,id) == 'noupdate') {
 1180: 	    updateSelect(formname,id);
 1181: 	    return;
 1182: 	}
 1183: 	gradeSelect = formname["GD_SEL"+id];
 1184: 	for (var i=0; i<gradeSelect.length; i++) {
 1185: 	    if (gradeSelect[i].selected) {
 1186: 		var selectx=i;
 1187: 	    }
 1188: 	}
 1189: 	var stores = formname["stores"+id];
 1190: 	if (selectx == stores.value) { return };
 1191: 	var gradeBox = formname["GD_BOX"+id];
 1192: 	gradeBox.value = "";
 1193: 	var radioButton = formname["RADVAL"+id];
 1194: 	for (var i=0; i<radioButton.length; i++) {
 1195: 	    radioButton[i].checked=false;
 1196: 	}
 1197: 	stores.value = selectx;
 1198:     }
 1199: 
 1200:     function checkSolved(formname,id) {
 1201: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1202: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1203: 	    if (!reply) {return "noupdate";}
 1204: 	    formname.overRideScore.value = 'yes';
 1205: 	}
 1206: 	return "update";
 1207:     }
 1208: 
 1209:     function updateSelect(formname,id) {
 1210: 	formname["GD_SEL"+id][0].selected = true;
 1211: 	return;
 1212:     }
 1213: 
 1214: //=========== Check that a point is assigned for all the parts  ============
 1215:     function checksubmit(formname,val,total,parttot) {
 1216: 	formname.gradeOpt.value = val;
 1217: 	if (val == "Save & Next") {
 1218: 	    for (i=0;i<=total;i++) {
 1219: 		for (j=0;j<parttot;j++) {
 1220: 		    var partid = formname["partid"+i+"_"+j].value;
 1221: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1222: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1223: 			if (points == "") {
 1224: 			    var name = formname["name"+i].value;
 1225: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1226: 			    var resp = confirm("You did not assign a score for "+studentID+
 1227: 					       ", part "+partid+". Continue?");
 1228: 			    if (resp == false) {
 1229: 				formname["GD_BOX"+i+"_"+partid].focus();
 1230: 				return false;
 1231: 			    }
 1232: 			}
 1233: 		    }
 1234: 		    
 1235: 		}
 1236: 	    }
 1237: 	    
 1238: 	}
 1239: 	if (val == "Grade Student") {
 1240: 	    formname.showgrading.value = "yes";
 1241: 	    if (formname.Status.value == "") {
 1242: 		formname.Status.value = "Active";
 1243: 	    }
 1244: 	    formname.studentNo.value = total;
 1245: 	}
 1246: 	formname.submit();
 1247:     }
 1248: 
 1249: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1250:     function checkSubmitPage(formname,total) {
 1251: 	noscore = new Array(100);
 1252: 	var ptr = 0;
 1253: 	for (i=1;i<total;i++) {
 1254: 	    var partid = formname["q_"+i].value;
 1255: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1256: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1257: 		var status = formname["solved"+i+"_"+partid].value;
 1258: 		if (points == "" && status != "correct_by_student") {
 1259: 		    noscore[ptr] = i;
 1260: 		    ptr++;
 1261: 		}
 1262: 	    }
 1263: 	}
 1264: 	if (ptr != 0) {
 1265: 	    var sense = ptr == 1 ? ": " : "s: ";
 1266: 	    var prolist = "";
 1267: 	    if (ptr == 1) {
 1268: 		prolist = noscore[0];
 1269: 	    } else {
 1270: 		var i = 0;
 1271: 		while (i < ptr-1) {
 1272: 		    prolist += noscore[i]+", ";
 1273: 		    i++;
 1274: 		}
 1275: 		prolist += "and "+noscore[i];
 1276: 	    }
 1277: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1278: 	    if (resp == false) {
 1279: 		return false;
 1280: 	    }
 1281: 	}
 1282: 
 1283: 	formname.submit();
 1284:     }
 1285: </script>
 1286: SUBJAVASCRIPT
 1287: }
 1288: 
 1289: #--- javascript for essay type problem --
 1290: sub sub_page_kw_js {
 1291:     my $request = shift;
 1292:     my $iconpath = $request->dir_config('lonIconsURL');
 1293:     &commonJSfunctions($request);
 1294: 
 1295:     my $inner_js_msg_central=<<INNERJS;
 1296:     <script text="text/javascript">
 1297:     function checkInput() {
 1298:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1299:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1300:       var usrctr = document.msgcenter.usrctr.value;
 1301:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1302:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1303: 
 1304:       var msgchk = "";
 1305:       if (document.msgcenter.subchk.checked) {
 1306:          msgchk = "msgsub,";
 1307:       }
 1308:       var includemsg = 0;
 1309:       for (var i=1; i<=nmsg; i++) {
 1310:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1311:           var frmmsg = document.msgcenter["msg"+i];
 1312:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1313:           var showflg = opener.document.SCORE["shownOnce"+i];
 1314:           showflg.value = "1";
 1315:           var chkbox = document.msgcenter["msgn"+i];
 1316:           if (chkbox.checked) {
 1317:              msgchk += "savemsg"+i+",";
 1318:              includemsg = 1;
 1319:           }
 1320:       }
 1321:       if (document.msgcenter.newmsgchk.checked) {
 1322:          msgchk += "newmsg"+usrctr;
 1323:          includemsg = 1;
 1324:       }
 1325:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1326:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1327:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1328:       includemsg.value = msgchk;
 1329: 
 1330:       self.close()
 1331: 
 1332:     }
 1333:     </script>
 1334: INNERJS
 1335: 
 1336:     my $inner_js_highlight_central=<<INNERJS;
 1337:  <script type="text/javascript">
 1338:     function updateChoice(flag) {
 1339:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1340:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1341:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1342:       opener.document.SCORE.refresh.value = "on";
 1343:       if (opener.document.SCORE.keywords.value!=""){
 1344:          opener.document.SCORE.submit();
 1345:       }
 1346:       self.close()
 1347:     }
 1348: </script>
 1349: INNERJS
 1350: 
 1351:     my $start_page_msg_central = 
 1352:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1353: 				       {'js_ready'  => 1,
 1354: 					'only_body' => 1,
 1355: 					'bgcolor'   =>'#FFFFFF',});
 1356:     my $end_page_msg_central = 
 1357: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1358: 
 1359: 
 1360:     my $start_page_highlight_central = 
 1361:         &Apache::loncommon::start_page('Highlight Central',
 1362: 				       $inner_js_highlight_central,
 1363: 				       {'js_ready'  => 1,
 1364: 					'only_body' => 1,
 1365: 					'bgcolor'   =>'#FFFFFF',});
 1366:     my $end_page_highlight_central = 
 1367: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1368: 
 1369:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1370:     $docopen=~s/^document\.//;
 1371:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1372:     $request->print(<<SUBJAVASCRIPT);
 1373: <script type="text/javascript" language="javascript">
 1374: 
 1375: //===================== Show list of keywords ====================
 1376:   function keywords(formname) {
 1377:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1378:     if (nret==null) return;
 1379:     formname.keywords.value = nret;
 1380: 
 1381:     if (formname.keywords.value != "") {
 1382: 	formname.refresh.value = "on";
 1383: 	formname.submit();
 1384:     }
 1385:     return;
 1386:   }
 1387: 
 1388: //===================== Script to view submitted by ==================
 1389:   function viewSubmitter(submitter) {
 1390:     document.SCORE.refresh.value = "on";
 1391:     document.SCORE.NCT.value = "1";
 1392:     document.SCORE.unamedom0.value = submitter;
 1393:     document.SCORE.submit();
 1394:     return;
 1395:   }
 1396: 
 1397: //===================== Script to add keyword(s) ==================
 1398:   function getSel() {
 1399:     if (document.getSelection) txt = document.getSelection();
 1400:     else if (document.selection) txt = document.selection.createRange().text;
 1401:     else return;
 1402:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1403:     if (cleantxt=="") {
 1404: 	alert("$alertmsg");
 1405: 	return;
 1406:     }
 1407:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1408:     if (nret==null) return;
 1409:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1410:     if (document.SCORE.keywords.value != "") {
 1411: 	document.SCORE.refresh.value = "on";
 1412: 	document.SCORE.submit();
 1413:     }
 1414:     return;
 1415:   }
 1416: 
 1417: //====================== Script for composing message ==============
 1418:    // preload images
 1419:    img1 = new Image();
 1420:    img1.src = "$iconpath/mailbkgrd.gif";
 1421:    img2 = new Image();
 1422:    img2.src = "$iconpath/mailto.gif";
 1423: 
 1424:   function msgCenter(msgform,usrctr,fullname) {
 1425:     var Nmsg  = msgform.savemsgN.value;
 1426:     savedMsgHeader(Nmsg,usrctr,fullname);
 1427:     var subject = msgform.msgsub.value;
 1428:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1429:     re = /msgsub/;
 1430:     var shwsel = "";
 1431:     if (re.test(msgchk)) { shwsel = "checked" }
 1432:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1433:     displaySubject(checkEntities(subject),shwsel);
 1434:     for (var i=1; i<=Nmsg; i++) {
 1435: 	var testmsg = "savemsg"+i+",";
 1436: 	re = new RegExp(testmsg,"g");
 1437: 	shwsel = "";
 1438: 	if (re.test(msgchk)) { shwsel = "checked" }
 1439: 	var message = document.SCORE["savemsg"+i].value;
 1440: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1441: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1442: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1443:     }
 1444:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1445:     shwsel = "";
 1446:     re = /newmsg/;
 1447:     if (re.test(msgchk)) { shwsel = "checked" }
 1448:     newMsg(newmsg,shwsel);
 1449:     msgTail(); 
 1450:     return;
 1451:   }
 1452: 
 1453:   function checkEntities(strx) {
 1454:     if (strx.length == 0) return strx;
 1455:     var orgStr = ["&", "<", ">", '"']; 
 1456:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1457:     var counter = 0;
 1458:     while (counter < 4) {
 1459: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1460: 	counter++;
 1461:     }
 1462:     return strx;
 1463:   }
 1464: 
 1465:   function strReplace(strx, orgStr, newStr) {
 1466:     return strx.split(orgStr).join(newStr);
 1467:   }
 1468: 
 1469:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1470:     var height = 70*Nmsg+250;
 1471:     var scrollbar = "no";
 1472:     if (height > 600) {
 1473: 	height = 600;
 1474: 	scrollbar = "yes";
 1475:     }
 1476:     var xpos = (screen.width-600)/2;
 1477:     xpos = (xpos < 0) ? '0' : xpos;
 1478:     var ypos = (screen.height-height)/2-30;
 1479:     ypos = (ypos < 0) ? '0' : ypos;
 1480: 
 1481:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1482:     pWin.focus();
 1483:     pDoc = pWin.document;
 1484:     pDoc.$docopen;
 1485:     pDoc.write('$start_page_msg_central');
 1486: 
 1487:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1488:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1489:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1490: 
 1491:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1492:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1493:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1494: }
 1495:     function displaySubject(msg,shwsel) {
 1496:     pDoc = pWin.document;
 1497:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1498:     pDoc.write("<td>Subject<\\/td>");
 1499:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1500:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1501: }
 1502: 
 1503:   function displaySavedMsg(ctr,msg,shwsel) {
 1504:     pDoc = pWin.document;
 1505:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1506:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1507:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1508:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1509: }
 1510: 
 1511:   function newMsg(newmsg,shwsel) {
 1512:     pDoc = pWin.document;
 1513:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1514:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1515:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1516:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1517: }
 1518: 
 1519:   function msgTail() {
 1520:     pDoc = pWin.document;
 1521:     pDoc.write("<\\/table>");
 1522:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1523:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1524:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1525:     pDoc.write("<\\/form>");
 1526:     pDoc.write('$end_page_msg_central');
 1527:     pDoc.close();
 1528: }
 1529: 
 1530: //====================== Script for keyword highlight options ==============
 1531:   function kwhighlight() {
 1532:     var kwclr    = document.SCORE.kwclr.value;
 1533:     var kwsize   = document.SCORE.kwsize.value;
 1534:     var kwstyle  = document.SCORE.kwstyle.value;
 1535:     var redsel = "";
 1536:     var grnsel = "";
 1537:     var blusel = "";
 1538:     if (kwclr=="red")   {var redsel="checked"};
 1539:     if (kwclr=="green") {var grnsel="checked"};
 1540:     if (kwclr=="blue")  {var blusel="checked"};
 1541:     var sznsel = "";
 1542:     var sz1sel = "";
 1543:     var sz2sel = "";
 1544:     if (kwsize=="0")  {var sznsel="checked"};
 1545:     if (kwsize=="+1") {var sz1sel="checked"};
 1546:     if (kwsize=="+2") {var sz2sel="checked"};
 1547:     var synsel = "";
 1548:     var syisel = "";
 1549:     var sybsel = "";
 1550:     if (kwstyle=="")    {var synsel="checked"};
 1551:     if (kwstyle=="<i>") {var syisel="checked"};
 1552:     if (kwstyle=="<b>") {var sybsel="checked"};
 1553:     highlightCentral();
 1554:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1555:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1556:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1557:     highlightend();
 1558:     return;
 1559:   }
 1560: 
 1561:   function highlightCentral() {
 1562: //    if (window.hwdWin) window.hwdWin.close();
 1563:     var xpos = (screen.width-400)/2;
 1564:     xpos = (xpos < 0) ? '0' : xpos;
 1565:     var ypos = (screen.height-330)/2-30;
 1566:     ypos = (ypos < 0) ? '0' : ypos;
 1567: 
 1568:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1569:     hwdWin.focus();
 1570:     var hDoc = hwdWin.document;
 1571:     hDoc.$docopen;
 1572:     hDoc.write('$start_page_highlight_central');
 1573:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1574:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1575: 
 1576:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1577:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1578:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1579:   }
 1580: 
 1581:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1582:     var hDoc = hwdWin.document;
 1583:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1584:     hDoc.write("<td align=\\"left\\">");
 1585:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1586:     hDoc.write("<td align=\\"left\\">");
 1587:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1588:     hDoc.write("<td align=\\"left\\">");
 1589:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1590:     hDoc.write("<\\/tr>");
 1591:   }
 1592: 
 1593:   function highlightend() { 
 1594:     var hDoc = hwdWin.document;
 1595:     hDoc.write("<\\/table>");
 1596:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1597:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1598:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1599:     hDoc.write("<\\/form>");
 1600:     hDoc.write('$end_page_highlight_central');
 1601:     hDoc.close();
 1602:   }
 1603: 
 1604: </script>
 1605: SUBJAVASCRIPT
 1606: }
 1607: 
 1608: sub get_increment {
 1609:     my $increment = $env{'form.increment'};
 1610:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1611:         $increment != .1) {
 1612:         $increment = 1;
 1613:     }
 1614:     return $increment;
 1615: }
 1616: 
 1617: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1618: sub gradeBox {
 1619:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1620:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1621: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1622:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1623:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1624:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1625:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1626:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1627: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1628:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1629:     my $display_part= &get_display_part($partid,$symb);
 1630:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1631: 				       [$partid]);
 1632:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1633:     if ($last_resets{$partid}) {
 1634:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1635:     }
 1636:     $result.='<table border="0"><tr>';
 1637:     my $ctr = 0;
 1638:     my $thisweight = 0;
 1639:     my $increment = &get_increment();
 1640: 
 1641:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1642:     while ($thisweight<=$wgt) {
 1643: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1644: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1645: 	    $thisweight.')" value="'.$thisweight.'" '.
 1646: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1647: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1648:         $thisweight += $increment;
 1649: 	$ctr++;
 1650:     }
 1651:     $radio.='</tr></table>';
 1652: 
 1653:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1654: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1655: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1656: 	$wgt.')" /></td>'."\n";
 1657:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1658: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1659: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1660:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1661: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1662:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1663: 	$line.='<option></option>'.
 1664: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1665:     } else {
 1666: 	$line.='<option selected="selected"></option>'.
 1667: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1668:     }
 1669:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1670: 
 1671: 
 1672: 	#&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
 1673:     $result .= 
 1674: 	    '<td><b>'.&mt('Part').':</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points').':</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>'.
 1675:     
 1676:     $result.='</tr></table>'."\n";
 1677:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1678: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1679: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1680: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1681:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1682:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1683:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1684:         $aggtries.'" />'."\n";
 1685:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1686:     return $result;
 1687: }
 1688: 
 1689: sub handback_box {
 1690:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1691:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1692:     my (@respids);
 1693:      my @part_response_id = &flatten_responseType($responseType);
 1694:     foreach my $part_response_id (@part_response_id) {
 1695:     	my ($part,$resp) = @{ $part_response_id };
 1696:         if ($part eq $partid) {
 1697:             push(@respids,$resp);
 1698:         }
 1699:     }
 1700:     my $result;
 1701:     foreach my $respid (@respids) {
 1702: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1703: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1704: 	next if (!@$files);
 1705: 	my $file_counter = 1;
 1706: 	foreach my $file (@$files) {
 1707: 	    if ($file =~ /\/portfolio\//) {
 1708:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1709:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1710:     	        $file_disp = "$name.$ext";
 1711:     	        $file = $file_path.$file_disp;
 1712:     	        $result.=&mt('Return commented version of [_1] to student.',
 1713:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1714:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1715:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1716:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1717:     	        $file_counter++;
 1718: 	    }
 1719: 	}
 1720:     }
 1721:     return $result;    
 1722: }
 1723: 
 1724: sub show_problem {
 1725:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1726:     my $rendered;
 1727:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1728:     &Apache::lonxml::remember_problem_counter();
 1729:     if ($mode eq 'both' or $mode eq 'text') {
 1730: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1731: 						       $env{'request.course.id'},
 1732: 						       undef,\%form);
 1733:     }
 1734:     if ($removeform) {
 1735: 	$rendered=~s|<form(.*?)>||g;
 1736: 	$rendered=~s|</form>||g;
 1737: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1738:     }
 1739:     my $companswer;
 1740:     if ($mode eq 'both' or $mode eq 'answer') {
 1741: 	&Apache::lonxml::restore_problem_counter();
 1742: 	$companswer=
 1743: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1744: 						    $env{'request.course.id'},
 1745: 						    %form);
 1746:     }
 1747:     if ($removeform) {
 1748: 	$companswer=~s|<form(.*?)>||g;
 1749: 	$companswer=~s|</form>||g;
 1750: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1751:     }
 1752:     $rendered=
 1753: 	'<div class="LC_grade_show_problem_header">'.
 1754: 	&mt('View of the problem').
 1755: 	'</div><div class="LC_grade_show_problem_problem">'.
 1756: 	$rendered.
 1757: 	'</div>';
 1758:     $companswer=
 1759: 	'<div class="LC_grade_show_problem_header">'.
 1760: 	&mt('Correct answer').
 1761: 	'</div><div class="LC_grade_show_problem_problem">'.
 1762: 	$companswer.
 1763: 	'</div>';
 1764:     my $result;
 1765:     if ($mode eq 'both') {
 1766: 	$result=$rendered.$companswer;
 1767:     } elsif ($mode eq 'text') {
 1768: 	$result=$rendered;
 1769:     } elsif ($mode eq 'answer') {
 1770: 	$result=$companswer;
 1771:     }
 1772:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1773:     return $result;
 1774: }
 1775: 
 1776: sub files_exist {
 1777:     my ($r, $symb) = @_;
 1778:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1779: 
 1780:     foreach my $student (@students) {
 1781:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1782:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1783: 					      $udom,$uname);
 1784:         my ($string,$timestamp)= &get_last_submission(\%record);
 1785:         foreach my $submission (@$string) {
 1786:             my ($partid,$respid) =
 1787: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1788:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1789: 					   \%record);
 1790:             return 1 if (@$files);
 1791:         }
 1792:     }
 1793:     return 0;
 1794: }
 1795: 
 1796: sub download_all_link {
 1797:     my ($r,$symb) = @_;
 1798:     my $all_students = 
 1799: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1800: 
 1801:     my $parts =
 1802: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1803: 
 1804:     my $identifier = &Apache::loncommon::get_cgi_id();
 1805:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1806:                              'cgi.'.$identifier.'.symb' => $symb,
 1807:                              'cgi.'.$identifier.'.parts' => $parts,});
 1808:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1809: 	      &mt('Download All Submitted Documents').'</a>');
 1810:     return
 1811: }
 1812: 
 1813: sub build_section_inputs {
 1814:     my $section_inputs;
 1815:     if ($env{'form.section'} eq '') {
 1816:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1817:     } else {
 1818:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1819:         foreach my $section (@sections) {
 1820:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1821:         }
 1822:     }
 1823:     return $section_inputs;
 1824: }
 1825: 
 1826: # --------------------------- show submissions of a student, option to grade 
 1827: sub submission {
 1828:     my ($request,$counter,$total) = @_;
 1829:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1830:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1831:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1832:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1833:     my $symb = &get_symb($request); 
 1834:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1835: 
 1836:     if (!&canview($usec)) {
 1837: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1838: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1839: 			$env{'request.course.id'}.')</span>');
 1840: 	$request->print(&show_grading_menu_form($symb));
 1841: 	return;
 1842:     }
 1843: 
 1844:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1845:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1846:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1847:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1848:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1849: 	'" src="'.$request->dir_config('lonIconsURL').
 1850: 	'/check.gif" height="16" border="0" />';
 1851: 
 1852:     my %old_essays;
 1853:     # header info
 1854:     if ($counter == 0) {
 1855: 	&sub_page_js($request);
 1856: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1857: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1858: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1859: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1860: 	    &download_all_link($request, $symb);
 1861: 	}
 1862: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1863: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1864: 
 1865: 	# option to display problem, only once else it cause problems 
 1866:         # with the form later since the problem has a form.
 1867: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1868: 	    my $mode;
 1869: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1870: 		$mode='both';
 1871: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1872: 		$mode='text';
 1873: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1874: 		$mode='answer';
 1875: 	    }
 1876: 	    &Apache::lonxml::clear_problem_counter();
 1877: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1878: 	}
 1879: 
 1880: 	# kwclr is the only variable that is guaranteed to be non blank 
 1881:         # if this subroutine has been called once.
 1882: 	my %keyhash = ();
 1883: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1884: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1885: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1886: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1887: 
 1888: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1889: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1890: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1891: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1892: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1893: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1894: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1895: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1896: 	}
 1897: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1898: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1899: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1900: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1901: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1902: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1903: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1904: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1905: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1906: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1907: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1908: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1909: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1910: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1911: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1912: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1913: 			&build_section_inputs().
 1914: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1915: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1916: 			'<input type="hidden" name="NCT"'.
 1917: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1918: 	if ($env{'form.handgrade'} eq 'yes') {
 1919: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1920: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1921: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1922: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1923: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1924: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1925: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1926: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1927: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1928: 	    }
 1929: 	}
 1930: 	
 1931: 	my ($cts,$prnmsg) = (1,'');
 1932: 	while ($cts <= $env{'form.savemsgN'}) {
 1933: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1934: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1935: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1936: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1937: 		'" />'."\n".
 1938: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1939: 	    $cts++;
 1940: 	}
 1941: 	$request->print($prnmsg);
 1942: 
 1943: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1944: #
 1945: # Print out the keyword options line
 1946: #
 1947: 	    $request->print(<<KEYWORDS);
 1948: &nbsp;<b>Keyword Options:</b>&nbsp;
 1949: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1950: <a href="#" onMouseDown="javascript:getSel(); return false"
 1951:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1952: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1953: KEYWORDS
 1954: #
 1955: # Load the other essays for similarity check
 1956: #
 1957:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1958: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1959: 	    $apath=&escape($apath);
 1960: 	    $apath=~s/\W/\_/gs;
 1961: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 1962:         }
 1963:     }
 1964: 
 1965: # This is where output for one specific student would start
 1966:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 1967:     $request->print("\n\n".
 1968:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 1969: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 1970: 		    '<div class="LC_grade_show_user_body">'."\n");
 1971: 
 1972:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 1973: 	my $mode;
 1974: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 1975: 	    $mode='both';
 1976: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 1977: 	    $mode='text';
 1978: 	} elsif ($env{'form.vAns'} eq 'all') {
 1979: 	    $mode='answer';
 1980: 	}
 1981: 	&Apache::lonxml::clear_problem_counter();
 1982: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 1983:     }
 1984: 
 1985:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 1986:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1987: 
 1988:     # Display student info
 1989:     $request->print(($counter == 0 ? '' : '<br />'));
 1990:     my $result='<div class="LC_grade_submissions">';
 1991:     
 1992:     $result.='<div class="LC_grade_submissions_header">';
 1993:     $result.= &mt('Submissions');
 1994:     $result.='<input type="hidden" name="name'.$counter.
 1995: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 1996:     if ($env{'form.handgrade'} eq 'no') {
 1997: 	$result.='<span class="LC_grade_check_note">'.
 1998: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 1999: 
 2000:     }
 2001: 
 2002: 
 2003: 
 2004:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2005:     my $fullname;
 2006:     my $col_fullnames = [];
 2007:     if ($env{'form.handgrade'} eq 'yes') {
 2008: 	(my $sub_result,$fullname,$col_fullnames)=
 2009: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2010: 				 $counter);
 2011: 	$result.=$sub_result;
 2012:     }
 2013:     $request->print($result."\n");
 2014:     $request->print('</div>'."\n");
 2015:     # print student answer/submission
 2016:     # Options are (1) Handgaded submission only
 2017:     #             (2) Last submission, includes submission that is not handgraded 
 2018:     #                  (for multi-response type part)
 2019:     #             (3) Last submission plus the parts info
 2020:     #             (4) The whole record for this student
 2021:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2022: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2023: 	
 2024: 	my $lastsubonly;
 2025: 
 2026: 	if ($$timestamp eq '') {
 2027: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2028: 	} else {
 2029: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2030: 
 2031: 	    my %seenparts;
 2032: 	    my @part_response_id = &flatten_responseType($responseType);
 2033: 	    foreach my $part (@part_response_id) {
 2034: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2035: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2036: 
 2037: 		my ($partid,$respid) = @{ $part };
 2038: 		my $display_part=&get_display_part($partid,$symb);
 2039: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2040: 		    if (exists($seenparts{$partid})) { next; }
 2041: 		    $seenparts{$partid}=1;
 2042: 		    my $submitby='<b>Part:</b> '.$display_part.
 2043: 			' <b>Collaborative submission by:</b> '.
 2044: 			'<a href="javascript:viewSubmitter(\''.
 2045: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2046: 			'\');" target="_self">'.
 2047: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2048: 		    $request->print($submitby);
 2049: 		    next;
 2050: 		}
 2051: 		my $responsetype = $responseType->{$partid}->{$respid};
 2052: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2053: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2054: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2055: 			' )</span>&nbsp; &nbsp;'.
 2056: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2057: 		    next;
 2058: 		}
 2059: 		foreach my $submission (@$string) {
 2060: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2061: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2062: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2063: 		    # Similarity check
 2064: 		    my $similar='';
 2065: 		    if($env{'form.checkPlag'}){
 2066: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2067: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2068: 			if ($osim) {
 2069: 			    $osim=int($osim*100.0);
 2070: 			    my %old_course_desc = 
 2071: 				&Apache::lonnet::coursedescription($ocrsid,
 2072: 								   {'one_time' => 1});
 2073: 
 2074: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2075: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2076: 				    $osim,
 2077: 				    &Apache::loncommon::plainname($oname,$odom),
 2078: 				    $oname,$odom,
 2079: 				    $old_course_desc{'description'},
 2080: 				    $old_course_desc{'num'},
 2081: 				    $old_course_desc{'domain'}).
 2082: 				'</span></h3><blockquote><i>'.
 2083: 				&keywords_highlight($oessay).
 2084: 				'</i></blockquote><hr />';
 2085: 			}
 2086: 		    }
 2087: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2088: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2089: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2090: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2091: 			my $display_part=&get_display_part($partid,$symb);
 2092: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2093: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2094: 			    ' )</span>&nbsp; &nbsp;';
 2095: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2096: 			if (@$files) {
 2097: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2098: 			    my $file_counter = 0;
 2099: 			    foreach my $file (@$files) {
 2100: 			        $file_counter++;
 2101: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2102: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2103: 			    }
 2104: 			    $lastsubonly.='<br />';
 2105: 			}
 2106: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2107: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2108: 					 $respid,\%record,$order);
 2109: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2110: 			$lastsubonly.='</div>';
 2111: 		    }
 2112: 		}
 2113: 	    }
 2114: 	    $lastsubonly.='</div>'."\n";
 2115: 	}
 2116: 	$request->print($lastsubonly);
 2117:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2118: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2119: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2120:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2121: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2122: 								 $env{'request.course.id'},
 2123: 								 $last,'.submission',
 2124: 								 'Apache::grades::keywords_highlight'));
 2125:     }
 2126: 
 2127:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2128: 	.$udom.'" />'."\n");
 2129:     # return if view submission with no grading option
 2130:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2131: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2132: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2133: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2134: 	$toGrade.='</div>'."\n";
 2135: 	if (($env{'form.command'} eq 'submission') || 
 2136: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2137: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2138: 	}
 2139: 	$request->print($toGrade);
 2140: 	return;
 2141:     } else {
 2142: 	$request->print('</div>'."\n");
 2143:     }
 2144: 
 2145:     # essay grading message center
 2146:     if ($env{'form.handgrade'} eq 'yes') {
 2147: 	my $result='<div class="LC_grade_message_center">';
 2148:     
 2149: 	$result.='<div class="LC_grade_message_center_header">'.
 2150: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2151: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2152: 	my $msgfor = $givenn.' '.$lastname;
 2153: 	if (scalar(@$col_fullnames) > 0) {
 2154: 	    my $lastone = pop(@$col_fullnames);
 2155: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2156: 	}
 2157: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2158: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2159: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2160: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2161: 	    ',\''.$msgfor.'\');" target="_self">'.
 2162: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2163: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2164: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2165: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2166: 	    '<br />&nbsp;('.
 2167: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2168: 	$result.='</div></div>';
 2169: 	$request->print($result);
 2170:     }
 2171: 
 2172:     my %seen = ();
 2173:     my @partlist;
 2174:     my @gradePartRespid;
 2175:     my @part_response_id = &flatten_responseType($responseType);
 2176:     $request->print('<div class="LC_grade_assign">'.
 2177: 		    
 2178: 		    '<div class="LC_grade_assign_header">'.
 2179: 		    &mt('Assign Grades').'</div>'.
 2180: 		    '<div class="LC_grade_assign_body">');
 2181:     foreach my $part_response_id (@part_response_id) {
 2182:     	my ($partid,$respid) = @{ $part_response_id };
 2183: 	my $part_resp = join('_',@{ $part_response_id });
 2184: 	next if ($seen{$partid} > 0);
 2185: 	$seen{$partid}++;
 2186: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2187: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2188: 	push(@partlist,$partid);
 2189: 	push(@gradePartRespid,$partid.'.'.$respid);
 2190: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2191:     }
 2192:     $request->print('</div></div>');
 2193: 
 2194:     $request->print('<div class="LC_grade_info_links">');
 2195:     if ($perm{'vgr'}) {
 2196: 	$request->print(
 2197: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2198: 						   $uname,$udom,'check'));
 2199:     }
 2200:     if ($perm{'opa'}) {
 2201: 	$request->print(
 2202: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2203: 					 $uname,$udom,$symb,'check'));
 2204:     }
 2205:     $request->print('</div>');
 2206: 
 2207:     $result='<input type="hidden" name="partlist'.$counter.
 2208: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2209:     $result.='<input type="hidden" name="gradePartRespid'.
 2210: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2211:     my $ctr = 0;
 2212:     while ($ctr < scalar(@partlist)) {
 2213: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2214: 	    $partlist[$ctr].'" />'."\n";
 2215: 	$ctr++;
 2216:     }
 2217:     $request->print($result.''."\n");
 2218: 
 2219: # Done with printing info for one student
 2220: 
 2221:     $request->print('</div>');#LC_grade_show_user_body
 2222:     $request->print('</div>');#LC_grade_show_user
 2223: 
 2224: 
 2225:     # print end of form
 2226:     if ($counter == $total) {
 2227: 	my $endform='<table border="0"><tr><td>'."\n";
 2228: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2229: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2230: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2231: 	my $ntstu ='<select name="NTSTU">'.
 2232: 	    '<option>1</option><option>2</option>'.
 2233: 	    '<option>3</option><option>5</option>'.
 2234: 	    '<option>7</option><option>10</option></select>'."\n";
 2235: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2236: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2237: 	$endform.=&mt('[quant,_1,student]',$ntstu);
 2238: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2239: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2240: 	    '<input type="button" value="'.&mt('Next').'" '.
 2241: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2242: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2243:         $endform.="<input type='hidden' value='".&get_increment().
 2244:             "' name='increment' />";
 2245: 	$endform.='</td></tr></table></form>';
 2246: 	$endform.=&show_grading_menu_form($symb);
 2247: 	$request->print($endform);
 2248:     }
 2249:     return '';
 2250: }
 2251: 
 2252: sub check_collaborators {
 2253:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2254:     my ($result,@col_fullnames);
 2255:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2256:     foreach my $part (keys(%$handgrade)) {
 2257: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2258: 					'.maxcollaborators',
 2259: 					$symb,$udom,$uname);
 2260: 	next if ($ncol <= 0);
 2261: 	$part =~ s/\_/\./g;
 2262: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2263: 	my (@good_collaborators, @bad_collaborators);
 2264: 	foreach my $possible_collaborator
 2265: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2266: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2267: 	    next if ($possible_collaborator eq '');
 2268: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2269: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2270: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2271: 	    # Doing this grep allows 'fuzzy' specification
 2272: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2273: 			       keys(%$classlist));
 2274: 	    if (! scalar(@matches)) {
 2275: 		push(@bad_collaborators, $possible_collaborator);
 2276: 	    } else {
 2277: 		push(@good_collaborators, @matches);
 2278: 	    }
 2279: 	}
 2280: 	if (scalar(@good_collaborators) != 0) {
 2281: 	    $result.='<br />'.&mt('Collaborators: ');
 2282: 	    foreach my $name (@good_collaborators) {
 2283: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2284: 		push(@col_fullnames, $givenn.' '.$lastname);
 2285: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2286: 	    }
 2287: 	    $result.='<br />'."\n";
 2288: 	    my ($part)=split(/\./,$part);
 2289: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2290: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2291: 		"\n";
 2292: 	}
 2293: 	if (scalar(@bad_collaborators) > 0) {
 2294: 	    $result.='<div class="LC_warning">';
 2295: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2296: 	    $result .= '</div>';
 2297: 	}         
 2298: 	if (scalar(@bad_collaborators > $ncol)) {
 2299: 	    $result .= '<div class="LC_warning">';
 2300: 	    $result .= &mt('This student has submitted too many '.
 2301: 		'collaborators.  Maximum is [_1].',$ncol);
 2302: 	    $result .= '</div>';
 2303: 	}
 2304:     }
 2305:     return ($result,$fullname,\@col_fullnames);
 2306: }
 2307: 
 2308: #--- Retrieve the last submission for all the parts
 2309: sub get_last_submission {
 2310:     my ($returnhash)=@_;
 2311:     my (@string,$timestamp);
 2312:     if ($$returnhash{'version'}) {
 2313: 	my %lasthash=();
 2314: 	my ($version);
 2315: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2316: 	    foreach my $key (sort(split(/\:/,
 2317: 					$$returnhash{$version.':keys'}))) {
 2318: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2319: 		$timestamp = 
 2320: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2321: 	    }
 2322: 	}
 2323: 	foreach my $key (keys(%lasthash)) {
 2324: 	    next if ($key !~ /\.submission$/);
 2325: 
 2326: 	    my ($partid,$foo) = split(/submission$/,$key);
 2327: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2328: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2329: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2330: 	}
 2331:     }
 2332:     if (!@string) {
 2333: 	$string[0] =
 2334: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2335:     }
 2336:     return (\@string,\$timestamp);
 2337: }
 2338: 
 2339: #--- High light keywords, with style choosen by user.
 2340: sub keywords_highlight {
 2341:     my $string    = shift;
 2342:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2343:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2344:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2345:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2346:     foreach my $keyword (@keylist) {
 2347: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2348:     }
 2349:     return $string;
 2350: }
 2351: 
 2352: #--- Called from submission routine
 2353: sub processHandGrade {
 2354:     my ($request) = shift;
 2355:     my $symb   = &get_symb($request);
 2356:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2357:     my $button = $env{'form.gradeOpt'};
 2358:     my $ngrade = $env{'form.NCT'};
 2359:     my $ntstu  = $env{'form.NTSTU'};
 2360:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2361:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2362: 
 2363:     if ($button eq 'Save & Next') {
 2364: 	my $ctr = 0;
 2365: 	while ($ctr < $ngrade) {
 2366: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2367: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2368: 	    if ($errorflag eq 'no_score') {
 2369: 		$ctr++;
 2370: 		next;
 2371: 	    }
 2372: 	    if ($errorflag eq 'not_allowed') {
 2373: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2374: 		$ctr++;
 2375: 		next;
 2376: 	    }
 2377: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2378: 	    my ($subject,$message,$msgstatus) = ('','','');
 2379: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2380:             my ($feedurl,$showsymb) =
 2381: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2382: 	    my $messagetail;
 2383: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2384: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2385: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2386: 		$subject.=' ['.$restitle.']';
 2387: 		my (@msgnum) = split(/,/,$includemsg);
 2388: 		foreach (@msgnum) {
 2389: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2390: 		}
 2391: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2392: 		if ($env{'form.withgrades'.$ctr}) {
 2393: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2394: 		    $messagetail = " for <a href=\"".
 2395: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2396: 		}
 2397: 		$msgstatus = 
 2398:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2399: 						     $message.$messagetail,
 2400:                                                      undef,$feedurl,undef,
 2401:                                                      undef,undef,$showsymb,
 2402:                                                      $restitle);
 2403: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2404: 				$msgstatus);
 2405: 	    }
 2406: 	    if ($env{'form.collaborator'.$ctr}) {
 2407: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2408: 		foreach my $collabstr (@collabstrs) {
 2409: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2410: 		    foreach my $collaborator (@collaborators) {
 2411: 			my ($errorflag,$pts,$wgt) = 
 2412: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2413: 					   $env{'form.unamedom'.$ctr},$part);
 2414: 			if ($errorflag eq 'not_allowed') {
 2415: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2416: 			    next;
 2417: 			} elsif ($message ne '') {
 2418: 			    my ($baseurl,$showsymb) = 
 2419: 				&get_feedurl_and_symb($symb,$collaborator,
 2420: 						      $udom);
 2421: 			    if ($env{'form.withgrades'.$ctr}) {
 2422: 				$messagetail = " for <a href=\"".
 2423:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2424: 			    }
 2425: 			    $msgstatus = 
 2426: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2427: 			}
 2428: 		    }
 2429: 		}
 2430: 	    }
 2431: 	    $ctr++;
 2432: 	}
 2433:     }
 2434: 
 2435:     if ($env{'form.handgrade'} eq 'yes') {
 2436: 	# Keywords sorted in alphabatical order
 2437: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2438: 	my %keyhash = ();
 2439: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2440: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2441: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2442: 	$env{'form.keywords'} = join(' ',@keywords);
 2443: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2444: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2445: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2446: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2447: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2448: 
 2449: 	# message center - Order of message gets changed. Blank line is eliminated.
 2450: 	# New messages are saved in env for the next student.
 2451: 	# All messages are saved in nohist_handgrade.db
 2452: 	my ($ctr,$idx) = (1,1);
 2453: 	while ($ctr <= $env{'form.savemsgN'}) {
 2454: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2455: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2456: 		$idx++;
 2457: 	    }
 2458: 	    $ctr++;
 2459: 	}
 2460: 	$ctr = 0;
 2461: 	while ($ctr < $ngrade) {
 2462: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2463: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2464: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2465: 		$idx++;
 2466: 	    }
 2467: 	    $ctr++;
 2468: 	}
 2469: 	$env{'form.savemsgN'} = --$idx;
 2470: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2471: 	my $putresult = &Apache::lonnet::put
 2472: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2473:     }
 2474:     # Called by Save & Refresh from Highlight Attribute Window
 2475:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2476:     if ($env{'form.refresh'} eq 'on') {
 2477: 	my ($ctr,$total) = (0,0);
 2478: 	while ($ctr < $ngrade) {
 2479: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2480: 	    $ctr++;
 2481: 	}
 2482: 	$env{'form.NTSTU'}=$ngrade;
 2483: 	$ctr = 0;
 2484: 	while ($ctr < $total) {
 2485: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2486: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2487: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2488: 	    &submission($request,$ctr,$total-1);
 2489: 	    $ctr++;
 2490: 	}
 2491: 	return '';
 2492:     }
 2493: 
 2494: # Go directly to grade student - from submission or link from chart page
 2495:     if ($button eq 'Grade Student') {
 2496: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2497: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2498: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2499: 	$env{'form.fullname'} = $$fullname{$processUser};
 2500: 	&submission($request,0,0);
 2501: 	return '';
 2502:     }
 2503: 
 2504:     # Get the next/previous one or group of students
 2505:     my $firststu = $env{'form.unamedom0'};
 2506:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2507:     my $ctr = 2;
 2508:     while ($laststu eq '') {
 2509: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2510: 	$ctr++;
 2511: 	$laststu = $firststu if ($ctr > $ngrade);
 2512:     }
 2513: 
 2514:     my (@parsedlist,@nextlist);
 2515:     my ($nextflg) = 0;
 2516:     foreach my $item (sort 
 2517: 	     {
 2518: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2519: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2520: 		 }
 2521: 		 return $a cmp $b;
 2522: 	     } (keys(%$fullname))) {
 2523: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2524: 	    push(@parsedlist,$item);
 2525: 	}
 2526: 	$nextflg = 1 if ($item eq $laststu);
 2527: 	if ($button eq 'Previous') {
 2528: 	    last if ($item eq $firststu);
 2529: 	    push(@parsedlist,$item);
 2530: 	}
 2531:     }
 2532:     $ctr = 0;
 2533:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2534:     my ($partlist) = &response_type($symb);
 2535:     foreach my $student (@parsedlist) {
 2536: 	my $submitonly=$env{'form.submitonly'};
 2537: 	my ($uname,$udom) = split(/:/,$student);
 2538: 	
 2539: 	if ($submitonly eq 'queued') {
 2540: 	    my %queue_status = 
 2541: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2542: 							$udom,$uname);
 2543: 	    next if (!defined($queue_status{'gradingqueue'}));
 2544: 	}
 2545: 
 2546: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2547: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2548: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2549: 	    my $submitted = 0;
 2550: 	    my $ungraded = 0;
 2551: 	    my $incorrect = 0;
 2552: 	    foreach my $item (keys(%status)) {
 2553: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2554: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2555: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2556: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2557: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2558: 		    $submitted = 0;
 2559: 		}
 2560: 	    }
 2561: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2562: 				     $submitonly eq 'incorrect' ||
 2563: 				     $submitonly eq 'graded'));
 2564: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2565: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2566: 	}
 2567: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2568: 	last if ($ctr == $ntstu);
 2569: 	$ctr++;
 2570:     }
 2571: 
 2572:     $ctr = 0;
 2573:     my $total = scalar(@nextlist)-1;
 2574: 
 2575:     foreach (sort(@nextlist)) {
 2576: 	my ($uname,$udom,$submitter) = split(/:/);
 2577: 	$env{'form.student'}  = $uname;
 2578: 	$env{'form.userdom'}  = $udom;
 2579: 	$env{'form.fullname'} = $$fullname{$_};
 2580: 	&submission($request,$ctr,$total);
 2581: 	$ctr++;
 2582:     }
 2583:     if ($total < 0) {
 2584: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2585: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2586: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2587: 	$the_end.=&show_grading_menu_form($symb);
 2588: 	$request->print($the_end);
 2589:     }
 2590:     return '';
 2591: }
 2592: 
 2593: #---- Save the score and award for each student, if changed
 2594: sub saveHandGrade {
 2595:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2596:     my @version_parts;
 2597:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2598: 					   $env{'request.course.id'});
 2599:     if (!&canmodify($usec)) { return('not_allowed'); }
 2600:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2601:     my @parts_graded;
 2602:     my %newrecord  = ();
 2603:     my ($pts,$wgt) = ('','');
 2604:     my %aggregate = ();
 2605:     my $aggregateflag = 0;
 2606:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2607:     foreach my $new_part (@parts) {
 2608: 	#collaborator ($submi may vary for different parts
 2609: 	if ($submitter && $new_part ne $part) { next; }
 2610: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2611: 	if ($dropMenu eq 'excused') {
 2612: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2613: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2614: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2615: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2616: 		}
 2617: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2618: 	    }
 2619: 	} elsif ($dropMenu eq 'reset status'
 2620: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2621: 	    foreach my $key (keys(%record)) {
 2622: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2623: 	    }
 2624: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2625: 		"$env{'user.name'}:$env{'user.domain'}";
 2626:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2627: 
 2628:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2629: 					       [$new_part]);
 2630:             my $aggtries =$totaltries;
 2631:             if ($last_resets{$new_part}) {
 2632:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2633: 					   $new_part);
 2634:             }
 2635: 
 2636:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2637:             if ($aggtries > 0) {
 2638:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2639:                 $aggregateflag = 1;
 2640:             }
 2641: 	} elsif ($dropMenu eq '') {
 2642: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2643: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2644: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2645: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2646: 		next;
 2647: 	    }
 2648: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2649: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2650: 	    my $partial= $pts/$wgt;
 2651: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2652: 		#do not update score for part if not changed.
 2653:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2654: 		next;
 2655: 	    } else {
 2656: 	        push(@parts_graded,$new_part);
 2657: 	    }
 2658: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2659: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2660: 	    }
 2661: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2662: 	    if ($partial == 0) {
 2663: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2664: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2665: 		}
 2666: 	    } else {
 2667: 		if ($record{$reckey} ne 'correct_by_override') {
 2668: 		    $newrecord{$reckey} = 'correct_by_override';
 2669: 		}
 2670: 	    }	    
 2671: 	    if ($submitter && 
 2672: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2673: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2674: 	    }
 2675: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2676: 		"$env{'user.name'}:$env{'user.domain'}";
 2677: 	}
 2678: 	# unless problem has been graded, set flag to version the submitted files
 2679: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2680: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2681: 	        $dropMenu eq 'reset status')
 2682: 	   {
 2683: 	    push(@version_parts,$new_part);
 2684: 	}
 2685:     }
 2686:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2687:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2688: 
 2689:     if (%newrecord) {
 2690:         if (@version_parts) {
 2691:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2692:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2693: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2694: 	    foreach my $new_part (@version_parts) {
 2695: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2696: 				$new_part,\%newrecord);
 2697: 	    }
 2698:         }
 2699: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2700: 				$env{'request.course.id'},$domain,$stuname);
 2701: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2702: 				     $cdom,$cnum,$domain,$stuname);
 2703:     }
 2704:     if ($aggregateflag) {
 2705:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2706: 			      $cdom,$cnum);
 2707:     }
 2708:     return ('',$pts,$wgt);
 2709: }
 2710: 
 2711: sub check_and_remove_from_queue {
 2712:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2713:     my @ungraded_parts;
 2714:     foreach my $part (@{$parts}) {
 2715: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2716: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2717: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2718: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2719: 		) {
 2720: 	    push(@ungraded_parts, $part);
 2721: 	}
 2722:     }
 2723:     if ( !@ungraded_parts ) {
 2724: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2725: 					       $cnum,$domain,$stuname);
 2726:     }
 2727: }
 2728: 
 2729: sub handback_files {
 2730:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2731:     my $portfolio_root = '/userfiles/portfolio';
 2732:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2733: 
 2734:     my @part_response_id = &flatten_responseType($responseType);
 2735:     foreach my $part_response_id (@part_response_id) {
 2736:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2737: 	my $part_resp = join('_',@{ $part_response_id });
 2738:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2739:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2740:                 my $file_counter = 1;
 2741: 		my $file_msg;
 2742:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2743:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2744:                     my ($directory,$answer_file) = 
 2745:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2746:                     my ($answer_name,$answer_ver,$answer_ext) =
 2747: 		        &file_name_version_ext($answer_file);
 2748: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2749:                     my $getpropath = 1;
 2750: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2751: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2752:                     # fix file name
 2753:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2754:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2755:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2756:             	                                $save_file_name);
 2757:                     if ($result !~ m|^/uploaded/|) {
 2758:                         $request->print('<br /><span class="LC_error">'.
 2759:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2760:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2761:                                         '</span>');
 2762:                     } else {
 2763:                         # mark the file as read only
 2764:                         my @files = ($save_file_name);
 2765:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2766:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2767: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2768: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2769: 			}
 2770:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2771: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2772: 
 2773:                     }
 2774:                     $request->print("<br />".$fname." will be the uploaded file name");
 2775:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2776:                     $file_counter++;
 2777:                 }
 2778: 		my $subject = "File Handed Back by Instructor ";
 2779: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2780: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2781: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2782: 		$message .= " and can be found in your portfolio space.";
 2783: 		my ($feedurl,$showsymb) = 
 2784: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2785:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2786: 		my $msgstatus = 
 2787:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2788: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2789:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2790:             }
 2791:         }
 2792:     return;
 2793: }
 2794: 
 2795: sub get_feedurl_and_symb {
 2796:     my ($symb,$uname,$udom) = @_;
 2797:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2798:     $url = &Apache::lonnet::clutter($url);
 2799:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2800: 					$symb,$udom,$uname);
 2801:     if ($encrypturl =~ /^yes$/i) {
 2802: 	&Apache::lonenc::encrypted(\$url,1);
 2803: 	&Apache::lonenc::encrypted(\$symb,1);
 2804:     }
 2805:     return ($url,$symb);
 2806: }
 2807: 
 2808: sub get_submitted_files {
 2809:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2810:     my @files;
 2811:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2812:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2813:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2814:     	    push(@files,$file_url.$file);
 2815:         }
 2816:     }
 2817:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2818:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2819:     }
 2820:     return (\@files);
 2821: }
 2822: 
 2823: # ----------- Provides number of tries since last reset.
 2824: sub get_num_tries {
 2825:     my ($record,$last_reset,$part) = @_;
 2826:     my $timestamp = '';
 2827:     my $num_tries = 0;
 2828:     if ($$record{'version'}) {
 2829:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2830:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2831:                 $timestamp = $$record{$version.':timestamp'};
 2832:                 if ($timestamp > $last_reset) {
 2833:                     $num_tries ++;
 2834:                 } else {
 2835:                     last;
 2836:                 }
 2837:             }
 2838:         }
 2839:     }
 2840:     return $num_tries;
 2841: }
 2842: 
 2843: # ----------- Determine decrements required in aggregate totals 
 2844: sub decrement_aggs {
 2845:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2846:     my %decrement = (
 2847:                         attempts => 0,
 2848:                         users => 0,
 2849:                         correct => 0
 2850:                     );
 2851:     $decrement{'attempts'} = $aggtries;
 2852:     if ($solvedstatus =~ /^correct/) {
 2853:         $decrement{'correct'} = 1;
 2854:     }
 2855:     if ($aggtries == $totaltries) {
 2856:         $decrement{'users'} = 1;
 2857:     }
 2858:     foreach my $type (keys(%decrement)) {
 2859:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2860:     }
 2861:     return;
 2862: }
 2863: 
 2864: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2865: sub get_last_resets {
 2866:     my ($symb,$courseid,$partids) =@_;
 2867:     my %last_resets;
 2868:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2869:     my $cname = $env{'course.'.$courseid.'.num'};
 2870:     my @keys;
 2871:     foreach my $part (@{$partids}) {
 2872: 	push(@keys,"$symb\0$part\0resettime");
 2873:     }
 2874:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2875: 				     $cdom,$cname);
 2876:     foreach my $part (@{$partids}) {
 2877: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2878:     }
 2879:     return %last_resets;
 2880: }
 2881: 
 2882: # ----------- Handles creating versions for portfolio files as answers
 2883: sub version_portfiles {
 2884:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2885:     my $version_parts = join('|',@$v_flag);
 2886:     my @returned_keys;
 2887:     my $parts = join('|', @$parts_graded);
 2888:     my $portfolio_root = '/userfiles/portfolio';
 2889:     foreach my $key (keys(%$record)) {
 2890:         my $new_portfiles;
 2891:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2892:             my @versioned_portfiles;
 2893:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2894:             foreach my $file (@portfiles) {
 2895:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2896:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2897: 		my ($answer_name,$answer_ver,$answer_ext) =
 2898: 		    &file_name_version_ext($answer_file);
 2899:                 my $getpropath = 1;    
 2900:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2901:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2902:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2903:                 if ($new_answer ne 'problem getting file') {
 2904:                     push(@versioned_portfiles, $directory.$new_answer);
 2905:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2906:                         [$directory.$new_answer],
 2907:                         [$symb,$env{'request.course.id'},'graded']);
 2908:                 }
 2909:             }
 2910:             $$record{$key} = join(',',@versioned_portfiles);
 2911:             push(@returned_keys,$key);
 2912:         }
 2913:     } 
 2914:     return (@returned_keys);   
 2915: }
 2916: 
 2917: sub get_next_version {
 2918:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2919:     my $version;
 2920:     foreach my $row (@$dir_list) {
 2921:         my ($file) = split(/\&/,$row,2);
 2922:         my ($file_name,$file_version,$file_ext) =
 2923: 	    &file_name_version_ext($file);
 2924:         if (($file_name eq $answer_name) && 
 2925: 	    ($file_ext eq $answer_ext)) {
 2926:                 # gets here if filename and extension match, regardless of version
 2927:                 if ($file_version ne '') {
 2928:                 # a versioned file is found  so save it for later
 2929:                 if ($file_version > $version) {
 2930: 		    $version = $file_version;
 2931: 	        }
 2932:             }
 2933:         }
 2934:     } 
 2935:     $version ++;
 2936:     return($version);
 2937: }
 2938: 
 2939: sub version_selected_portfile {
 2940:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2941:     my ($answer_name,$answer_ver,$answer_ext) =
 2942:         &file_name_version_ext($file_name);
 2943:     my $new_answer;
 2944:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2945:     if($env{'form.copy'} eq '-1') {
 2946:         $new_answer = 'problem getting file';
 2947:     } else {
 2948:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2949:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2950:                             $stu_name,$domain,'copy',
 2951: 		        '/portfolio'.$directory.$new_answer);
 2952:     }    
 2953:     return ($new_answer);
 2954: }
 2955: 
 2956: sub file_name_version_ext {
 2957:     my ($file)=@_;
 2958:     my @file_parts = split(/\./, $file);
 2959:     my ($name,$version,$ext);
 2960:     if (@file_parts > 1) {
 2961: 	$ext=pop(@file_parts);
 2962: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 2963: 	    $version=pop(@file_parts);
 2964: 	}
 2965: 	$name=join('.',@file_parts);
 2966:     } else {
 2967: 	$name=join('.',@file_parts);
 2968:     }
 2969:     return($name,$version,$ext);
 2970: }
 2971: 
 2972: #--------------------------------------------------------------------------------------
 2973: #
 2974: #-------------------------- Next few routines handles grading by section or whole class
 2975: #
 2976: #--- Javascript to handle grading by section or whole class
 2977: sub viewgrades_js {
 2978:     my ($request) = shift;
 2979: 
 2980:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 2981:     $request->print(<<VIEWJAVASCRIPT);
 2982: <script type="text/javascript" language="javascript">
 2983:    function writePoint(partid,weight,point) {
 2984: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2985: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2986: 	if (point == "textval") {
 2987: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 2988: 	    if (isNaN(point) || parseFloat(point) < 0) {
 2989: 		alert("$alertmsg"+parseFloat(point));
 2990: 		var resetbox = false;
 2991: 		for (var i=0; i<radioButton.length; i++) {
 2992: 		    if (radioButton[i].checked) {
 2993: 			textbox.value = i;
 2994: 			resetbox = true;
 2995: 		    }
 2996: 		}
 2997: 		if (!resetbox) {
 2998: 		    textbox.value = "";
 2999: 		}
 3000: 		return;
 3001: 	    }
 3002: 	    if (parseFloat(point) > parseFloat(weight)) {
 3003: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3004: 				   ") greater than the weight for the part. Accept?");
 3005: 		if (resp == false) {
 3006: 		    textbox.value = "";
 3007: 		    return;
 3008: 		}
 3009: 	    }
 3010: 	    for (var i=0; i<radioButton.length; i++) {
 3011: 		radioButton[i].checked=false;
 3012: 		if (parseFloat(point) == i) {
 3013: 		    radioButton[i].checked=true;
 3014: 		}
 3015: 	    }
 3016: 
 3017: 	} else {
 3018: 	    textbox.value = parseFloat(point);
 3019: 	}
 3020: 	for (i=0;i<document.classgrade.total.value;i++) {
 3021: 	    var user = document.classgrade["ctr"+i].value;
 3022: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3023: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3024: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3025: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3026: 	    if (saveval != "correct") {
 3027: 		scorename.value = point;
 3028: 		if (selname[0].selected != true) {
 3029: 		    selname[0].selected = true;
 3030: 		}
 3031: 	    }
 3032: 	}
 3033: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3034:     }
 3035: 
 3036:     function writeRadText(partid,weight) {
 3037: 	var selval   = document.classgrade["SELVAL_"+partid];
 3038: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3039:         var override = document.classgrade["FORCE_"+partid].checked;
 3040: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3041: 	if (selval[1].selected || selval[2].selected) {
 3042: 	    for (var i=0; i<radioButton.length; i++) {
 3043: 		radioButton[i].checked=false;
 3044: 
 3045: 	    }
 3046: 	    textbox.value = "";
 3047: 
 3048: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3049: 		var user = document.classgrade["ctr"+i].value;
 3050: 		user = user.replace(new RegExp(':', 'g'),"_");
 3051: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3052: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3053: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3054: 		if ((saveval != "correct") || override) {
 3055: 		    scorename.value = "";
 3056: 		    if (selval[1].selected) {
 3057: 			selname[1].selected = true;
 3058: 		    } else {
 3059: 			selname[2].selected = true;
 3060: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3061: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3062: 		    }
 3063: 		}
 3064: 	    }
 3065: 	} else {
 3066: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3067: 		var user = document.classgrade["ctr"+i].value;
 3068: 		user = user.replace(new RegExp(':', 'g'),"_");
 3069: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3070: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3071: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3072: 		if ((saveval != "correct") || override) {
 3073: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3074: 		    selname[0].selected = true;
 3075: 		}
 3076: 	    }
 3077: 	}	    
 3078:     }
 3079: 
 3080:     function changeSelect(partid,user) {
 3081: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3082: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3083: 	var point  = textbox.value;
 3084: 	var weight = document.classgrade["weight_"+partid].value;
 3085: 
 3086: 	if (isNaN(point) || parseFloat(point) < 0) {
 3087: 	    alert("$alertmsg"+parseFloat(point));
 3088: 	    textbox.value = "";
 3089: 	    return;
 3090: 	}
 3091: 	if (parseFloat(point) > parseFloat(weight)) {
 3092: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3093: 			       ") greater than the weight of the part. Accept?");
 3094: 	    if (resp == false) {
 3095: 		textbox.value = "";
 3096: 		return;
 3097: 	    }
 3098: 	}
 3099: 	selval[0].selected = true;
 3100:     }
 3101: 
 3102:     function changeOneScore(partid,user) {
 3103: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3104: 	if (selval[1].selected || selval[2].selected) {
 3105: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3106: 	    if (selval[2].selected) {
 3107: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3108: 	    }
 3109:         }
 3110:     }
 3111: 
 3112:     function resetEntry(numpart) {
 3113: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3114: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3115: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3116: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3117: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3118: 	    for (var i=0; i<radioButton.length; i++) {
 3119: 		radioButton[i].checked=false;
 3120: 
 3121: 	    }
 3122: 	    textbox.value = "";
 3123: 	    selval[0].selected = true;
 3124: 
 3125: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3126: 		var user = document.classgrade["ctr"+i].value;
 3127: 		user = user.replace(new RegExp(':', 'g'),"_");
 3128: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3129: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3130: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3131: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3132: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3133: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3134: 		if (saveselval == "excused") {
 3135: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3136: 		} else {
 3137: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3138: 		}
 3139: 	    }
 3140: 	}
 3141:     }
 3142: 
 3143: </script>
 3144: VIEWJAVASCRIPT
 3145: }
 3146: 
 3147: #--- show scores for a section or whole class w/ option to change/update a score
 3148: sub viewgrades {
 3149:     my ($request) = shift;
 3150:     &viewgrades_js($request);
 3151: 
 3152:     my ($symb) = &get_symb($request);
 3153:     #need to make sure we have the correct data for later EXT calls, 
 3154:     #thus invalidate the cache
 3155:     &Apache::lonnet::devalidatecourseresdata(
 3156:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3157:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3158:     &Apache::lonnet::clear_EXT_cache_status();
 3159: 
 3160:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3161:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3162: 
 3163:     #view individual student submission form - called using Javascript viewOneStudent
 3164:     $result.=&jscriptNform($symb);
 3165: 
 3166:     #beginning of class grading form
 3167:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3168:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3169: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3170: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3171: 	&build_section_inputs().
 3172: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3173: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3174: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3175: 
 3176:     my $sectionClass;
 3177:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3178:     if ($env{'form.section'} eq 'all') {
 3179: 	$sectionClass=&mt('Class');
 3180:     } elsif ($env{'form.section'} eq 'none') {
 3181: 	$sectionClass=&mt('Students in no Section');
 3182:     } else {
 3183: 	$sectionClass=&mt('Students in Section(s) [_1]');
 3184:     }
 3185:     $result.=
 3186: 	'<h3>'.
 3187: 	&mt("Assign Common Grade to [_1]",$sectionClass,$section_display).'</h3>';
 3188:     $result.= &Apache::loncommon::start_data_table();
 3189:     #radio buttons/text box for assigning points for a section or class.
 3190:     #handles different parts of a problem
 3191:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3192:     my %weight = ();
 3193:     my $ctsparts = 0;
 3194:     my %seen = ();
 3195:     my @part_response_id = &flatten_responseType($responseType);
 3196:     foreach my $part_response_id (@part_response_id) {
 3197:     	my ($partid,$respid) = @{ $part_response_id };
 3198: 	my $part_resp = join('_',@{ $part_response_id });
 3199: 	next if $seen{$partid};
 3200: 	$seen{$partid}++;
 3201: 	my $handgrade=$$handgrade{$part_resp};
 3202: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3203: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3204: 
 3205: 	my $display_part=&get_display_part($partid,$symb);
 3206: 	my $radio.='<table border="0"><tr>';  
 3207: 	my $ctr = 0;
 3208: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3209: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3210: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3211: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3212: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3213: 	    $ctr++;
 3214: 	}
 3215: 	$radio.='</tr></table>';
 3216: 	my $line = '<input type="text" name="TEXTVAL_'.
 3217: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3218: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3219: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3220: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3221: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3222: 		$weight{$partid}.')"> '.
 3223: 	    '<option selected="selected"> </option>'.
 3224: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3225: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3226: 	    '</select></td>'.
 3227:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3228: 	$line.='<input type="hidden" name="partid_'.
 3229: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3230: 	$line.='<input type="hidden" name="weight_'.
 3231: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3232: 
 3233: 	$result.=
 3234: 	    &Apache::loncommon::start_data_table_row()."\n".
 3235: 	    '<td><b>'.&mt('Part').':</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points').':</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>'.
 3236: 	    &Apache::loncommon::end_data_table_row()."\n";
 3237: 	$ctsparts++;
 3238:     }
 3239:     $result.=&Apache::loncommon::end_data_table()."\n".
 3240: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3241:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3242: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3243: 
 3244:     #table listing all the students in a section/class
 3245:     #header of table
 3246:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in ').$sectionClass,
 3247: 			 $section_display.'</h3>';
 3248:     $result.= &Apache::loncommon::start_data_table().
 3249: 	&Apache::loncommon::start_data_table_header_row().
 3250: 	'<th>'.&mt('No.').'</th>'.
 3251: 	'<th>'.&nameUserString('header')."</th>\n";
 3252:     my (@parts) = sort(&getpartlist($symb));
 3253:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3254:     my @partids = ();
 3255:     foreach my $part (@parts) {
 3256: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3257:         my $narrowtext = &mt('Tries');
 3258: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3259: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3260: 	my ($partid) = &split_part_type($part);
 3261:         push(@partids,$partid);
 3262: 	my $display_part=&get_display_part($partid,$symb);
 3263: 	if ($display =~ /^Partial Credit Factor/) {
 3264: 	    $result.='<th>'.
 3265: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3266: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3267: 	    next;
 3268: 	    
 3269: 	} else {
 3270: 	    if ($display =~ /Problem Status/) {
 3271: 		my $grade_status_mt = &mt('Grade Status');
 3272: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3273: 	    }
 3274: 	    my $part_mt = &mt('Part:');
 3275: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3276: 	}
 3277: 
 3278: 	$result.='<th>'.$display.'</th>'."\n";
 3279:     }
 3280:     $result.=&Apache::loncommon::end_data_table_header_row();
 3281: 
 3282:     my %last_resets = 
 3283: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3284: 
 3285:     #get info for each student
 3286:     #list all the students - with points and grade status
 3287:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3288:     my $ctr = 0;
 3289:     foreach (sort 
 3290: 	     {
 3291: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3292: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3293: 		 }
 3294: 		 return $a cmp $b;
 3295: 	     } (keys(%$fullname))) {
 3296: 	$ctr++;
 3297: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3298: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3299:     }
 3300:     $result.=&Apache::loncommon::end_data_table();
 3301:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3302:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3303: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3304:     if (scalar(%$fullname) eq 0) {
 3305: 	my $colspan=3+scalar(@parts);
 3306: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3307:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3308: 	$result='<span class="LC_warning">'.
 3309: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3310: 	        $section_display, $stu_status).
 3311: 	    '</span>';
 3312:     }
 3313:     $result.=&show_grading_menu_form($symb);
 3314:     return $result;
 3315: }
 3316: 
 3317: #--- call by previous routine to display each student
 3318: sub viewstudentgrade {
 3319:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3320:     my ($uname,$udom) = split(/:/,$student);
 3321:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3322:     my %aggregates = (); 
 3323:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3324: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3325: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3326: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3327: 	'\');" target="_self">'.$fullname.'</a> '.
 3328: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3329:     $student=~s/:/_/; # colon doen't work in javascript for names
 3330:     foreach my $apart (@$parts) {
 3331: 	my ($part,$type) = &split_part_type($apart);
 3332: 	my $score=$record{"resource.$part.$type"};
 3333:         $result.='<td align="center">';
 3334:         my ($aggtries,$totaltries);
 3335:         unless (exists($aggregates{$part})) {
 3336: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3337: 
 3338: 	    $aggtries = $totaltries;
 3339:             if ($$last_resets{$part}) {  
 3340:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3341: 					   $part);
 3342:             }
 3343:             $result.='<input type="hidden" name="'.
 3344:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3345:             $result.='<input type="hidden" name="'.
 3346:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3347:             $aggregates{$part} = 1;
 3348:         }
 3349: 	if ($type eq 'awarded') {
 3350: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3351: 	    $result.='<input type="hidden" name="'.
 3352: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3353: 	    $result.='<input type="text" name="'.
 3354: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3355: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3356: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3357: 	} elsif ($type eq 'solved') {
 3358: 	    my ($status,$foo)=split(/_/,$score,2);
 3359: 	    $status = 'nothing' if ($status eq '');
 3360: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3361: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3362: 	    $result.='&nbsp;<select name="'.
 3363: 		'GD_'.$student.'_'.$part.'_solved" '.
 3364: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3365: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3366: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3367: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3368: 	    $result.="</select>&nbsp;</td>\n";
 3369: 	} else {
 3370: 	    $result.='<input type="hidden" name="'.
 3371: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3372: 		    "\n";
 3373: 	    $result.='<input type="text" name="'.
 3374: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3375: 		'value="'.$score.'" size="4" /></td>'."\n";
 3376: 	}
 3377:     }
 3378:     $result.=&Apache::loncommon::end_data_table_row();
 3379:     return $result;
 3380: }
 3381: 
 3382: #--- change scores for all the students in a section/class
 3383: #    record does not get update if unchanged
 3384: sub editgrades {
 3385:     my ($request) = @_;
 3386: 
 3387:     my $symb=&get_symb($request);
 3388:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3389:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3390:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3391:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3392: 
 3393:     my $result= &Apache::loncommon::start_data_table().
 3394: 	&Apache::loncommon::start_data_table_header_row().
 3395: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3396: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3397:     my %scoreptr = (
 3398: 		    'correct'  =>'correct_by_override',
 3399: 		    'incorrect'=>'incorrect_by_override',
 3400: 		    'excused'  =>'excused',
 3401: 		    'ungraded' =>'ungraded_attempted',
 3402: 		    'nothing'  => '',
 3403: 		    );
 3404:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3405: 
 3406:     my (@partid);
 3407:     my %weight = ();
 3408:     my %columns = ();
 3409:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3410: 
 3411:     my (@parts) = sort(&getpartlist($symb));
 3412:     my $header;
 3413:     while ($ctr < $env{'form.totalparts'}) {
 3414: 	my $partid = $env{'form.partid_'.$ctr};
 3415: 	push(@partid,$partid);
 3416: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3417: 	$ctr++;
 3418:     }
 3419:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3420:     foreach my $partid (@partid) {
 3421: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3422: 	    '<th align="center">'.&mt('New Score').'</th>';
 3423: 	$columns{$partid}=2;
 3424: 	foreach my $stores (@parts) {
 3425: 	    my ($part,$type) = &split_part_type($stores);
 3426: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3427: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3428: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3429: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3430:             my $narrowtext = &mt('Tries');
 3431: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3432: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3433: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3434: 	    $columns{$partid}+=2;
 3435: 	}
 3436:     }
 3437:     foreach my $partid (@partid) {
 3438: 	my $display_part=&get_display_part($partid,$symb);
 3439: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3440: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3441: 	    '</th>';
 3442: 
 3443:     }
 3444:     $result .= &Apache::loncommon::end_data_table_header_row().
 3445: 	&Apache::loncommon::start_data_table_header_row().
 3446: 	$header.
 3447: 	&Apache::loncommon::end_data_table_header_row();
 3448:     my @noupdate;
 3449:     my ($updateCtr,$noupdateCtr) = (1,1);
 3450:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3451: 	my $line;
 3452: 	my $user = $env{'form.ctr'.$i};
 3453: 	my ($uname,$udom)=split(/:/,$user);
 3454: 	my %newrecord;
 3455: 	my $updateflag = 0;
 3456: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3457: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3458: 	if (!&canmodify($usec)) {
 3459: 	    my $numcols=scalar(@partid)*4+2;
 3460: 	    push(@noupdate,
 3461: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3462: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3463: 	    next;
 3464: 	}
 3465:         my %aggregate = ();
 3466:         my $aggregateflag = 0;
 3467: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3468: 	foreach (@partid) {
 3469: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3470: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3471: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3472: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3473: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3474: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3475: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3476: 	    my $score;
 3477: 	    if ($partial eq '') {
 3478: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3479: 	    } elsif ($partial > 0) {
 3480: 		$score = 'correct_by_override';
 3481: 	    } elsif ($partial == 0) {
 3482: 		$score = 'incorrect_by_override';
 3483: 	    }
 3484: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3485: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3486: 
 3487: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3488: 		"$env{'user.name'}:$env{'user.domain'}";
 3489: 	    if ($dropMenu eq 'reset status' &&
 3490: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3491: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3492: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3493: 		$newrecord{'resource.'.$_.'.award'} = '';
 3494: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3495: 		$updateflag = 1;
 3496:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3497:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3498:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3499:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3500:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3501:                     $aggregateflag = 1;
 3502:                 }
 3503: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3504: 		$updateflag = 1;
 3505: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3506: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3507: 		$rec_update++;
 3508: 	    }
 3509: 
 3510: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3511: 		'<td align="center">'.$awarded.
 3512: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3513: 
 3514: 
 3515: 	    my $partid=$_;
 3516: 	    foreach my $stores (@parts) {
 3517: 		my ($part,$type) = &split_part_type($stores);
 3518: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3519: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3520: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3521: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3522: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3523: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3524: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3525: 		    $updateflag=1;
 3526: 		}
 3527: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3528: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3529: 	    }
 3530: 	}
 3531: 	$line.="\n";
 3532: 
 3533: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3534: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3535: 
 3536: 	if ($updateflag) {
 3537: 	    $count++;
 3538: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3539: 				    $udom,$uname);
 3540: 
 3541: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3542: 					      $cnum,$udom,$uname)) {
 3543: 		# need to figure out if should be in queue.
 3544: 		my %record =  
 3545: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3546: 					     $udom,$uname);
 3547: 		my $all_graded = 1;
 3548: 		my $none_graded = 1;
 3549: 		foreach my $part (@parts) {
 3550: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3551: 			$all_graded = 0;
 3552: 		    } else {
 3553: 			$none_graded = 0;
 3554: 		    }
 3555: 		}
 3556: 
 3557: 		if ($all_graded || $none_graded) {
 3558: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3559: 							   $symb,$cdom,$cnum,
 3560: 							   $udom,$uname);
 3561: 		}
 3562: 	    }
 3563: 
 3564: 	    $result.=&Apache::loncommon::start_data_table_row().
 3565: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3566: 		&Apache::loncommon::end_data_table_row();
 3567: 	    $updateCtr++;
 3568: 	} else {
 3569: 	    push(@noupdate,
 3570: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3571: 	    $noupdateCtr++;
 3572: 	}
 3573:         if ($aggregateflag) {
 3574:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3575: 				  $cdom,$cnum);
 3576:         }
 3577:     }
 3578:     if (@noupdate) {
 3579: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3580: 	my $numcols=scalar(@partid)*4+2;
 3581: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3582: 	    '<td align="center" colspan="'.$numcols.'">'.
 3583: 	    &mt('No Changes Occurred For the Students Below').
 3584: 	    '</td>'.
 3585: 	    &Apache::loncommon::end_data_table_row();
 3586: 	foreach my $line (@noupdate) {
 3587: 	    $result.=
 3588: 		&Apache::loncommon::start_data_table_row().
 3589: 		$line.
 3590: 		&Apache::loncommon::end_data_table_row();
 3591: 	}
 3592:     }
 3593:     $result .= &Apache::loncommon::end_data_table().
 3594: 	&show_grading_menu_form($symb);
 3595:     my $msg = '<p><b>'.
 3596: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3597: 	    $rec_update,$count).'</b><br />'.
 3598: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3599: 	'</b></p>';
 3600:     return $title.$msg.$result;
 3601: }
 3602: 
 3603: sub split_part_type {
 3604:     my ($partstr) = @_;
 3605:     my ($temp,@allparts)=split(/_/,$partstr);
 3606:     my $type=pop(@allparts);
 3607:     my $part=join('_',@allparts);
 3608:     return ($part,$type);
 3609: }
 3610: 
 3611: #------------- end of section for handling grading by section/class ---------
 3612: #
 3613: #----------------------------------------------------------------------------
 3614: 
 3615: 
 3616: #----------------------------------------------------------------------------
 3617: #
 3618: #-------------------------- Next few routines handles grading by csv upload
 3619: #
 3620: #--- Javascript to handle csv upload
 3621: sub csvupload_javascript_reverse_associate {
 3622:     my $error1=&mt('You need to specify the username or ID');
 3623:     my $error2=&mt('You need to specify at least one grading field');
 3624:   return(<<ENDPICK);
 3625:   function verify(vf) {
 3626:     var foundsomething=0;
 3627:     var founduname=0;
 3628:     var foundID=0;
 3629:     for (i=0;i<=vf.nfields.value;i++) {
 3630:       tw=eval('vf.f'+i+'.selectedIndex');
 3631:       if (i==0 && tw!=0) { foundID=1; }
 3632:       if (i==1 && tw!=0) { founduname=1; }
 3633:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3634:     }
 3635:     if (founduname==0 && foundID==0) {
 3636: 	alert('$error1');
 3637: 	return;
 3638:     }
 3639:     if (foundsomething==0) {
 3640: 	alert('$error2');
 3641: 	return;
 3642:     }
 3643:     vf.submit();
 3644:   }
 3645:   function flip(vf,tf) {
 3646:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3647:     var i;
 3648:     for (i=0;i<=vf.nfields.value;i++) {
 3649:       //can not pick the same destination field for both name and domain
 3650:       if (((i ==0)||(i ==1)) && 
 3651:           ((tf==0)||(tf==1)) && 
 3652:           (i!=tf) &&
 3653:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3654:         eval('vf.f'+i+'.selectedIndex=0;')
 3655:       }
 3656:     }
 3657:   }
 3658: ENDPICK
 3659: }
 3660: 
 3661: sub csvupload_javascript_forward_associate {
 3662:     my $error1=&mt('You need to specify the username or ID');
 3663:     my $error2=&mt('You need to specify at least one grading field');
 3664:   return(<<ENDPICK);
 3665:   function verify(vf) {
 3666:     var foundsomething=0;
 3667:     var founduname=0;
 3668:     var foundID=0;
 3669:     for (i=0;i<=vf.nfields.value;i++) {
 3670:       tw=eval('vf.f'+i+'.selectedIndex');
 3671:       if (tw==1) { foundID=1; }
 3672:       if (tw==2) { founduname=1; }
 3673:       if (tw>3) { foundsomething=1; }
 3674:     }
 3675:     if (founduname==0 && foundID==0) {
 3676: 	alert('$error1');
 3677: 	return;
 3678:     }
 3679:     if (foundsomething==0) {
 3680: 	alert('$error2');
 3681: 	return;
 3682:     }
 3683:     vf.submit();
 3684:   }
 3685:   function flip(vf,tf) {
 3686:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3687:     var i;
 3688:     //can not pick the same destination field twice
 3689:     for (i=0;i<=vf.nfields.value;i++) {
 3690:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3691:         eval('vf.f'+i+'.selectedIndex=0;')
 3692:       }
 3693:     }
 3694:   }
 3695: ENDPICK
 3696: }
 3697: 
 3698: sub csvuploadmap_header {
 3699:     my ($request,$symb,$datatoken,$distotal)= @_;
 3700:     my $javascript;
 3701:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3702: 	$javascript=&csvupload_javascript_reverse_associate();
 3703:     } else {
 3704: 	$javascript=&csvupload_javascript_forward_associate();
 3705:     }
 3706: 
 3707:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3708:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3709:     my $ignore=&mt('Ignore First Line');
 3710:     $symb = &Apache::lonenc::check_encrypt($symb);
 3711:     $request->print(<<ENDPICK);
 3712: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3713: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3714: $result
 3715: <hr />
 3716: <h3>Identify fields</h3>
 3717: Total number of records found in file: $distotal <hr />
 3718: Enter as many fields as you can. The system will inform you and bring you back
 3719: to this page if the data selected is insufficient to run your class.<hr />
 3720: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3721: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3722: <input type="hidden" name="associate"  value="" />
 3723: <input type="hidden" name="phase"      value="three" />
 3724: <input type="hidden" name="datatoken"  value="$datatoken" />
 3725: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3726: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3727: <input type="hidden" name="upfile_associate" 
 3728:                                        value="$env{'form.upfile_associate'}" />
 3729: <input type="hidden" name="symb"       value="$symb" />
 3730: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3731: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3732: <input type="hidden" name="command"    value="csvuploadoptions" />
 3733: <hr />
 3734: <script type="text/javascript" language="Javascript">
 3735: $javascript
 3736: </script>
 3737: ENDPICK
 3738:     return '';
 3739: 
 3740: }
 3741: 
 3742: sub csvupload_fields {
 3743:     my ($symb) = @_;
 3744:     my (@parts) = &getpartlist($symb);
 3745:     my @fields=(['ID','Student ID'],
 3746: 		['username','Student Username'],
 3747: 		['domain','Student Domain']);
 3748:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3749:     foreach my $part (sort(@parts)) {
 3750: 	my @datum;
 3751: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3752: 	my $name=$part;
 3753: 	if  (!$display) { $display = $name; }
 3754: 	@datum=($name,$display);
 3755: 	if ($name=~/^stores_(.*)_awarded/) {
 3756: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3757: 	}
 3758: 	push(@fields,\@datum);
 3759:     }
 3760:     return (@fields);
 3761: }
 3762: 
 3763: sub csvuploadmap_footer {
 3764:     my ($request,$i,$keyfields) =@_;
 3765:     $request->print(<<ENDPICK);
 3766: </table>
 3767: <input type="hidden" name="nfields" value="$i" />
 3768: <input type="hidden" name="keyfields" value="$keyfields" />
 3769: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3770: </form>
 3771: ENDPICK
 3772: }
 3773: 
 3774: sub checkforfile_js {
 3775:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3776:     my $result =<<CSVFORMJS;
 3777: <script type="text/javascript" language="javascript">
 3778:     function checkUpload(formname) {
 3779: 	if (formname.upfile.value == "") {
 3780: 	    alert("$alertmsg");
 3781: 	    return false;
 3782: 	}
 3783: 	formname.submit();
 3784:     }
 3785:     </script>
 3786: CSVFORMJS
 3787:     return $result;
 3788: }
 3789: 
 3790: sub upcsvScores_form {
 3791:     my ($request) = shift;
 3792:     my ($symb)=&get_symb($request);
 3793:     if (!$symb) {return '';}
 3794:     my $result=&checkforfile_js();
 3795:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3796:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3797:     $result.=$table;
 3798:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3799:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3800:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3801: 	'</b></td></tr>'."\n";
 3802:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3803:     my $upload=&mt("Upload Scores");
 3804:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3805:     my $ignore=&mt('Ignore First Line');
 3806:     $symb = &Apache::lonenc::check_encrypt($symb);
 3807:     $result.=<<ENDUPFORM;
 3808: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3809: <input type="hidden" name="symb" value="$symb" />
 3810: <input type="hidden" name="command" value="csvuploadmap" />
 3811: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3812: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3813: $upfile_select
 3814: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3815: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3816: </form>
 3817: ENDUPFORM
 3818:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3819:                            &mt("How do I create a CSV file from a spreadsheet"))
 3820:     .'</td></tr></table>'."\n";
 3821:     $result.='</td></tr></table><br /><br />'."\n";
 3822:     $result.=&show_grading_menu_form($symb);
 3823:     return $result;
 3824: }
 3825: 
 3826: 
 3827: sub csvuploadmap {
 3828:     my ($request)= @_;
 3829:     my ($symb)=&get_symb($request);
 3830:     if (!$symb) {return '';}
 3831: 
 3832:     my $datatoken;
 3833:     if (!$env{'form.datatoken'}) {
 3834: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3835:     } else {
 3836: 	$datatoken=$env{'form.datatoken'};
 3837: 	&Apache::loncommon::load_tmp_file($request);
 3838:     }
 3839:     my @records=&Apache::loncommon::upfile_record_sep();
 3840:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3841:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3842:     my ($i,$keyfields);
 3843:     if (@records) {
 3844: 	my @fields=&csvupload_fields($symb);
 3845: 
 3846: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3847: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3848: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3849: 							  \@fields);
 3850: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3851: 	    chop($keyfields);
 3852: 	} else {
 3853: 	    unshift(@fields,['none','']);
 3854: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3855: 							    \@fields);
 3856:             foreach my $rec (@records) {
 3857:                 my %temp = &Apache::loncommon::record_sep($rec);
 3858:                 if (%temp) {
 3859:                     $keyfields=join(',',sort(keys(%temp)));
 3860:                     last;
 3861:                 }
 3862:             }
 3863: 	}
 3864:     }
 3865:     &csvuploadmap_footer($request,$i,$keyfields);
 3866:     $request->print(&show_grading_menu_form($symb));
 3867: 
 3868:     return '';
 3869: }
 3870: 
 3871: sub csvuploadoptions {
 3872:     my ($request)= @_;
 3873:     my ($symb)=&get_symb($request);
 3874:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3875:     my $ignore=&mt('Ignore First Line');
 3876:     $request->print(<<ENDPICK);
 3877: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3878: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3879: <input type="hidden" name="command"    value="csvuploadassign" />
 3880: <!--
 3881: <p>
 3882: <label>
 3883:    <input type="checkbox" name="show_full_results" />
 3884:    Show a table of all changes
 3885: </label>
 3886: </p>
 3887: -->
 3888: <p>
 3889: <label>
 3890:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3891:    Overwrite any existing score
 3892: </label>
 3893: </p>
 3894: ENDPICK
 3895:     my %fields=&get_fields();
 3896:     if (!defined($fields{'domain'})) {
 3897: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3898: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3899:     }
 3900:     foreach my $key (sort(keys(%env))) {
 3901: 	if ($key !~ /^form\.(.*)$/) { next; }
 3902: 	my $cleankey=$1;
 3903: 	if ($cleankey eq 'command') { next; }
 3904: 	$request->print('<input type="hidden" name="'.$cleankey.
 3905: 			'"  value="'.$env{$key}.'" />'."\n");
 3906:     }
 3907:     # FIXME do a check for any duplicated user ids...
 3908:     # FIXME do a check for any invalid user ids?...
 3909:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3910: <hr /></form>'."\n");
 3911:     $request->print(&show_grading_menu_form($symb));
 3912:     return '';
 3913: }
 3914: 
 3915: sub get_fields {
 3916:     my %fields;
 3917:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3918:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3919: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3920: 	    if ($env{'form.f'.$i} ne 'none') {
 3921: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3922: 	    }
 3923: 	} else {
 3924: 	    if ($env{'form.f'.$i} ne 'none') {
 3925: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3926: 	    }
 3927: 	}
 3928:     }
 3929:     return %fields;
 3930: }
 3931: 
 3932: sub csvuploadassign {
 3933:     my ($request)= @_;
 3934:     my ($symb)=&get_symb($request);
 3935:     if (!$symb) {return '';}
 3936:     my $error_msg = '';
 3937:     &Apache::loncommon::load_tmp_file($request);
 3938:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3939:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3940:     my %fields=&get_fields();
 3941:     $request->print('<h3>Assigning Grades</h3>');
 3942:     my $courseid=$env{'request.course.id'};
 3943:     my ($classlist) = &getclasslist('all',0);
 3944:     my @notallowed;
 3945:     my @skipped;
 3946:     my $countdone=0;
 3947:     foreach my $grade (@gradedata) {
 3948: 	my %entries=&Apache::loncommon::record_sep($grade);
 3949: 	my $domain;
 3950: 	if ($entries{$fields{'domain'}}) {
 3951: 	    $domain=$entries{$fields{'domain'}};
 3952: 	} else {
 3953: 	    $domain=$env{'form.default_domain'};
 3954: 	}
 3955: 	$domain=~s/\s//g;
 3956: 	my $username=$entries{$fields{'username'}};
 3957: 	$username=~s/\s//g;
 3958: 	if (!$username) {
 3959: 	    my $id=$entries{$fields{'ID'}};
 3960: 	    $id=~s/\s//g;
 3961: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3962: 	    $username=$ids{$id};
 3963: 	}
 3964: 	if (!exists($$classlist{"$username:$domain"})) {
 3965: 	    my $id=$entries{$fields{'ID'}};
 3966: 	    $id=~s/\s//g;
 3967: 	    if ($id) {
 3968: 		push(@skipped,"$id:$domain");
 3969: 	    } else {
 3970: 		push(@skipped,"$username:$domain");
 3971: 	    }
 3972: 	    next;
 3973: 	}
 3974: 	my $usec=$classlist->{"$username:$domain"}[5];
 3975: 	if (!&canmodify($usec)) {
 3976: 	    push(@notallowed,"$username:$domain");
 3977: 	    next;
 3978: 	}
 3979: 	my %points;
 3980: 	my %grades;
 3981: 	foreach my $dest (keys(%fields)) {
 3982: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 3983: 		$dest eq 'domain') { next; }
 3984: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 3985: 	    if ($dest=~/stores_(.*)_points/) {
 3986: 		my $part=$1;
 3987: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 3988: 					      $symb,$domain,$username);
 3989:                 if ($wgt) {
 3990:                     $entries{$fields{$dest}}=~s/\s//g;
 3991:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 3992:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 3993:                                           : 'correct_by_override';
 3994:                     $grades{"resource.$part.awarded"}=$pcr;
 3995:                     $grades{"resource.$part.solved"}=$award;
 3996:                     $points{$part}=1;
 3997:                 } else {
 3998:                     $error_msg = "<br />" .
 3999:                         &mt("Some point values were assigned"
 4000:                             ." for problems with a weight "
 4001:                             ."of zero. These values were "
 4002:                             ."ignored.");
 4003:                 }
 4004: 	    } else {
 4005: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4006: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4007: 		my $store_key=$dest;
 4008: 		$store_key=~s/^stores/resource/;
 4009: 		$store_key=~s/_/\./g;
 4010: 		$grades{$store_key}=$entries{$fields{$dest}};
 4011: 	    }
 4012: 	}
 4013: 	if (! %grades) { 
 4014:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4015:         } else {
 4016: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4017: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4018: 					   $env{'request.course.id'},
 4019: 					   $domain,$username);
 4020: 	   if ($result eq 'ok') {
 4021: 	      $request->print('.');
 4022: 	   } else {
 4023: 	      $request->print("<p><span class=\"LC_error\">".
 4024:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4025:                                   "$username:$domain",$result)."</span></p>");
 4026: 	   }
 4027: 	   $request->rflush();
 4028: 	   $countdone++;
 4029:         }
 4030:     }
 4031:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4032:     if (@skipped) {
 4033: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4034: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4035:     }
 4036:     if (@notallowed) {
 4037: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4038: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4039:     }
 4040:     $request->print("<br />\n");
 4041:     $request->print(&show_grading_menu_form($symb));
 4042:     return $error_msg;
 4043: }
 4044: #------------- end of section for handling csv file upload ---------
 4045: #
 4046: #-------------------------------------------------------------------
 4047: #
 4048: #-------------- Next few routines handle grading by page/sequence
 4049: #
 4050: #--- Select a page/sequence and a student to grade
 4051: sub pickStudentPage {
 4052:     my ($request) = shift;
 4053: 
 4054:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4055:     $request->print(<<LISTJAVASCRIPT);
 4056: <script type="text/javascript" language="javascript">
 4057: 
 4058: function checkPickOne(formname) {
 4059:     if (radioSelection(formname.student) == null) {
 4060: 	alert("$alertmsg");
 4061: 	return;
 4062:     }
 4063:     ptr = pullDownSelection(formname.selectpage);
 4064:     formname.page.value = formname["page"+ptr].value;
 4065:     formname.title.value = formname["title"+ptr].value;
 4066:     formname.submit();
 4067: }
 4068: 
 4069: </script>
 4070: LISTJAVASCRIPT
 4071:     &commonJSfunctions($request);
 4072:     my ($symb) = &get_symb($request);
 4073:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4074:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4075:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4076: 
 4077:     my $result='<h3><span class="LC_info">&nbsp;'.
 4078: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4079: 
 4080:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4081:     my ($titles,$symbx) = &getSymbMap();
 4082:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4083: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4084: #    my $type=($curpage =~ /\.(page|sequence)/);
 4085:     my $select = '<select name="selectpage">'."\n";
 4086:     my $ctr=0;
 4087:     foreach (@$titles) {
 4088: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4089: 	$select.='<option value="'.$ctr.'" '.
 4090: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4091: 	    '>'.$showtitle.'</option>'."\n";
 4092: 	$ctr++;
 4093:     }
 4094:     $select.= '</select>';
 4095:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4096: 
 4097:     $ctr=0;
 4098:     foreach (@$titles) {
 4099: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4100: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4101: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4102: 	$ctr++;
 4103:     }
 4104:     $result.='<input type="hidden" name="page" />'."\n".
 4105: 	'<input type="hidden" name="title" />'."\n";
 4106: 
 4107:     my $options =
 4108: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4109: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4110:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4111: 
 4112:     $options =
 4113: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4114: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4115: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4116:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4117:     
 4118:     $result.=&build_section_inputs();
 4119:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4120:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4121: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4122: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4123: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4124: 
 4125:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4126: 
 4127:     $result.='&nbsp;<input type="button" '.
 4128: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4129: 
 4130:     $request->print($result);
 4131: 
 4132:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4133: 	&Apache::loncommon::start_data_table().
 4134: 	&Apache::loncommon::start_data_table_header_row().
 4135: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4136: 	'<th>'.&nameUserString('header').'</th>'.
 4137: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4138: 	'<th>'.&nameUserString('header').'</th>'.
 4139: 	&Apache::loncommon::end_data_table_header_row();
 4140:  
 4141:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4142:     my $ptr = 1;
 4143:     foreach my $student (sort 
 4144: 			 {
 4145: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4146: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4147: 			     }
 4148: 			     return $a cmp $b;
 4149: 			 } (keys(%$fullname))) {
 4150: 	my ($uname,$udom) = split(/:/,$student);
 4151: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4152:                                   : '</td>');
 4153: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4154: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4155: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4156: 	$studentTable.=
 4157: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4158:                          : '');
 4159: 	$ptr++;
 4160:     }
 4161:     if ($ptr%2 == 0) {
 4162: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4163: 	    &Apache::loncommon::end_data_table_row();
 4164:     }
 4165:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4166:     $studentTable.='<input type="button" '.
 4167: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4168: 
 4169:     $studentTable.=&show_grading_menu_form($symb);
 4170:     $request->print($studentTable);
 4171: 
 4172:     return '';
 4173: }
 4174: 
 4175: sub getSymbMap {
 4176:     my $navmap = Apache::lonnavmaps::navmap->new();
 4177: 
 4178:     my %symbx = ();
 4179:     my @titles = ();
 4180:     my $minder = 0;
 4181: 
 4182:     # Gather every sequence that has problems.
 4183:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4184: 					       1,0,1);
 4185:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4186: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4187: 	    my $title = $minder.'.'.
 4188: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4189: 	    push(@titles, $title); # minder in case two titles are identical
 4190: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4191: 	    $minder++;
 4192: 	}
 4193:     }
 4194:     return \@titles,\%symbx;
 4195: }
 4196: 
 4197: #
 4198: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4199: sub displayPage {
 4200:     my ($request) = shift;
 4201: 
 4202:     my ($symb) = &get_symb($request);
 4203:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4204:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4205:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4206:     my $pageTitle = $env{'form.page'};
 4207:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4208:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4209:     my $usec=$classlist->{$env{'form.student'}}[5];
 4210: 
 4211:     #need to make sure we have the correct data for later EXT calls, 
 4212:     #thus invalidate the cache
 4213:     &Apache::lonnet::devalidatecourseresdata(
 4214:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4215:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4216:     &Apache::lonnet::clear_EXT_cache_status();
 4217: 
 4218:     if (!&canview($usec)) {
 4219: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4220: 	$request->print(&show_grading_menu_form($symb));
 4221: 	return;
 4222:     }
 4223:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4224:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4225: 	'</h3>'."\n";
 4226:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4227:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4228: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4229:     } else {
 4230: 	delete($env{'form.CODE'});
 4231:     }
 4232:     &sub_page_js($request);
 4233:     $request->print($result);
 4234: 
 4235:     my $navmap = Apache::lonnavmaps::navmap->new();
 4236:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4237:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4238:     if (!$map) {
 4239: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4240: 	$request->print(&show_grading_menu_form($symb));
 4241: 	return; 
 4242:     }
 4243:     my $iterator = $navmap->getIterator($map->map_start(),
 4244: 					$map->map_finish());
 4245: 
 4246:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4247: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4248: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4249: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4250: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4251: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4252: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4253: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4254: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4255: 
 4256:     if (defined($env{'form.CODE'})) {
 4257: 	$studentTable.=
 4258: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4259:     }
 4260:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4261: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4262: 
 4263:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4264: 	&Apache::loncommon::start_data_table().
 4265: 	&Apache::loncommon::start_data_table_header_row().
 4266: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4267: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4268: 	&Apache::loncommon::end_data_table_header_row();
 4269: 
 4270:     &Apache::lonxml::clear_problem_counter();
 4271:     my ($depth,$question,$prob) = (1,1,1);
 4272:     $iterator->next(); # skip the first BEGIN_MAP
 4273:     my $curRes = $iterator->next(); # for "current resource"
 4274:     while ($depth > 0) {
 4275:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4276:         if($curRes == $iterator->END_MAP) { $depth--; }
 4277: 
 4278:         if (ref($curRes) && $curRes->is_problem()) {
 4279: 	    my $parts = $curRes->parts();
 4280:             my $title = $curRes->compTitle();
 4281: 	    my $symbx = $curRes->symb();
 4282: 	    $studentTable.=
 4283: 		&Apache::loncommon::start_data_table_row().
 4284: 		'<td align="center" valign="top" >'.$prob.
 4285: 		(scalar(@{$parts}) == 1 ? '' 
 4286: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4287: 							scalar(@{$parts}))
 4288: 		 ).
 4289: 		 '</td>';
 4290: 	    $studentTable.='<td valign="top">';
 4291: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4292: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4293: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4294: 					     undef,'both',\%form);
 4295: 	    } else {
 4296: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4297: 		$companswer =~ s|<form(.*?)>||g;
 4298: 		$companswer =~ s|</form>||g;
 4299: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4300: #		    $companswer =~ s/$1/ /ms;
 4301: #		    $request->print('match='.$1."<br />\n");
 4302: #		}
 4303: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4304: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4305: 	    }
 4306: 
 4307: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4308: 
 4309: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4310: 		if ($record{'version'} eq '') {
 4311: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4312: 		} else {
 4313: 		    my %responseType = ();
 4314: 		    foreach my $partid (@{$parts}) {
 4315: 			my @responseIds =$curRes->responseIds($partid);
 4316: 			my @responseType =$curRes->responseType($partid);
 4317: 			my %responseIds;
 4318: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4319: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4320: 			}
 4321: 			$responseType{$partid} = \%responseIds;
 4322: 		    }
 4323: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4324: 
 4325: 		}
 4326: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4327: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4328: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4329: 									$env{'request.course.id'},
 4330: 									'','.submission');
 4331:  
 4332: 	    }
 4333: 	    if (&canmodify($usec)) {
 4334: 		foreach my $partid (@{$parts}) {
 4335: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4336: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4337: 		    $question++;
 4338: 		}
 4339: 		$prob++;
 4340: 	    }
 4341: 	    $studentTable.='</td></tr>';
 4342: 
 4343: 	}
 4344:         $curRes = $iterator->next();
 4345:     }
 4346: 
 4347:     $studentTable.='</table>'."\n".
 4348: 	'<input type="button" value="'.&mt('Save').'" '.
 4349: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4350: 	'</form>'."\n";
 4351:     $studentTable.=&show_grading_menu_form($symb);
 4352:     $request->print($studentTable);
 4353: 
 4354:     return '';
 4355: }
 4356: 
 4357: sub displaySubByDates {
 4358:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4359:     my $isCODE=0;
 4360:     my $isTask = ($symb =~/\.task$/);
 4361:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4362:     my $studentTable=&Apache::loncommon::start_data_table().
 4363: 	&Apache::loncommon::start_data_table_header_row().
 4364: 	'<th>'.&mt('Date/Time').'</th>'.
 4365: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4366: 	'<th>'.&mt('Submission').'</th>'.
 4367: 	'<th>'.&mt('Status').'</th>'.
 4368: 	&Apache::loncommon::end_data_table_header_row();
 4369:     my ($version);
 4370:     my %mark;
 4371:     my %orders;
 4372:     $mark{'correct_by_student'} = $checkIcon;
 4373:     if (!exists($$record{'1:timestamp'})) {
 4374: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4375:     }
 4376: 
 4377:     my $interaction;
 4378:     my $no_increment = 1;
 4379:     for ($version=1;$version<=$$record{'version'};$version++) {
 4380: 	my $timestamp = 
 4381: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4382: 	if (exists($$record{$version.':resource.0.version'})) {
 4383: 	    $interaction = $$record{$version.':resource.0.version'};
 4384: 	}
 4385: 
 4386: 	my $where = ($isTask ? "$version:resource.$interaction"
 4387: 		             : "$version:resource");
 4388: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4389: 	    '<td>'.$timestamp.'</td>';
 4390: 	if ($isCODE) {
 4391: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4392: 	}
 4393: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4394: 	my @displaySub = ();
 4395: 	foreach my $partid (@{$parts}) {
 4396: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4397: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4398: 	    
 4399: 
 4400: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4401: 	    my $display_part=&get_display_part($partid,$symb);
 4402: 	    foreach my $matchKey (@matchKey) {
 4403: 		if (exists($$record{$version.':'.$matchKey}) &&
 4404: 		    $$record{$version.':'.$matchKey} ne '') {
 4405: 
 4406: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4407: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4408: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4409: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4410: 			$responseId.')</span>&nbsp;<b>';
 4411: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4412: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4413: 		    } else {
 4414: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4415: 					    $$record{"$where.$partid.tries"});
 4416: 		    }
 4417: 		    my $responseType=($isTask ? 'Task'
 4418:                                               : $responseType->{$partid}->{$responseId});
 4419: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4420: 		    if (!exists($orders{$partid}->{$responseId})) {
 4421: 			$orders{$partid}->{$responseId}=
 4422: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4423:                                        $no_increment);
 4424: 		    }
 4425: 		    $displaySub[0].='</b>&nbsp; '.
 4426: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4427: 		}
 4428: 	    }
 4429: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4430: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4431: 				    $$record{"$where.$partid.checkedin"},
 4432: 				    $$record{"$where.$partid.checkedin.slot"}).
 4433: 					'<br />';
 4434: 	    }
 4435: 	    if (exists $$record{"$where.$partid.award"}) {
 4436: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4437: 		    lc($$record{"$where.$partid.award"}).' '.
 4438: 		    $mark{$$record{"$where.$partid.solved"}}.
 4439: 		    '<br />';
 4440: 	    }
 4441: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4442: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4443: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4444: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4445: 		$displaySub[2].=
 4446: 		    $$record{"$version:resource.$partid.regrader"}.
 4447: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4448: 	    }
 4449: 	}
 4450: 	# needed because old essay regrader has not parts info
 4451: 	if (exists $$record{"$version:resource.regrader"}) {
 4452: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4453: 	}
 4454: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4455: 	if ($displaySub[2]) {
 4456: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4457: 	}
 4458: 	$studentTable.='&nbsp;</td>'.
 4459: 	    &Apache::loncommon::end_data_table_row();
 4460:     }
 4461:     $studentTable.=&Apache::loncommon::end_data_table();
 4462:     return $studentTable;
 4463: }
 4464: 
 4465: sub updateGradeByPage {
 4466:     my ($request) = shift;
 4467: 
 4468:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4469:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4470:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4471:     my $pageTitle = $env{'form.page'};
 4472:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4473:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4474:     my $usec=$classlist->{$env{'form.student'}}[5];
 4475:     if (!&canmodify($usec)) {
 4476: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4477: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4478: 	return;
 4479:     }
 4480:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4481:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4482: 	'</h3>'."\n";
 4483: 
 4484:     $request->print($result);
 4485: 
 4486:     my $navmap = Apache::lonnavmaps::navmap->new();
 4487:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4488:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4489:     if (!$map) {
 4490: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4491: 	my ($symb)=&get_symb($request);
 4492: 	$request->print(&show_grading_menu_form($symb));
 4493: 	return; 
 4494:     }
 4495:     my $iterator = $navmap->getIterator($map->map_start(),
 4496: 					$map->map_finish());
 4497: 
 4498:     my $studentTable=
 4499: 	&Apache::loncommon::start_data_table().
 4500: 	&Apache::loncommon::start_data_table_header_row().
 4501: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4502: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4503: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4504: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4505: 	&Apache::loncommon::end_data_table_header_row();
 4506: 
 4507:     $iterator->next(); # skip the first BEGIN_MAP
 4508:     my $curRes = $iterator->next(); # for "current resource"
 4509:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4510:     while ($depth > 0) {
 4511:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4512:         if($curRes == $iterator->END_MAP) { $depth--; }
 4513: 
 4514:         if (ref($curRes) && $curRes->is_problem()) {
 4515: 	    my $parts = $curRes->parts();
 4516:             my $title = $curRes->compTitle();
 4517: 	    my $symbx = $curRes->symb();
 4518: 	    $studentTable.=
 4519: 		&Apache::loncommon::start_data_table_row().
 4520: 		'<td align="center" valign="top" >'.$prob.
 4521: 		(scalar(@{$parts}) == 1 ? '' 
 4522:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4523: 		.')').'</td>';
 4524: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4525: 
 4526: 	    my %newrecord=();
 4527: 	    my @displayPts=();
 4528:             my %aggregate = ();
 4529:             my $aggregateflag = 0;
 4530: 	    foreach my $partid (@{$parts}) {
 4531: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4532: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4533: 
 4534: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4535: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4536: 		my $partial = $newpts/$wgt;
 4537: 		my $score;
 4538: 		if ($partial > 0) {
 4539: 		    $score = 'correct_by_override';
 4540: 		} elsif ($newpts ne '') { #empty is taken as 0
 4541: 		    $score = 'incorrect_by_override';
 4542: 		}
 4543: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4544: 		if ($dropMenu eq 'excused') {
 4545: 		    $partial = '';
 4546: 		    $score = 'excused';
 4547: 		} elsif ($dropMenu eq 'reset status'
 4548: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4549: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4550: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4551: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4552: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4553: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4554: 		    $changeflag++;
 4555: 		    $newpts = '';
 4556:                     
 4557:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4558:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4559:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4560:                     if ($aggtries > 0) {
 4561:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4562:                         $aggregateflag = 1;
 4563:                     }
 4564: 		}
 4565: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4566: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4567: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4568: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4569: 		    '&nbsp;<br />';
 4570: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4571: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4572: 		    '&nbsp;<br />';
 4573: 		$question++;
 4574: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4575: 
 4576: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4577: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4578: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4579: 		    if (scalar(keys(%newrecord)) > 0);
 4580: 
 4581: 		$changeflag++;
 4582: 	    }
 4583: 	    if (scalar(keys(%newrecord)) > 0) {
 4584: 		my %record = 
 4585: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4586: 					     $udom,$uname);
 4587: 
 4588: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4589: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4590: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4591: 		    $newrecord{'resource.CODE'} = '';
 4592: 		}
 4593: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4594: 					$udom,$uname);
 4595: 		%record = &Apache::lonnet::restore($symbx,
 4596: 						   $env{'request.course.id'},
 4597: 						   $udom,$uname);
 4598: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4599: 					     $cdom,$cnum,$udom,$uname);
 4600: 	    }
 4601: 	    
 4602:             if ($aggregateflag) {
 4603:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4604:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4605:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4606:             }
 4607: 
 4608: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4609: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4610: 		&Apache::loncommon::end_data_table_row();
 4611: 
 4612: 	    $prob++;
 4613: 	}
 4614:         $curRes = $iterator->next();
 4615:     }
 4616: 
 4617:     $studentTable.=&Apache::loncommon::end_data_table();
 4618:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4619:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4620: 		  &mt('The scores were changed for [quant,_1,problem].',
 4621: 		  $changeflag));
 4622:     $request->print($grademsg.$studentTable);
 4623: 
 4624:     return '';
 4625: }
 4626: 
 4627: #-------- end of section for handling grading by page/sequence ---------
 4628: #
 4629: #-------------------------------------------------------------------
 4630: 
 4631: #--------------------Scantron Grading-----------------------------------
 4632: #
 4633: #------ start of section for handling grading by page/sequence ---------
 4634: 
 4635: =pod
 4636: 
 4637: =head1 Bubble sheet grading routines
 4638: 
 4639:   For this documentation:
 4640: 
 4641:    'scanline' refers to the full line of characters
 4642:    from the file that we are parsing that represents one entire sheet
 4643: 
 4644:    'bubble line' refers to the data
 4645:    representing the line of bubbles that are on the physical bubble sheet
 4646: 
 4647: 
 4648: The overall process is that a scanned in bubble sheet data is uploaded
 4649: into a course. When a user wants to grade, they select a
 4650: sequence/folder of resources, a file of bubble sheet info, and pick
 4651: one of the predefined configurations for what each scanline looks
 4652: like.
 4653: 
 4654: Next each scanline is checked for any errors of either 'missing
 4655: bubbles' (it's an error because it may have been mis-scanned
 4656: because too light bubbling), 'double bubble' (each bubble line should
 4657: have no more that one letter picked), invalid or duplicated CODE,
 4658: invalid student ID
 4659: 
 4660: If the CODE option is used that determines the randomization of the
 4661: homework problems, either way the student ID is looked up into a
 4662: username:domain.
 4663: 
 4664: During the validation phase the instructor can choose to skip scanlines. 
 4665: 
 4666: After the validation phase, there are now 3 bubble sheet files
 4667: 
 4668:   scantron_original_filename (unmodified original file)
 4669:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4670:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4671: 
 4672: Also there is a separate hash nohist_scantrondata that contains extra
 4673: correction information that isn't representable in the bubble sheet
 4674: file (see &scantron_getfile() for more information)
 4675: 
 4676: After all scanlines are either valid, marked as valid or skipped, then
 4677: foreach line foreach problem in the picked sequence, an ssi request is
 4678: made that simulates a user submitting their selected letter(s) against
 4679: the homework problem.
 4680: 
 4681: =over 4
 4682: 
 4683: 
 4684: 
 4685: =item defaultFormData
 4686: 
 4687:   Returns html hidden inputs used to hold context/default values.
 4688: 
 4689:  Arguments:
 4690:   $symb - $symb of the current resource 
 4691: 
 4692: =cut
 4693: 
 4694: sub defaultFormData {
 4695:     my ($symb)=@_;
 4696:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4697:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4698:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4699: }
 4700: 
 4701: 
 4702: =pod 
 4703: 
 4704: =item getSequenceDropDown
 4705: 
 4706:    Return html dropdown of possible sequences to grade
 4707:  
 4708:  Arguments:
 4709:    $symb - $symb of the current resource 
 4710: 
 4711: =cut
 4712: 
 4713: sub getSequenceDropDown {
 4714:     my ($symb)=@_;
 4715:     my $result='<select name="selectpage">'."\n";
 4716:     my ($titles,$symbx) = &getSymbMap();
 4717:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4718:     my $ctr=0;
 4719:     foreach (@$titles) {
 4720: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4721: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4722: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4723: 	    '>'.$showtitle.'</option>'."\n";
 4724: 	$ctr++;
 4725:     }
 4726:     $result.= '</select>';
 4727:     return $result;
 4728: }
 4729: 
 4730: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4731:                                    # index is "symb.part_id"
 4732: 
 4733: my %first_bubble_line;             # First bubble line no. for each bubble.
 4734: 
 4735: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4736:                                    # matchresponse or rankresponse, where 
 4737:                                    # an individual response can have multiple 
 4738:                                    # lines
 4739: 
 4740: my %responsetype_per_response;     # responsetype for each response
 4741: 
 4742: # Save and restore the bubble lines array to the form env.
 4743: 
 4744: 
 4745: sub save_bubble_lines {
 4746:     foreach my $line (keys(%bubble_lines_per_response)) {
 4747: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4748: 	$env{"form.scantron.first_bubble_line.$line"} =
 4749: 	    $first_bubble_line{$line};
 4750:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4751:             $subdivided_bubble_lines{$line};
 4752:         $env{"form.scantron.responsetype.$line"} =
 4753:             $responsetype_per_response{$line};
 4754:     }
 4755: }
 4756: 
 4757: 
 4758: sub restore_bubble_lines {
 4759:     my $line = 0;
 4760:     %bubble_lines_per_response = ();
 4761:     while ($env{"form.scantron.bubblelines.$line"}) {
 4762: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4763: 	$bubble_lines_per_response{$line} = $value;
 4764: 	$first_bubble_line{$line}  =
 4765: 	    $env{"form.scantron.first_bubble_line.$line"};
 4766:         $subdivided_bubble_lines{$line} =
 4767:             $env{"form.scantron.sub_bubblelines.$line"};
 4768:         $responsetype_per_response{$line} =
 4769:             $env{"form.scantron.responsetype.$line"};
 4770: 	$line++;
 4771:     }
 4772: 
 4773: }
 4774: 
 4775: #  Given the parsed scanline, get the response for 
 4776: #  'answer' number n:
 4777: 
 4778: sub get_response_bubbles {
 4779:     my ($parsed_line, $response)  = @_;
 4780: 
 4781: 
 4782:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4783:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4784:     
 4785:     my $selected = "";
 4786: 
 4787:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4788: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4789: 	$bubble_line++;
 4790:     }
 4791:     return $selected;
 4792: }
 4793: 
 4794: =pod 
 4795: 
 4796: =item scantron_filenames
 4797: 
 4798:    Returns a list of the scantron files in the current course 
 4799: 
 4800: =cut
 4801: 
 4802: sub scantron_filenames {
 4803:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4804:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4805:     my $getpropath = 1;
 4806:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4807:                                        $getpropath);
 4808:     my @possiblenames;
 4809:     foreach my $filename (sort(@files)) {
 4810: 	($filename)=split(/&/,$filename);
 4811: 	if ($filename!~/^scantron_orig_/) { next ; }
 4812: 	$filename=~s/^scantron_orig_//;
 4813: 	push(@possiblenames,$filename);
 4814:     }
 4815:     return @possiblenames;
 4816: }
 4817: 
 4818: =pod 
 4819: 
 4820: =item scantron_uploads
 4821: 
 4822:    Returns  html drop-down list of scantron files in current course.
 4823: 
 4824:  Arguments:
 4825:    $file2grade - filename to set as selected in the dropdown
 4826: 
 4827: =cut
 4828: 
 4829: sub scantron_uploads {
 4830:     my ($file2grade) = @_;
 4831:     my $result=	'<select name="scantron_selectfile">';
 4832:     $result.="<option></option>";
 4833:     foreach my $filename (sort(&scantron_filenames())) {
 4834: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4835:     }
 4836:     $result.="</select>";
 4837:     return $result;
 4838: }
 4839: 
 4840: =pod 
 4841: 
 4842: =item scantron_scantab
 4843: 
 4844:   Returns html drop down of the scantron formats in the scantronformat.tab
 4845:   file.
 4846: 
 4847: =cut
 4848: 
 4849: sub scantron_scantab {
 4850:     my $result='<select name="scantron_format">'."\n";
 4851:     $result.='<option></option>'."\n";
 4852:     my @lines = &get_scantronformat_file();
 4853:     if (@lines > 0) {
 4854:         foreach my $line (@lines) {
 4855:             next if (($line =~ /^\#/) || ($line eq ''));
 4856: 	    my ($name,$descrip)=split(/:/,$line);
 4857: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4858:         }
 4859:     }
 4860:     $result.='</select>'."\n";
 4861:     return $result;
 4862: }
 4863: 
 4864: =pod
 4865: 
 4866: =item get_scantronformat_file
 4867: 
 4868:   Returns an array containing lines from the scantron format file for
 4869:   the domain of the course.
 4870: 
 4871:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4872:   lines are from this file.
 4873: 
 4874:   Otherwise, if a default.tab has been published in RES space by the 
 4875:   domainconfig user, lines are from this file.
 4876: 
 4877:   Otherwise, fall back to getting lines from the legacy file on the
 4878:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4879: 
 4880: =cut
 4881: 
 4882: sub get_scantronformat_file {
 4883:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4884:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4885:     my $gottab = 0;
 4886:     my @lines;
 4887:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4888:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4889:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4890:             if ($formatfile ne '-1') {
 4891:                 @lines = split("\n",$formatfile,-1);
 4892:                 $gottab = 1;
 4893:             }
 4894:         }
 4895:     }
 4896:     if (!$gottab) {
 4897:         my $confname = $cdom.'-domainconfig';
 4898:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4899:         my $formatfile =  &Apache::lonnet::getfile($default);
 4900:         if ($formatfile ne '-1') {
 4901:             @lines = split("\n",$formatfile,-1);
 4902:             $gottab = 1;
 4903:         }
 4904:     }
 4905:     if (!$gottab) {
 4906:         my @domains = &Apache::lonnet::current_machine_domains();
 4907:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4908:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4909:             @lines = <$fh>;
 4910:             close($fh);
 4911:         } else {
 4912:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4913:             @lines = <$fh>;
 4914:             close($fh);
 4915:         }
 4916:     }
 4917:     return @lines;
 4918: }
 4919: 
 4920: =pod 
 4921: 
 4922: =item scantron_CODElist
 4923: 
 4924:   Returns html drop down of the saved CODE lists from current course,
 4925:   generated from earlier printings.
 4926: 
 4927: =cut
 4928: 
 4929: sub scantron_CODElist {
 4930:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4931:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4932:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4933:     my $namechoice='<option></option>';
 4934:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4935: 	if ($name =~ /^error: 2 /) { next; }
 4936: 	if ($name =~ /^type\0/) { next; }
 4937: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4938:     }
 4939:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4940:     return $namechoice;
 4941: }
 4942: 
 4943: =pod 
 4944: 
 4945: =item scantron_CODEunique
 4946: 
 4947:   Returns the html for "Each CODE to be used once" radio.
 4948: 
 4949: =cut
 4950: 
 4951: sub scantron_CODEunique {
 4952:     my $result='<span class="LC_nobreak">
 4953:                  <label><input type="radio" name="scantron_CODEunique"
 4954:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4955:                 </span>
 4956:                 <span class="LC_nobreak">
 4957:                  <label><input type="radio" name="scantron_CODEunique"
 4958:                         value="no" />'.&mt('No').' </label>
 4959:                 </span>';
 4960:     return $result;
 4961: }
 4962: 
 4963: =pod 
 4964: 
 4965: =item scantron_selectphase
 4966: 
 4967:   Generates the initial screen to start the bubble sheet process.
 4968:   Allows for - starting a grading run.
 4969:              - downloading existing scan data (original, corrected
 4970:                                                 or skipped info)
 4971: 
 4972:              - uploading new scan data
 4973: 
 4974:  Arguments:
 4975:   $r          - The Apache request object
 4976:   $file2grade - name of the file that contain the scanned data to score
 4977: 
 4978: =cut
 4979: 
 4980: sub scantron_selectphase {
 4981:     my ($r,$file2grade) = @_;
 4982:     my ($symb)=&get_symb($r);
 4983:     if (!$symb) {return '';}
 4984:     my $sequence_selector=&getSequenceDropDown($symb);
 4985:     my $default_form_data=&defaultFormData($symb);
 4986:     my $grading_menu_button=&show_grading_menu_form($symb);
 4987:     my $file_selector=&scantron_uploads($file2grade);
 4988:     my $format_selector=&scantron_scantab();
 4989:     my $CODE_selector=&scantron_CODElist();
 4990:     my $CODE_unique=&scantron_CODEunique();
 4991:     my $result;
 4992: 
 4993:     $ssi_error = 0;
 4994: 
 4995:     # Chunk of form to prompt for a file to grade and how:
 4996: 
 4997:     $result.= '
 4998:     <br />
 4999:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5000:     <input type="hidden" name="command" value="scantron_warning" />
 5001:     '.$default_form_data.'
 5002:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5003:        '.&Apache::loncommon::start_data_table_header_row().'
 5004:             <th colspan="2">
 5005:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5006:             </th>
 5007:        '.&Apache::loncommon::end_data_table_header_row().'
 5008:        '.&Apache::loncommon::start_data_table_row().'
 5009:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5010:        '.&Apache::loncommon::end_data_table_row().'
 5011:        '.&Apache::loncommon::start_data_table_row().'
 5012:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5013:        '.&Apache::loncommon::end_data_table_row().'
 5014:        '.&Apache::loncommon::start_data_table_row().'
 5015:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5016:        '.&Apache::loncommon::end_data_table_row().'
 5017:        '.&Apache::loncommon::start_data_table_row().'
 5018:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5019:        '.&Apache::loncommon::end_data_table_row().'
 5020:        '.&Apache::loncommon::start_data_table_row().'
 5021:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5022:        '.&Apache::loncommon::end_data_table_row().'
 5023:        '.&Apache::loncommon::start_data_table_row().'
 5024: 	    <td> '.&mt('Options:').' </td>
 5025:             <td>
 5026: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5027:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5028:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5029: 	    </td>
 5030:        '.&Apache::loncommon::end_data_table_row().'
 5031:        '.&Apache::loncommon::start_data_table_row().'
 5032:             <td colspan="2">
 5033:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5034:             </td>
 5035:        '.&Apache::loncommon::end_data_table_row().'
 5036:     '.&Apache::loncommon::end_data_table().'
 5037:     </form>
 5038: ';
 5039:    
 5040:     $r->print($result);
 5041: 
 5042:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5043:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5044: 
 5045: 	# Chunk of form to prompt for a scantron file upload.
 5046: 
 5047:         $r->print('
 5048:     <br />
 5049:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5050:        '.&Apache::loncommon::start_data_table_header_row().'
 5051:             <th>
 5052:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5053:             </th>
 5054:        '.&Apache::loncommon::end_data_table_header_row().'
 5055:        '.&Apache::loncommon::start_data_table_row().'
 5056:             <td>
 5057: ');
 5058:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5059:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5060:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5061:     $r->print('
 5062:               <script type="text/javascript" language="javascript">
 5063:     function checkUpload(formname) {
 5064: 	if (formname.upfile.value == "") {
 5065: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5066: 	    return false;
 5067: 	}
 5068: 	formname.submit();
 5069:     }
 5070:               </script>
 5071: 
 5072:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5073:                 '.$default_form_data.'
 5074:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5075:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5076:                 <input name="command" value="scantronupload_save" type="hidden" />
 5077:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5078:                 <br />
 5079:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5080:               </form>
 5081: ');
 5082: 
 5083:         $r->print('
 5084:             </td>
 5085:        '.&Apache::loncommon::end_data_table_row().'
 5086:        '.&Apache::loncommon::end_data_table().'
 5087: ');
 5088:     }
 5089: 
 5090:     # Chunk of the form that prompts to view a scoring office file,
 5091:     # corrected file, skipped records in a file.
 5092: 
 5093:     $r->print('
 5094:    <br />
 5095:    <form action="/adm/grades" name="scantron_download">
 5096:      '.$default_form_data.'
 5097:      <input type="hidden" name="command" value="scantron_download" />
 5098:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5099:        '.&Apache::loncommon::start_data_table_header_row().'
 5100:               <th>
 5101:                 &nbsp;'.&mt('Download a scoring office file').'
 5102:               </th>
 5103:        '.&Apache::loncommon::end_data_table_header_row().'
 5104:        '.&Apache::loncommon::start_data_table_row().'
 5105:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5106:                 <br />
 5107:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5108:        '.&Apache::loncommon::end_data_table_row().'
 5109:      '.&Apache::loncommon::end_data_table().'
 5110:    </form>
 5111:    <br />
 5112: ');
 5113: 
 5114:     &Apache::lonpickcode::code_list($r,2);
 5115: 
 5116:     $r->print('<br /><form method="post" name="checkscantron">'.
 5117:              $default_form_data."\n".
 5118:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5119:              &Apache::loncommon::start_data_table_header_row()."\n".
 5120:              '<th colspan="2">
 5121:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5122:              '</th>'."\n".
 5123:               &Apache::loncommon::end_data_table_header_row()."\n".
 5124:               &Apache::loncommon::start_data_table_row()."\n".
 5125:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5126:               '<td> '.$sequence_selector.' </td>'.
 5127:               &Apache::loncommon::end_data_table_row()."\n".
 5128:               &Apache::loncommon::start_data_table_row()."\n".
 5129:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5130:               '<td> '.$file_selector.' </td>'."\n".
 5131:               &Apache::loncommon::end_data_table_row()."\n".
 5132:               &Apache::loncommon::start_data_table_row()."\n".
 5133:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5134:               '<td> '.$format_selector.' </td>'."\n".
 5135:               &Apache::loncommon::end_data_table_row()."\n".
 5136:               &Apache::loncommon::start_data_table_row()."\n".
 5137:               '<td colspan="2">'."\n".
 5138:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5139:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5140:               '</td>'."\n".
 5141:               &Apache::loncommon::end_data_table_row()."\n".
 5142:               &Apache::loncommon::end_data_table()."\n".
 5143:               '</form><br />');
 5144:     $r->print($grading_menu_button);
 5145:     return;
 5146: }
 5147: 
 5148: =pod
 5149: 
 5150: =item get_scantron_config
 5151: 
 5152:    Parse and return the scantron configuration line selected as a
 5153:    hash of configuration file fields.
 5154: 
 5155:  Arguments:
 5156:     which - the name of the configuration to parse from the file.
 5157: 
 5158: 
 5159:  Returns:
 5160:             If the named configuration is not in the file, an empty
 5161:             hash is returned.
 5162:     a hash with the fields
 5163:       name         - internal name for the this configuration setup
 5164:       description  - text to display to operator that describes this config
 5165:       CODElocation - if 0 or the string 'none'
 5166:                           - no CODE exists for this config
 5167:                      if -1 || the string 'letter'
 5168:                           - a CODE exists for this config and is
 5169:                             a string of letters
 5170:                      Unsupported value (but planned for future support)
 5171:                           if a positive integer
 5172:                                - The CODE exists as the first n items from
 5173:                                  the question section of the form
 5174:                           if the string 'number'
 5175:                                - The CODE exists for this config and is
 5176:                                  a string of numbers
 5177:       CODEstart   - (only matter if a CODE exists) column in the line where
 5178:                      the CODE starts
 5179:       CODElength  - length of the CODE
 5180:       IDstart     - column where the student ID number starts
 5181:       IDlength    - length of the student ID info
 5182:       Qstart      - column where the information from the bubbled
 5183:                     'questions' start
 5184:       Qlength     - number of columns comprising a single bubble line from
 5185:                     the sheet. (usually either 1 or 10)
 5186:       Qon         - either a single character representing the character used
 5187:                     to signal a bubble was chosen in the positional setup, or
 5188:                     the string 'letter' if the letter of the chosen bubble is
 5189:                     in the final, or 'number' if a number representing the
 5190:                     chosen bubble is in the file (1->A 0->J)
 5191:       Qoff        - the character used to represent that a bubble was
 5192:                     left blank
 5193:       PaperID     - if the scanning process generates a unique number for each
 5194:                     sheet scanned the column that this ID number starts in
 5195:       PaperIDlength - number of columns that comprise the unique ID number
 5196:                       for the sheet of paper
 5197:       FirstName   - column that the first name starts in
 5198:       FirstNameLength - number of columns that the first name spans
 5199:  
 5200:       LastName    - column that the last name starts in
 5201:       LastNameLength - number of columns that the last name spans
 5202: 
 5203: =cut
 5204: 
 5205: sub get_scantron_config {
 5206:     my ($which) = @_;
 5207:     my @lines = &get_scantronformat_file();
 5208:     my %config;
 5209:     #FIXME probably should move to XML it has already gotten a bit much now
 5210:     foreach my $line (@lines) {
 5211: 	my ($name,$descrip)=split(/:/,$line);
 5212: 	if ($name ne $which ) { next; }
 5213: 	chomp($line);
 5214: 	my @config=split(/:/,$line);
 5215: 	$config{'name'}=$config[0];
 5216: 	$config{'description'}=$config[1];
 5217: 	$config{'CODElocation'}=$config[2];
 5218: 	$config{'CODEstart'}=$config[3];
 5219: 	$config{'CODElength'}=$config[4];
 5220: 	$config{'IDstart'}=$config[5];
 5221: 	$config{'IDlength'}=$config[6];
 5222: 	$config{'Qstart'}=$config[7];
 5223:  	$config{'Qlength'}=$config[8];
 5224: 	$config{'Qoff'}=$config[9];
 5225: 	$config{'Qon'}=$config[10];
 5226: 	$config{'PaperID'}=$config[11];
 5227: 	$config{'PaperIDlength'}=$config[12];
 5228: 	$config{'FirstName'}=$config[13];
 5229: 	$config{'FirstNamelength'}=$config[14];
 5230: 	$config{'LastName'}=$config[15];
 5231: 	$config{'LastNamelength'}=$config[16];
 5232: 	last;
 5233:     }
 5234:     return %config;
 5235: }
 5236: 
 5237: =pod 
 5238: 
 5239: =item username_to_idmap
 5240: 
 5241:     creates a hash keyed by student id with values of the corresponding
 5242:     student username:domain.
 5243: 
 5244:   Arguments:
 5245: 
 5246:     $classlist - reference to the class list hash. This is a hash
 5247:                  keyed by student name:domain  whose elements are references
 5248:                  to arrays containing various chunks of information
 5249:                  about the student. (See loncoursedata for more info).
 5250: 
 5251:   Returns
 5252:     %idmap - the constructed hash
 5253: 
 5254: =cut
 5255: 
 5256: sub username_to_idmap {
 5257:     my ($classlist)= @_;
 5258:     my %idmap;
 5259:     foreach my $student (keys(%$classlist)) {
 5260: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5261: 	    $student;
 5262:     }
 5263:     return %idmap;
 5264: }
 5265: 
 5266: =pod
 5267: 
 5268: =item scantron_fixup_scanline
 5269: 
 5270:    Process a requested correction to a scanline.
 5271: 
 5272:   Arguments:
 5273:     $scantron_config   - hash from &get_scantron_config()
 5274:     $scan_data         - hash of correction information 
 5275:                           (see &scantron_getfile())
 5276:     $line              - existing scanline
 5277:     $whichline         - line number of the passed in scanline
 5278:     $field             - type of change to process 
 5279:                          (either 
 5280:                           'ID'     -> correct the student ID number
 5281:                           'CODE'   -> correct the CODE
 5282:                           'answer' -> fixup the submitted answers)
 5283:     
 5284:    $args               - hash of additional info,
 5285:                           - 'ID' 
 5286:                                'newid' -> studentID to use in replacement
 5287:                                           of existing one
 5288:                           - 'CODE' 
 5289:                                'CODE_ignore_dup' - set to true if duplicates
 5290:                                                    should be ignored.
 5291: 	                       'CODE' - is new code or 'use_unfound'
 5292:                                         if the existing unfound code should
 5293:                                         be used as is
 5294:                           - 'answer'
 5295:                                'response' - new answer or 'none' if blank
 5296:                                'question' - the bubble line to change
 5297:                                'questionnum' - the question identifier,
 5298:                                                may include subquestion. 
 5299: 
 5300:   Returns:
 5301:     $line - the modified scanline
 5302: 
 5303:   Side effects: 
 5304:     $scan_data - may be updated
 5305: 
 5306: =cut
 5307: 
 5308: 
 5309: sub scantron_fixup_scanline {
 5310:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5311:     if ($field eq 'ID') {
 5312: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5313: 	    return ($line,1,'New value too large');
 5314: 	}
 5315: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5316: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5317: 				     $args->{'newid'});
 5318: 	}
 5319: 	substr($line,$$scantron_config{'IDstart'}-1,
 5320: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5321: 	if ($args->{'newid'}=~/^\s*$/) {
 5322: 	    &scan_data($scan_data,"$whichline.user",
 5323: 		       $args->{'username'}.':'.$args->{'domain'});
 5324: 	}
 5325:     } elsif ($field eq 'CODE') {
 5326: 	if ($args->{'CODE_ignore_dup'}) {
 5327: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5328: 	}
 5329: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5330: 	if ($args->{'CODE'} ne 'use_unfound') {
 5331: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5332: 		return ($line,1,'New CODE value too large');
 5333: 	    }
 5334: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5335: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5336: 	    }
 5337: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5338: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5339: 	}
 5340:     } elsif ($field eq 'answer') {
 5341: 	my $length=$scantron_config->{'Qlength'};
 5342: 	my $off=$scantron_config->{'Qoff'};
 5343: 	my $on=$scantron_config->{'Qon'};
 5344: 	my $answer=${off}x$length;
 5345: 	if ($args->{'response'} eq 'none') {
 5346: 	    &scan_data($scan_data,
 5347: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5348: 	} else {
 5349: 	    if ($on eq 'letter') {
 5350: 		my @alphabet=('A'..'Z');
 5351: 		$answer=$alphabet[$args->{'response'}];
 5352: 	    } elsif ($on eq 'number') {
 5353: 		$answer=$args->{'response'}+1;
 5354: 		if ($answer == 10) { $answer = '0'; }
 5355: 	    } else {
 5356: 		substr($answer,$args->{'response'},1)=$on;
 5357: 	    }
 5358: 	    &scan_data($scan_data,
 5359: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5360: 	}
 5361: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5362: 	substr($line,$where-1,$length)=$answer;
 5363:     }
 5364:     return $line;
 5365: }
 5366: 
 5367: =pod
 5368: 
 5369: =item scan_data
 5370: 
 5371:     Edit or look up  an item in the scan_data hash.
 5372: 
 5373:   Arguments:
 5374:     $scan_data  - The hash (see scantron_getfile)
 5375:     $key        - shorthand of the key to edit (actual key is
 5376:                   scantronfilename_key).
 5377:     $data        - New value of the hash entry.
 5378:     $delete      - If true, the entry is removed from the hash.
 5379: 
 5380:   Returns:
 5381:     The new value of the hash table field (undefined if deleted).
 5382: 
 5383: =cut
 5384: 
 5385: 
 5386: sub scan_data {
 5387:     my ($scan_data,$key,$value,$delete)=@_;
 5388:     my $filename=$env{'form.scantron_selectfile'};
 5389:     if (defined($value)) {
 5390: 	$scan_data->{$filename.'_'.$key} = $value;
 5391:     }
 5392:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5393:     return $scan_data->{$filename.'_'.$key};
 5394: }
 5395: 
 5396: # ----- These first few routines are general use routines.----
 5397: 
 5398: # Return the number of occurences of a pattern in a string.
 5399: 
 5400: sub occurence_count {
 5401:     my ($string, $pattern) = @_;
 5402: 
 5403:     my @matches = ($string =~ /$pattern/g);
 5404: 
 5405:     return scalar(@matches);
 5406: }
 5407: 
 5408: 
 5409: # Take a string known to have digits and convert all the
 5410: # digits into letters in the range J,A..I.
 5411: 
 5412: sub digits_to_letters {
 5413:     my ($input) = @_;
 5414: 
 5415:     my @alphabet = ('J', 'A'..'I');
 5416: 
 5417:     my @input    = split(//, $input);
 5418:     my $output ='';
 5419:     for (my $i = 0; $i < scalar(@input); $i++) {
 5420: 	if ($input[$i] =~ /\d/) {
 5421: 	    $output .= $alphabet[$input[$i]];
 5422: 	} else {
 5423: 	    $output .= $input[$i];
 5424: 	}
 5425:     }
 5426:     return $output;
 5427: }
 5428: 
 5429: =pod 
 5430: 
 5431: =item scantron_parse_scanline
 5432: 
 5433:   Decodes a scanline from the selected scantron file
 5434: 
 5435:  Arguments:
 5436:     line             - The text of the scantron file line to process
 5437:     whichline        - Line number
 5438:     scantron_config  - Hash describing the format of the scantron lines.
 5439:     scan_data        - Hash of extra information about the scanline
 5440:                        (see scantron_getfile for more information)
 5441:     just_header      - True if should not process question answers but only
 5442:                        the stuff to the left of the answers.
 5443:  Returns:
 5444:    Hash containing the result of parsing the scanline
 5445: 
 5446:    Keys are all proceeded by the string 'scantron.'
 5447: 
 5448:        CODE    - the CODE in use for this scanline
 5449:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5450:                  by the operator
 5451:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5452:                             CODEs were selected, but the usage has been
 5453:                             forced by the operator
 5454:        ID  - student ID
 5455:        PaperID - if used, the ID number printed on the sheet when the 
 5456:                  paper was scanned
 5457:        FirstName - first name from the sheet
 5458:        LastName  - last name from the sheet
 5459: 
 5460:      if just_header was not true these key may also exist
 5461: 
 5462:        missingerror - a list of bubble ranges that are considered to be answers
 5463:                       to a single question that don't have any bubbles filled in.
 5464:                       Of the form questionnumber:firstbubblenumber:count.
 5465:        doubleerror  - a list of bubble ranges that are considered to be answers
 5466:                       to a single question that have more than one bubble filled in.
 5467:                       Of the form questionnumber::firstbubblenumber:count
 5468:    
 5469:                 In the above, count is the number of bubble responses in the
 5470:                 input line needed to represent the possible answers to the question.
 5471:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5472:                 per line would have count = 2.
 5473: 
 5474:        maxquest     - the number of the last bubble line that was parsed
 5475: 
 5476:        (<number> starts at 1)
 5477:        <number>.answer - zero or more letters representing the selected
 5478:                          letters from the scanline for the bubble line 
 5479:                          <number>.
 5480:                          if blank there was either no bubble or there where
 5481:                          multiple bubbles, (consult the keys missingerror and
 5482:                          doubleerror if this is an error condition)
 5483: 
 5484: =cut
 5485: 
 5486: sub scantron_parse_scanline {
 5487:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5488: 
 5489:     my %record;
 5490:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5491:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5492:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5493:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5494: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5495: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5496: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5497: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5498: 	    $record{'scantron.CODE'}=substr($data,
 5499: 					    $$scantron_config{'CODEstart'}-1,
 5500: 					    $$scantron_config{'CODElength'});
 5501: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5502: 		$record{'scantron.useCODE'}=1;
 5503: 	    }
 5504: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5505: 		$record{'scantron.CODE_ignore_dup'}=1;
 5506: 	    }
 5507: 	} else {
 5508: 	    #FIXME interpret first N questions
 5509: 	}
 5510:     }
 5511:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5512: 				  $$scantron_config{'IDlength'});
 5513:     $record{'scantron.PaperID'}=
 5514: 	substr($data,$$scantron_config{'PaperID'}-1,
 5515: 	       $$scantron_config{'PaperIDlength'});
 5516:     $record{'scantron.FirstName'}=
 5517: 	substr($data,$$scantron_config{'FirstName'}-1,
 5518: 	       $$scantron_config{'FirstNamelength'});
 5519:     $record{'scantron.LastName'}=
 5520: 	substr($data,$$scantron_config{'LastName'}-1,
 5521: 	       $$scantron_config{'LastNamelength'});
 5522:     if ($just_header) { return \%record; }
 5523: 
 5524:     my @alphabet=('A'..'Z');
 5525:     my $questnum=0;
 5526:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5527: 
 5528:     chomp($questions);		# Get rid of any trailing \n.
 5529:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5530:     while (length($questions)) {
 5531: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5532:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5533:                              || 1;
 5534:         $questnum++;
 5535:         my $quest_id = $questnum;
 5536:         my $currentquest = substr($questions,0,$answer_length);
 5537:         $questions       = substr($questions,$answer_length);
 5538:         if (length($currentquest) < $answer_length) { next; }
 5539: 
 5540:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5541:             my $subquestnum = 1;
 5542:             my $subquestions = $currentquest;
 5543:             my @subanswers_needed = 
 5544:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5545:             foreach my $subans (@subanswers_needed) {
 5546:                 my $subans_length =
 5547:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5548:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5549:                 $subquestions   = substr($subquestions,$subans_length);
 5550:                 $quest_id = "$questnum.$subquestnum";
 5551:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5552:                     ($$scantron_config{'Qon'} eq 'number')) {
 5553:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5554:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5555:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5556:                 } else {
 5557:                     $ansnum = &scantron_validator_positional($ansnum,
 5558:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5559:                 }
 5560:                 $subquestnum ++;
 5561:             }
 5562:         } else {
 5563:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5564:                 ($$scantron_config{'Qon'} eq 'number')) {
 5565:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5566:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5567:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5568:             } else {
 5569:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5570:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5571:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5572:             }
 5573:         }
 5574:     }
 5575:     $record{'scantron.maxquest'}=$questnum;
 5576:     return \%record;
 5577: }
 5578: 
 5579: sub scantron_validator_lettnum {
 5580:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5581:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5582: 
 5583:     # Qon 'letter' implies for each slot in currquest we have:
 5584:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5585:     #    about anything else (esp. a value of Qoff) for missing
 5586:     #    bubbles.
 5587:     #
 5588:     # Qon 'number' implies each slot gives a digit that indexes the
 5589:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5590:     #    and * or ? for double bubbles on a single line.
 5591:     #
 5592: 
 5593:     my $matchon;
 5594:     if ($$scantron_config{'Qon'} eq 'letter') {
 5595:         $matchon = '[A-Z]';
 5596:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5597:         $matchon = '\d';
 5598:     }
 5599:     my $occurrences = 0;
 5600:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5601:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5602:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5603:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5604:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5605:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5606:         my @singlelines = split('',$currquest);
 5607:         foreach my $entry (@singlelines) {
 5608:             $occurrences = &occurence_count($entry,$matchon);
 5609:             if ($occurrences > 1) {
 5610:                 last;
 5611:             }
 5612:         } 
 5613:     } else {
 5614:         $occurrences = &occurence_count($currquest,$matchon); 
 5615:     }
 5616:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5617:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5618:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5619:             my $bubble = substr($currquest,$ans,1);
 5620:             if ($bubble =~ /$matchon/ ) {
 5621:                 if ($$scantron_config{'Qon'} eq 'number') {
 5622:                     if ($bubble == 0) {
 5623:                         $bubble = 10; 
 5624:                     }
 5625:                     $record->{"scantron.$ansnum.answer"} = 
 5626:                         $alphabet->[$bubble-1];
 5627:                 } else {
 5628:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5629:                 }
 5630:             } else {
 5631:                 $record->{"scantron.$ansnum.answer"}='';
 5632:             }
 5633:             $ansnum++;
 5634:         }
 5635:     } elsif (!defined($currquest)
 5636:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5637:             || (&occurence_count($currquest,$matchon) == 0)) {
 5638:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5639:             $record->{"scantron.$ansnum.answer"}='';
 5640:             $ansnum++;
 5641:         }
 5642:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5643:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5644:         }
 5645:     } else {
 5646:         if ($$scantron_config{'Qon'} eq 'number') {
 5647:             $currquest = &digits_to_letters($currquest);            
 5648:         }
 5649:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5650:             my $bubble = substr($currquest,$ans,1);
 5651:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5652:             $ansnum++;
 5653:         }
 5654:     }
 5655:     return $ansnum;
 5656: }
 5657: 
 5658: sub scantron_validator_positional {
 5659:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5660:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5661: 
 5662:     # Otherwise there's a positional notation;
 5663:     # each bubble line requires Qlength items, and there are filled in
 5664:     # bubbles for each case where there 'Qon' characters.
 5665:     #
 5666: 
 5667:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5668: 
 5669:     # If the split only gives us one element.. the full length of the
 5670:     # answer string, no bubbles are filled in:
 5671: 
 5672:     if ($answers_needed eq '') {
 5673:         return;
 5674:     }
 5675: 
 5676:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5677:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5678:             $record->{"scantron.$ansnum.answer"}='';
 5679:             $ansnum++;
 5680:         }
 5681:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5682:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5683:         }
 5684:     } elsif (scalar(@array) == 2) {
 5685:         my $location = length($array[0]);
 5686:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5687:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5688:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5689:             if ($ans eq $line_num) {
 5690:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5691:             } else {
 5692:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5693:             }
 5694:             $ansnum++;
 5695:          }
 5696:     } else {
 5697:         #  If there's more than one instance of a bubble character
 5698:         #  That's a double bubble; with positional notation we can
 5699:         #  record all the bubbles filled in as well as the
 5700:         #  fact this response consists of multiple bubbles.
 5701:         #
 5702:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5703:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5704:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5705:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5706:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5707:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5708:             my $doubleerror = 0;
 5709:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5710:                    (!$doubleerror)) {
 5711:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5712:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5713:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5714:                if (length(@currarray) > 2) {
 5715:                    $doubleerror = 1;
 5716:                } 
 5717:             }
 5718:             if ($doubleerror) {
 5719:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5720:             }
 5721:         } else {
 5722:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5723:         }
 5724:         my $item = $ansnum;
 5725:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5726:             $record->{"scantron.$item.answer"} = '';
 5727:             $item ++;
 5728:         }
 5729: 
 5730:         my @ans=@array;
 5731:         my $i=0;
 5732:         my $increment = 0;
 5733:         while ($#ans) {
 5734:             $i+=length($ans[0]) + $increment;
 5735:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5736:             my $bubble = $i%$$scantron_config{'Qlength'};
 5737:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5738:             shift(@ans);
 5739:             $increment = 1;
 5740:         }
 5741:         $ansnum += $answers_needed;
 5742:     }
 5743:     return $ansnum;
 5744: }
 5745: 
 5746: =pod
 5747: 
 5748: =item scantron_add_delay
 5749: 
 5750:    Adds an error message that occurred during the grading phase to a
 5751:    queue of messages to be shown after grading pass is complete
 5752: 
 5753:  Arguments:
 5754:    $delayqueue  - arrary ref of hash ref of error messages
 5755:    $scanline    - the scanline that caused the error
 5756:    $errormesage - the error message
 5757:    $errorcode   - a numeric code for the error
 5758: 
 5759:  Side Effects:
 5760:    updates the $delayqueue to have a new hash ref of the error
 5761: 
 5762: =cut
 5763: 
 5764: sub scantron_add_delay {
 5765:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5766:     push(@$delayqueue,
 5767: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5768: 	  'ecode' => $errorcode }
 5769: 	 );
 5770: }
 5771: 
 5772: =pod
 5773: 
 5774: =item scantron_find_student
 5775: 
 5776:    Finds the username for the current scanline
 5777: 
 5778:   Arguments:
 5779:    $scantron_record - hash result from scantron_parse_scanline
 5780:    $scan_data       - hash of correction information 
 5781:                       (see &scantron_getfile() form more information)
 5782:    $idmap           - hash from &username_to_idmap()
 5783:    $line            - number of current scanline
 5784:  
 5785:   Returns:
 5786:    Either 'username:domain' or undef if unknown
 5787: 
 5788: =cut
 5789: 
 5790: sub scantron_find_student {
 5791:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5792:     my $scanID=$$scantron_record{'scantron.ID'};
 5793:     if ($scanID =~ /^\s*$/) {
 5794:  	return &scan_data($scan_data,"$line.user");
 5795:     }
 5796:     foreach my $id (keys(%$idmap)) {
 5797:  	if (lc($id) eq lc($scanID)) {
 5798:  	    return $$idmap{$id};
 5799:  	}
 5800:     }
 5801:     return undef;
 5802: }
 5803: 
 5804: =pod
 5805: 
 5806: =item scantron_filter
 5807: 
 5808:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5809:    hidden resources was selected
 5810: 
 5811: =cut
 5812: 
 5813: sub scantron_filter {
 5814:     my ($curres)=@_;
 5815: 
 5816:     if (ref($curres) && $curres->is_problem()) {
 5817: 	# if the user has asked to not have either hidden
 5818: 	# or 'randomout' controlled resources to be graded
 5819: 	# don't include them
 5820: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5821: 	    && $curres->randomout) {
 5822: 	    return 0;
 5823: 	}
 5824: 	return 1;
 5825:     }
 5826:     return 0;
 5827: }
 5828: 
 5829: =pod
 5830: 
 5831: =item scantron_process_corrections
 5832: 
 5833:    Gets correction information out of submitted form data and corrects
 5834:    the scanline
 5835: 
 5836: =cut
 5837: 
 5838: sub scantron_process_corrections {
 5839:     my ($r) = @_;
 5840:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5841:     my ($scanlines,$scan_data)=&scantron_getfile();
 5842:     my $classlist=&Apache::loncoursedata::get_classlist();
 5843:     my $which=$env{'form.scantron_line'};
 5844:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5845:     my ($skip,$err,$errmsg);
 5846:     if ($env{'form.scantron_skip_record'}) {
 5847: 	$skip=1;
 5848:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5849: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5850: 	    $env{'form.scantron_domain'};
 5851: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5852: 	($line,$err,$errmsg)=
 5853: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5854: 				     'ID',{'newid'=>$newid,
 5855: 				    'username'=>$env{'form.scantron_username'},
 5856: 				    'domain'=>$env{'form.scantron_domain'}});
 5857:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5858: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5859: 	my $newCODE;
 5860: 	my %args;
 5861: 	if      ($resolution eq 'use_unfound') {
 5862: 	    $newCODE='use_unfound';
 5863: 	} elsif ($resolution eq 'use_found') {
 5864: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5865: 	} elsif ($resolution eq 'use_typed') {
 5866: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5867: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5868: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5869: 	}
 5870: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5871: 	    $args{'CODE_ignore_dup'}=1;
 5872: 	}
 5873: 	$args{'CODE'}=$newCODE;
 5874: 	($line,$err,$errmsg)=
 5875: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5876: 				     'CODE',\%args);
 5877:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5878: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5879: 	    ($line,$err,$errmsg)=
 5880: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5881: 					 $which,'answer',
 5882: 					 { 'question'=>$question,
 5883: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5884:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5885: 	    if ($err) { last; }
 5886: 	}
 5887:     }
 5888:     if ($err) {
 5889: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5890:     } else {
 5891: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5892: 	&scantron_putfile($scanlines,$scan_data);
 5893:     }
 5894: }
 5895: 
 5896: =pod
 5897: 
 5898: =item reset_skipping_status
 5899: 
 5900:    Forgets the current set of remember skipped scanlines (and thus
 5901:    reverts back to considering all lines in the
 5902:    scantron_skipped_<filename> file)
 5903: 
 5904: =cut
 5905: 
 5906: sub reset_skipping_status {
 5907:     my ($scanlines,$scan_data)=&scantron_getfile();
 5908:     &scan_data($scan_data,'remember_skipping',undef,1);
 5909:     &scantron_putfile(undef,$scan_data);
 5910: }
 5911: 
 5912: =pod
 5913: 
 5914: =item start_skipping
 5915: 
 5916:    Marks a scanline to be skipped. 
 5917: 
 5918: =cut
 5919: 
 5920: sub start_skipping {
 5921:     my ($scan_data,$i)=@_;
 5922:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5923:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5924: 	$remembered{$i}=2;
 5925:     } else {
 5926: 	$remembered{$i}=1;
 5927:     }
 5928:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5929: }
 5930: 
 5931: =pod
 5932: 
 5933: =item should_be_skipped
 5934: 
 5935:    Checks whether a scanline should be skipped.
 5936: 
 5937: =cut
 5938: 
 5939: sub should_be_skipped {
 5940:     my ($scanlines,$scan_data,$i)=@_;
 5941:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5942: 	# not redoing old skips
 5943: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5944: 	return 0;
 5945:     }
 5946:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5947: 
 5948:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5949: 	return 0;
 5950:     }
 5951:     return 1;
 5952: }
 5953: 
 5954: =pod
 5955: 
 5956: =item remember_current_skipped
 5957: 
 5958:    Discovers what scanlines are in the scantron_skipped_<filename>
 5959:    file and remembers them into scan_data for later use.
 5960: 
 5961: =cut
 5962: 
 5963: sub remember_current_skipped {
 5964:     my ($scanlines,$scan_data)=&scantron_getfile();
 5965:     my %to_remember;
 5966:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 5967: 	if ($scanlines->{'skipped'}[$i]) {
 5968: 	    $to_remember{$i}=1;
 5969: 	}
 5970:     }
 5971: 
 5972:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 5973:     &scantron_putfile(undef,$scan_data);
 5974: }
 5975: 
 5976: =pod
 5977: 
 5978: =item check_for_error
 5979: 
 5980:     Checks if there was an error when attempting to remove a specific
 5981:     scantron_.. bubble sheet data file. Prints out an error if
 5982:     something went wrong.
 5983: 
 5984: =cut
 5985: 
 5986: sub check_for_error {
 5987:     my ($r,$result)=@_;
 5988:     if ($result ne 'ok' && $result ne 'not_found' ) {
 5989: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 5990:     }
 5991: }
 5992: 
 5993: =pod
 5994: 
 5995: =item scantron_warning_screen
 5996: 
 5997:    Interstitial screen to make sure the operator has selected the
 5998:    correct options before we start the validation phase.
 5999: 
 6000: =cut
 6001: 
 6002: sub scantron_warning_screen {
 6003:     my ($button_text)=@_;
 6004:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6005:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6006:     my $CODElist;
 6007:     if ($scantron_config{'CODElocation'} &&
 6008: 	$scantron_config{'CODEstart'} &&
 6009: 	$scantron_config{'CODElength'}) {
 6010: 	$CODElist=$env{'form.scantron_CODElist'};
 6011: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6012: 	$CODElist=
 6013: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6014: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6015:     }
 6016:     return ('
 6017: <p>
 6018: <span class="LC_warning">
 6019: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6020: </p>
 6021: <table>
 6022: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6023: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6024: '.$CODElist.'
 6025: </table>
 6026: <br />
 6027: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6028: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6029: 
 6030: <br />
 6031: ');
 6032: }
 6033: 
 6034: =pod
 6035: 
 6036: =item scantron_do_warning
 6037: 
 6038:    Check if the operator has picked something for all required
 6039:    fields. Error out if something is missing.
 6040: 
 6041: =cut
 6042: 
 6043: sub scantron_do_warning {
 6044:     my ($r)=@_;
 6045:     my ($symb)=&get_symb($r);
 6046:     if (!$symb) {return '';}
 6047:     my $default_form_data=&defaultFormData($symb);
 6048:     $r->print(&scantron_form_start().$default_form_data);
 6049:     if ( $env{'form.selectpage'} eq '' ||
 6050: 	 $env{'form.scantron_selectfile'} eq '' ||
 6051: 	 $env{'form.scantron_format'} eq '' ) {
 6052: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6053: 	if ( $env{'form.selectpage'} eq '') {
 6054: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6055: 	} 
 6056: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6057: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6058: 	} 
 6059: 	if ( $env{'form.scantron_format'} eq '') {
 6060: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6061: 	} 
 6062:     } else {
 6063: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6064: 	$r->print('
 6065: '.$warning.'
 6066: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6067: <input type="hidden" name="command" value="scantron_validate" />
 6068: ');
 6069:     }
 6070:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6071:     return '';
 6072: }
 6073: 
 6074: =pod
 6075: 
 6076: =item scantron_form_start
 6077: 
 6078:     html hidden input for remembering all selected grading options
 6079: 
 6080: =cut
 6081: 
 6082: sub scantron_form_start {
 6083:     my ($max_bubble)=@_;
 6084:     my $result= <<SCANTRONFORM;
 6085: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6086:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6087:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6088:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6089:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6090:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6091:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6092:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6093:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6094:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6095: SCANTRONFORM
 6096: 
 6097:   my $line = 0;
 6098:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6099:        my $chunk =
 6100: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6101:        $chunk .=
 6102: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6103:        $chunk .= 
 6104:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6105:        $chunk .=
 6106:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6107:        $result .= $chunk;
 6108:        $line++;
 6109:    }
 6110:     return $result;
 6111: }
 6112: 
 6113: =pod
 6114: 
 6115: =item scantron_validate_file
 6116: 
 6117:     Dispatch routine for doing validation of a bubble sheet data file.
 6118: 
 6119:     Also processes any necessary information resets that need to
 6120:     occur before validation begins (ignore previous corrections,
 6121:     restarting the skipped records processing)
 6122: 
 6123: =cut
 6124: 
 6125: sub scantron_validate_file {
 6126:     my ($r) = @_;
 6127:     my ($symb)=&get_symb($r);
 6128:     if (!$symb) {return '';}
 6129:     my $default_form_data=&defaultFormData($symb);
 6130:     
 6131:     # do the detection of only doing skipped records first befroe we delete
 6132:     # them when doing the corrections reset
 6133:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6134: 	&reset_skipping_status();
 6135:     }
 6136:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6137: 	&remember_current_skipped();
 6138: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6139:     }
 6140: 
 6141:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6142: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6143: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6144: 	&check_for_error($r,&scantron_remove_scan_data());
 6145: 	$env{'form.scantron_options_ignore'}='done';
 6146:     }
 6147: 
 6148:     if ($env{'form.scantron_corrections'}) {
 6149: 	&scantron_process_corrections($r);
 6150:     }
 6151:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6152:     #get the student pick code ready
 6153:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6154:     my $max_bubble=&scantron_get_maxbubble();
 6155:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6156:     $r->print($result);
 6157:     
 6158:     my @validate_phases=( 'sequence',
 6159: 			  'ID',
 6160: 			  'CODE',
 6161: 			  'doublebubble',
 6162: 			  'missingbubbles');
 6163:     if (!$env{'form.validatepass'}) {
 6164: 	$env{'form.validatepass'} = 0;
 6165:     }
 6166:     my $currentphase=$env{'form.validatepass'};
 6167: 
 6168: 
 6169:     my $stop=0;
 6170:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6171: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6172: 	$r->rflush();
 6173: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6174: 	{
 6175: 	    no strict 'refs';
 6176: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6177: 	}
 6178:     }
 6179:     if (!$stop) {
 6180: 	my $warning=&scantron_warning_screen('Start Grading');
 6181: 	$r->print(&mt('Validation process complete.').'<br />'.
 6182:                   $warning.
 6183:                   &mt('Perform verification for each student after storage of submissions?').
 6184:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6185:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6186:                   ('&nbsp;'x3).'<label>'.
 6187:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6188:                   '</label></span><br />'.
 6189:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6190:                   &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6191:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6192:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6193:     } else {
 6194: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6195: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6196:     }
 6197:     if ($stop) {
 6198: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6199: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6200: 	    $r->print(' '.&mt('this error').' <br />');
 6201: 
 6202: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6203: 	} else {
 6204:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6205: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6206:             } else {
 6207:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6208:             }
 6209: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6210: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6211: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6212: 	}
 6213:     }
 6214:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6215:     return '';
 6216: }
 6217: 
 6218: 
 6219: =pod
 6220: 
 6221: =item scantron_remove_file
 6222: 
 6223:    Removes the requested bubble sheet data file, makes sure that
 6224:    scantron_original_<filename> is never removed
 6225: 
 6226: 
 6227: =cut
 6228: 
 6229: sub scantron_remove_file {
 6230:     my ($which)=@_;
 6231:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6232:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6233:     my $file='scantron_';
 6234:     if ($which eq 'corrected' || $which eq 'skipped') {
 6235: 	$file.=$which.'_';
 6236:     } else {
 6237: 	return 'refused';
 6238:     }
 6239:     $file.=$env{'form.scantron_selectfile'};
 6240:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6241: }
 6242: 
 6243: 
 6244: =pod
 6245: 
 6246: =item scantron_remove_scan_data
 6247: 
 6248:    Removes all scan_data correction for the requested bubble sheet
 6249:    data file.  (In the case that both the are doing skipped records we need
 6250:    to remember the old skipped lines for the time being so that element
 6251:    persists for a while.)
 6252: 
 6253: =cut
 6254: 
 6255: sub scantron_remove_scan_data {
 6256:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6257:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6258:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6259:     my @todelete;
 6260:     my $filename=$env{'form.scantron_selectfile'};
 6261:     foreach my $key (@keys) {
 6262: 	if ($key=~/^\Q$filename\E_/) {
 6263: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6264: 		$key=~/remember_skipping/) {
 6265: 		next;
 6266: 	    }
 6267: 	    push(@todelete,$key);
 6268: 	}
 6269:     }
 6270:     my $result;
 6271:     if (@todelete) {
 6272: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6273: 				       \@todelete,$cdom,$cname);
 6274:     } else {
 6275: 	$result = 'ok';
 6276:     }
 6277:     return $result;
 6278: }
 6279: 
 6280: 
 6281: =pod
 6282: 
 6283: =item scantron_getfile
 6284: 
 6285:     Fetches the requested bubble sheet data file (all 3 versions), and
 6286:     the scan_data hash
 6287:   
 6288:   Arguments:
 6289:     None
 6290: 
 6291:   Returns:
 6292:     2 hash references
 6293: 
 6294:      - first one has 
 6295:          orig      -
 6296:          corrected -
 6297:          skipped   -  each of which points to an array ref of the specified
 6298:                       file broken up into individual lines
 6299:          count     - number of scanlines
 6300:  
 6301:      - second is the scan_data hash possible keys are
 6302:        ($number refers to scanline numbered $number and thus the key affects
 6303:         only that scanline
 6304:         $bubline refers to the specific bubble line element and the aspects
 6305:         refers to that specific bubble line element)
 6306: 
 6307:        $number.user - username:domain to use
 6308:        $number.CODE_ignore_dup 
 6309:                     - ignore the duplicate CODE error 
 6310:        $number.useCODE
 6311:                     - use the CODE in the scanline as is
 6312:        $number.no_bubble.$bubline
 6313:                     - it is valid that there is no bubbled in bubble
 6314:                       at $number $bubline
 6315:        remember_skipping
 6316:                     - a frozen hash containing keys of $number and values
 6317:                       of either 
 6318:                         1 - we are on a 'do skipped records pass' and plan
 6319:                             on processing this line
 6320:                         2 - we are on a 'do skipped records pass' and this
 6321:                             scanline has been marked to skip yet again
 6322: 
 6323: =cut
 6324: 
 6325: sub scantron_getfile {
 6326:     #FIXME really would prefer a scantron directory
 6327:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6328:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6329:     my $lines;
 6330:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6331: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6332:     my %scanlines;
 6333:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6334:     my $temp=$scanlines{'orig'};
 6335:     $scanlines{'count'}=$#$temp;
 6336: 
 6337:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6338: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6339:     if ($lines eq '-1') {
 6340: 	$scanlines{'corrected'}=[];
 6341:     } else {
 6342: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6343:     }
 6344:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6345: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6346:     if ($lines eq '-1') {
 6347: 	$scanlines{'skipped'}=[];
 6348:     } else {
 6349: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6350:     }
 6351:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6352:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6353:     my %scan_data = @tmp;
 6354:     return (\%scanlines,\%scan_data);
 6355: }
 6356: 
 6357: =pod
 6358: 
 6359: =item lonnet_putfile
 6360: 
 6361:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6362: 
 6363:  Arguments:
 6364:    $contents - data to store
 6365:    $filename - filename to store $contents into
 6366: 
 6367:  Returns:
 6368:    result value from &Apache::lonnet::finishuserfileupload
 6369: 
 6370: =cut
 6371: 
 6372: sub lonnet_putfile {
 6373:     my ($contents,$filename)=@_;
 6374:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6375:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6376:     $env{'form.sillywaytopassafilearound'}=$contents;
 6377:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6378: 
 6379: }
 6380: 
 6381: =pod
 6382: 
 6383: =item scantron_putfile
 6384: 
 6385:     Stores the current version of the bubble sheet data files, and the
 6386:     scan_data hash. (Does not modify the original version only the
 6387:     corrected and skipped versions.
 6388: 
 6389:  Arguments:
 6390:     $scanlines - hash ref that looks like the first return value from
 6391:                  &scantron_getfile()
 6392:     $scan_data - hash ref that looks like the second return value from
 6393:                  &scantron_getfile()
 6394: 
 6395: =cut
 6396: 
 6397: sub scantron_putfile {
 6398:     my ($scanlines,$scan_data) = @_;
 6399:     #FIXME really would prefer a scantron directory
 6400:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6401:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6402:     if ($scanlines) {
 6403: 	my $prefix='scantron_';
 6404: # no need to update orig, shouldn't change
 6405: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6406: #		    $env{'form.scantron_selectfile'});
 6407: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6408: 			$prefix.'corrected_'.
 6409: 			$env{'form.scantron_selectfile'});
 6410: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6411: 			$prefix.'skipped_'.
 6412: 			$env{'form.scantron_selectfile'});
 6413:     }
 6414:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6415: }
 6416: 
 6417: =pod
 6418: 
 6419: =item scantron_get_line
 6420: 
 6421:    Returns the correct version of the scanline
 6422: 
 6423:  Arguments:
 6424:     $scanlines - hash ref that looks like the first return value from
 6425:                  &scantron_getfile()
 6426:     $scan_data - hash ref that looks like the second return value from
 6427:                  &scantron_getfile()
 6428:     $i         - number of the requested line (starts at 0)
 6429: 
 6430:  Returns:
 6431:    A scanline, (either the original or the corrected one if it
 6432:    exists), or undef if the requested scanline should be
 6433:    skipped. (Either because it's an skipped scanline, or it's an
 6434:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6435:    pass.
 6436: 
 6437: =cut
 6438: 
 6439: sub scantron_get_line {
 6440:     my ($scanlines,$scan_data,$i)=@_;
 6441:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6442:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6443:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6444:     return $scanlines->{'orig'}[$i]; 
 6445: }
 6446: 
 6447: =pod
 6448: 
 6449: =item scantron_todo_count
 6450: 
 6451:     Counts the number of scanlines that need processing.
 6452: 
 6453:  Arguments:
 6454:     $scanlines - hash ref that looks like the first return value from
 6455:                  &scantron_getfile()
 6456:     $scan_data - hash ref that looks like the second return value from
 6457:                  &scantron_getfile()
 6458: 
 6459:  Returns:
 6460:     $count - number of scanlines to process
 6461: 
 6462: =cut
 6463: 
 6464: sub get_todo_count {
 6465:     my ($scanlines,$scan_data)=@_;
 6466:     my $count=0;
 6467:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6468: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6469: 	if ($line=~/^[\s\cz]*$/) { next; }
 6470: 	$count++;
 6471:     }
 6472:     return $count;
 6473: }
 6474: 
 6475: =pod
 6476: 
 6477: =item scantron_put_line
 6478: 
 6479:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6480:     data file.
 6481: 
 6482:  Arguments:
 6483:     $scanlines - hash ref that looks like the first return value from
 6484:                  &scantron_getfile()
 6485:     $scan_data - hash ref that looks like the second return value from
 6486:                  &scantron_getfile()
 6487:     $i         - line number to update
 6488:     $newline   - contents of the updated scanline
 6489:     $skip      - if true make the line for skipping and update the
 6490:                  'skipped' file
 6491: 
 6492: =cut
 6493: 
 6494: sub scantron_put_line {
 6495:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6496:     if ($skip) {
 6497: 	$scanlines->{'skipped'}[$i]=$newline;
 6498: 	&start_skipping($scan_data,$i);
 6499: 	return;
 6500:     }
 6501:     $scanlines->{'corrected'}[$i]=$newline;
 6502: }
 6503: 
 6504: =pod
 6505: 
 6506: =item scantron_clear_skip
 6507: 
 6508:    Remove a line from the 'skipped' file
 6509: 
 6510:  Arguments:
 6511:     $scanlines - hash ref that looks like the first return value from
 6512:                  &scantron_getfile()
 6513:     $scan_data - hash ref that looks like the second return value from
 6514:                  &scantron_getfile()
 6515:     $i         - line number to update
 6516: 
 6517: =cut
 6518: 
 6519: sub scantron_clear_skip {
 6520:     my ($scanlines,$scan_data,$i)=@_;
 6521:     if (exists($scanlines->{'skipped'}[$i])) {
 6522: 	undef($scanlines->{'skipped'}[$i]);
 6523: 	return 1;
 6524:     }
 6525:     return 0;
 6526: }
 6527: 
 6528: =pod
 6529: 
 6530: =item scantron_filter_not_exam
 6531: 
 6532:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6533:    filter out resources that are not marked as 'exam' mode
 6534: 
 6535: =cut
 6536: 
 6537: sub scantron_filter_not_exam {
 6538:     my ($curres)=@_;
 6539:     
 6540:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6541: 	# if the user has asked to not have either hidden
 6542: 	# or 'randomout' controlled resources to be graded
 6543: 	# don't include them
 6544: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6545: 	    && $curres->randomout) {
 6546: 	    return 0;
 6547: 	}
 6548: 	return 1;
 6549:     }
 6550:     return 0;
 6551: }
 6552: 
 6553: =pod
 6554: 
 6555: =item scantron_validate_sequence
 6556: 
 6557:     Validates the selected sequence, checking for resource that are
 6558:     not set to exam mode.
 6559: 
 6560: =cut
 6561: 
 6562: sub scantron_validate_sequence {
 6563:     my ($r,$currentphase) = @_;
 6564: 
 6565:     my $navmap=Apache::lonnavmaps::navmap->new();
 6566:     my (undef,undef,$sequence)=
 6567: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6568: 
 6569:     my $map=$navmap->getResourceByUrl($sequence);
 6570: 
 6571:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6572:                                     value="ignore" />');
 6573:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6574: 	my @resources=
 6575: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6576: 	if (@resources) {
 6577: 	    $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>");
 6578: 	    return (1,$currentphase);
 6579: 	}
 6580:     }
 6581: 
 6582:     return (0,$currentphase+1);
 6583: }
 6584: 
 6585: 
 6586: 
 6587: sub scantron_validate_ID {
 6588:     my ($r,$currentphase) = @_;
 6589:     
 6590:     #get student info
 6591:     my $classlist=&Apache::loncoursedata::get_classlist();
 6592:     my %idmap=&username_to_idmap($classlist);
 6593: 
 6594:     #get scantron line setup
 6595:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6596:     my ($scanlines,$scan_data)=&scantron_getfile();
 6597:     
 6598:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6599: 
 6600:     my %found=('ids'=>{},'usernames'=>{});
 6601:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6602: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6603: 	if ($line=~/^[\s\cz]*$/) { next; }
 6604: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6605: 						 $scan_data);
 6606: 	my $id=$$scan_record{'scantron.ID'};
 6607: 	my $found;
 6608: 	foreach my $checkid (keys(%idmap)) {
 6609: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6610: 	}
 6611: 	if ($found) {
 6612: 	    my $username=$idmap{$found};
 6613: 	    if ($found{'ids'}{$found}) {
 6614: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6615: 					 $line,'duplicateID',$found);
 6616: 		return(1,$currentphase);
 6617: 	    } elsif ($found{'usernames'}{$username}) {
 6618: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6619: 					 $line,'duplicateID',$username);
 6620: 		return(1,$currentphase);
 6621: 	    }
 6622: 	    #FIXME store away line we previously saw the ID on to use above
 6623: 	    $found{'ids'}{$found}++;
 6624: 	    $found{'usernames'}{$username}++;
 6625: 	} else {
 6626: 	    if ($id =~ /^\s*$/) {
 6627: 		my $username=&scan_data($scan_data,"$i.user");
 6628: 		if (defined($username) && $found{'usernames'}{$username}) {
 6629: 		    &scantron_get_correction($r,$i,$scan_record,
 6630: 					     \%scantron_config,
 6631: 					     $line,'duplicateID',$username);
 6632: 		    return(1,$currentphase);
 6633: 		} elsif (!defined($username)) {
 6634: 		    &scantron_get_correction($r,$i,$scan_record,
 6635: 					     \%scantron_config,
 6636: 					     $line,'incorrectID');
 6637: 		    return(1,$currentphase);
 6638: 		}
 6639: 		$found{'usernames'}{$username}++;
 6640: 	    } else {
 6641: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6642: 					 $line,'incorrectID');
 6643: 		return(1,$currentphase);
 6644: 	    }
 6645: 	}
 6646:     }
 6647: 
 6648:     return (0,$currentphase+1);
 6649: }
 6650: 
 6651: 
 6652: sub scantron_get_correction {
 6653:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6654: #FIXME in the case of a duplicated ID the previous line, probably need
 6655: #to show both the current line and the previous one and allow skipping
 6656: #the previous one or the current one
 6657: 
 6658:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6659: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6660: 			    " for PaperID <tt>[_1]</tt>",
 6661: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6662:     } else {
 6663: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6664: 			    " in scanline [_1] <pre>[_2]</pre>",
 6665: 			    $i,$line)."</p> \n");
 6666:     }
 6667:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6668: 			  "The name on the paper is [_2],[_3]",
 6669: 			  $$scan_record{'scantron.ID'},
 6670: 			  $$scan_record{'scantron.LastName'},
 6671: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6672: 
 6673:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6674:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6675:                            # Array populated for doublebubble or
 6676:     my @lines_to_correct;  # missingbubble errors to build javascript
 6677:                            # to validate radio button checking   
 6678: 
 6679:     if ($error =~ /ID$/) {
 6680: 	if ($error eq 'incorrectID') {
 6681: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6682: 		      "</p>\n");
 6683: 	} elsif ($error eq 'duplicateID') {
 6684: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6685: 	}
 6686: 	$r->print($message);
 6687: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6688: 	$r->print("\n<ul><li> ");
 6689: 	#FIXME it would be nice if this sent back the user ID and
 6690: 	#could do partial userID matches
 6691: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6692: 				       'scantron_username','scantron_domain'));
 6693: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6694: 	$r->print("\n@".
 6695: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6696: 
 6697: 	$r->print('</li>');
 6698:     } elsif ($error =~ /CODE$/) {
 6699: 	if ($error eq 'incorrectCODE') {
 6700: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6701: 	} elsif ($error eq 'duplicateCODE') {
 6702: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 6703: 	}
 6704: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6705: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6706: 	$r->print($message);
 6707: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6708: 	$r->print("\n<br /> ");
 6709: 	my $i=0;
 6710: 	if ($error eq 'incorrectCODE' 
 6711: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6712: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6713: 	    if ($closest > 0) {
 6714: 		foreach my $testcode (@{$closest}) {
 6715: 		    my $checked='';
 6716: 		    if (!$i) { $checked=' checked="checked" '; }
 6717: 		    $r->print("
 6718:    <label>
 6719:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6720:        ".&mt("Use the similar CODE [_1] instead.",
 6721: 	    "<b><tt>".$testcode."</tt></b>")."
 6722:     </label>
 6723:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6724: 		    $r->print("\n<br />");
 6725: 		    $i++;
 6726: 		}
 6727: 	    }
 6728: 	}
 6729: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6730: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6731: 	    $r->print("
 6732:     <label>
 6733:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6734:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6735: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6736:     </label>");
 6737: 	    $r->print("\n<br />");
 6738: 	}
 6739: 
 6740: 	$r->print(<<ENDSCRIPT);
 6741: <script type="text/javascript">
 6742: function change_radio(field) {
 6743:     var slct=document.scantronupload.scantron_CODE_resolution;
 6744:     var i;
 6745:     for (i=0;i<slct.length;i++) {
 6746:         if (slct[i].value==field) { slct[i].checked=true; }
 6747:     }
 6748: }
 6749: </script>
 6750: ENDSCRIPT
 6751: 	my $href="/adm/pickcode?".
 6752: 	   "form=".&escape("scantronupload").
 6753: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6754: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6755: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6756: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6757: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6758: 	    $r->print("
 6759:     <label>
 6760:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6761:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6762: 	     "<a target='_blank' href='$href'>","</a>")."
 6763:     </label> 
 6764:     ".&mt("Selected CODE is [_1]","<input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />"));
 6765: 	    $r->print("\n<br />");
 6766: 	}
 6767: 	$r->print("
 6768:     <label>
 6769:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6770:        ".&mt("Use [_1] as the CODE.",
 6771: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6772: 	$r->print("\n<br /><br />");
 6773:     } elsif ($error eq 'doublebubble') {
 6774: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6775: 
 6776: 	# The form field scantron_questions is acutally a list of line numbers.
 6777: 	# represented by this form so:
 6778: 
 6779: 	my $line_list = &questions_to_line_list($arg);
 6780: 
 6781: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6782: 		  $line_list.'" />');
 6783: 	$r->print($message);
 6784: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6785: 	foreach my $question (@{$arg}) {
 6786: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6787:                                                    $scan_record, $error);
 6788:             push(@lines_to_correct,@linenums);
 6789: 	}
 6790:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6791:     } elsif ($error eq 'missingbubble') {
 6792: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6793: 	$r->print($message);
 6794: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6795: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6796: 
 6797: 	# The form field scantron_questions is actually a list of line numbers not
 6798: 	# a list of question numbers. Therefore:
 6799: 	#
 6800: 	
 6801: 	my $line_list = &questions_to_line_list($arg);
 6802: 
 6803: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6804: 		  $line_list.'" />');
 6805: 	foreach my $question (@{$arg}) {
 6806: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6807:                                                    $scan_record, $error);
 6808:             push(@lines_to_correct,@linenums);
 6809: 	}
 6810:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6811:     } else {
 6812: 	$r->print("\n<ul>");
 6813:     }
 6814:     $r->print("\n</li></ul>");
 6815: }
 6816: 
 6817: sub verify_bubbles_checked {
 6818:     my (@ansnums) = @_;
 6819:     my $ansnumstr = join('","',@ansnums);
 6820:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6821:     my $output = (<<ENDSCRIPT);
 6822: <script type="text/javascript">
 6823: function verify_bubble_radio(form) {
 6824:     var ansnumArray = new Array ("$ansnumstr");
 6825:     var need_bubble_count = 0;
 6826:     for (var i=0; i<ansnumArray.length; i++) {
 6827:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6828:             var bubble_picked = 0; 
 6829:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6830:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6831:                     bubble_picked = 1;
 6832:                 }
 6833:             }
 6834:             if (bubble_picked == 0) {
 6835:                 need_bubble_count ++;
 6836:             }
 6837:         }
 6838:     }
 6839:     if (need_bubble_count) {
 6840:         alert("$warning");
 6841:         return;
 6842:     }
 6843:     form.submit(); 
 6844: }
 6845: </script>
 6846: ENDSCRIPT
 6847:     return $output;
 6848: }
 6849: 
 6850: =pod
 6851: 
 6852: =item  questions_to_line_list
 6853: 
 6854: Converts a list of questions into a string of comma separated
 6855: line numbers in the answer sheet used by the questions.  This is
 6856: used to fill in the scantron_questions form field.
 6857: 
 6858:   Arguments:
 6859:      questions    - Reference to an array of questions.
 6860: 
 6861: =cut
 6862: 
 6863: 
 6864: sub questions_to_line_list {
 6865:     my ($questions) = @_;
 6866:     my @lines;
 6867: 
 6868:     foreach my $item (@{$questions}) {
 6869:         my $question = $item;
 6870:         my ($first,$count,$last);
 6871:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6872:             $question = $1;
 6873:             my $subquestion = $2;
 6874:             $first = $first_bubble_line{$question-1} + 1;
 6875:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6876:             my $subcount = 1;
 6877:             while ($subcount<$subquestion) {
 6878:                 $first += $subans[$subcount-1];
 6879:                 $subcount ++;
 6880:             }
 6881:             $count = $subans[$subquestion-1];
 6882:         } else {
 6883: 	    $first   = $first_bubble_line{$question-1} + 1;
 6884: 	    $count   = $bubble_lines_per_response{$question-1};
 6885:         }
 6886:         $last = $first+$count-1;
 6887:         push(@lines, ($first..$last));
 6888:     }
 6889:     return join(',', @lines);
 6890: }
 6891: 
 6892: =pod 
 6893: 
 6894: =item prompt_for_corrections
 6895: 
 6896: Prompts for a potentially multiline correction to the
 6897: user's bubbling (factors out common code from scantron_get_correction
 6898: for multi and missing bubble cases).
 6899: 
 6900:  Arguments:
 6901:    $r           - Apache request object.
 6902:    $question    - The question number to prompt for.
 6903:    $scan_config - The scantron file configuration hash.
 6904:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6905:    $error       - Type of error
 6906: 
 6907:  Implicit inputs:
 6908:    %bubble_lines_per_response   - Starting line numbers for each question.
 6909:                                   Numbered from 0 (but question numbers are from
 6910:                                   1.
 6911:    %first_bubble_line           - Starting bubble line for each question.
 6912:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6913:                                   type problems render as separate sub-questions, 
 6914:                                   in exam mode. This hash contains a 
 6915:                                   comma-separated list of the lines per 
 6916:                                   sub-question.
 6917:    %responsetype_per_response   - essayresponse, formularesponse,
 6918:                                   stringresponse, imageresponse, reactionresponse,
 6919:                                   and organicresponse type problem parts can have
 6920:                                   multiple lines per response if the weight
 6921:                                   assigned exceeds 10.  In this case, only
 6922:                                   one bubble per line is permitted, but more 
 6923:                                   than one line might contain bubbles, e.g.
 6924:                                   bubbling of: line 1 - J, line 2 - J, 
 6925:                                   line 3 - B would assign 22 points.  
 6926: 
 6927: =cut
 6928: 
 6929: sub prompt_for_corrections {
 6930:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6931:     my ($current_line,$lines);
 6932:     my @linenums;
 6933:     my $questionnum = $question;
 6934:     if ($question =~ /^(\d+)\.(\d+)$/) {
 6935:         $question = $1;
 6936:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6937:         my $subquestion = $2;
 6938:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6939:         my $subcount = 1;
 6940:         while ($subcount<$subquestion) {
 6941:             $current_line += $subans[$subcount-1];
 6942:             $subcount ++;
 6943:         }
 6944:         $lines = $subans[$subquestion-1];
 6945:     } else {
 6946:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6947:         $lines        = $bubble_lines_per_response{$question-1};
 6948:     }
 6949:     if ($lines > 1) {
 6950:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 6951:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 6952:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 6953:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 6954:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 6955:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 6956:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 6957:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their scantron sheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during scantron grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 6958:         } else {
 6959:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 6960:         }
 6961:     }
 6962:     for (my $i =0; $i < $lines; $i++) {
 6963:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 6964: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 6965: 	        		  $questionnum,$error,split('', $selected));
 6966:         push(@linenums,$current_line);
 6967: 	$current_line++;
 6968:     }
 6969:     if ($lines > 1) {
 6970: 	$r->print("<hr /><br />");
 6971:     }
 6972:     return @linenums;
 6973: }
 6974: 
 6975: =pod
 6976: 
 6977: =item scantron_bubble_selector
 6978:   
 6979:    Generates the html radiobuttons to correct a single bubble line
 6980:    possibly showing the existing the selected bubbles if known
 6981: 
 6982:  Arguments:
 6983:     $r           - Apache request object
 6984:     $scan_config - hash from &get_scantron_config()
 6985:     $line        - Number of the line being displayed.
 6986:     $questionnum - Question number (may include subquestion)
 6987:     $error       - Type of error.
 6988:     @selected    - Array of bubbles picked on this line.
 6989: 
 6990: =cut
 6991: 
 6992: sub scantron_bubble_selector {
 6993:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 6994:     my $max=$$scan_config{'Qlength'};
 6995: 
 6996:     my $scmode=$$scan_config{'Qon'};
 6997:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 6998: 
 6999:     my @alphabet=('A'..'Z');
 7000:     $r->print(&Apache::loncommon::start_data_table().
 7001:               &Apache::loncommon::start_data_table_row());
 7002:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7003:     for (my $i=0;$i<$max+1;$i++) {
 7004: 	$r->print("\n".'<td align="center">');
 7005: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7006: 	else { $r->print('&nbsp;'); }
 7007: 	$r->print('</td>');
 7008:     }
 7009:     $r->print(&Apache::loncommon::end_data_table_row().
 7010:               &Apache::loncommon::start_data_table_row());
 7011:     for (my $i=0;$i<$max;$i++) {
 7012: 	$r->print("\n".
 7013: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7014: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7015:     }
 7016:     my $nobub_checked = ' ';
 7017:     if ($error eq 'missingbubble') {
 7018:         $nobub_checked = ' checked = "checked" ';
 7019:     }
 7020:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7021: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7022:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7023:               $line.'" value="'.$questionnum.'" /></td>');
 7024:     $r->print(&Apache::loncommon::end_data_table_row().
 7025:               &Apache::loncommon::end_data_table());
 7026: }
 7027: 
 7028: =pod
 7029: 
 7030: =item num_matches
 7031: 
 7032:    Counts the number of characters that are the same between the two arguments.
 7033: 
 7034:  Arguments:
 7035:    $orig - CODE from the scanline
 7036:    $code - CODE to match against
 7037: 
 7038:  Returns:
 7039:    $count - integer count of the number of same characters between the
 7040:             two arguments
 7041: 
 7042: =cut
 7043: 
 7044: sub num_matches {
 7045:     my ($orig,$code) = @_;
 7046:     my @code=split(//,$code);
 7047:     my @orig=split(//,$orig);
 7048:     my $same=0;
 7049:     for (my $i=0;$i<scalar(@code);$i++) {
 7050: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7051:     }
 7052:     return $same;
 7053: }
 7054: 
 7055: =pod
 7056: 
 7057: =item scantron_get_closely_matching_CODEs
 7058: 
 7059:    Cycles through all CODEs and finds the set that has the greatest
 7060:    number of same characters as the provided CODE
 7061: 
 7062:  Arguments:
 7063:    $allcodes - hash ref returned by &get_codes()
 7064:    $CODE     - CODE from the current scanline
 7065: 
 7066:  Returns:
 7067:    2 element list
 7068:     - first elements is number of how closely matching the best fit is 
 7069:       (5 means best set has 5 matching characters)
 7070:     - second element is an arrary ref containing the set of valid CODEs
 7071:       that best fit the passed in CODE
 7072: 
 7073: =cut
 7074: 
 7075: sub scantron_get_closely_matching_CODEs {
 7076:     my ($allcodes,$CODE)=@_;
 7077:     my @CODEs;
 7078:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7079: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7080:     }
 7081: 
 7082:     return ($#CODEs,$CODEs[-1]);
 7083: }
 7084: 
 7085: =pod
 7086: 
 7087: =item get_codes
 7088: 
 7089:    Builds a hash which has keys of all of the valid CODEs from the selected
 7090:    set of remembered CODEs.
 7091: 
 7092:  Arguments:
 7093:   $old_name - name of the set of remembered CODEs
 7094:   $cdom     - domain of the course
 7095:   $cnum     - internal course name
 7096: 
 7097:  Returns:
 7098:   %allcodes - keys are the valid CODEs, values are all 1
 7099: 
 7100: =cut
 7101: 
 7102: sub get_codes {
 7103:     my ($old_name, $cdom, $cnum) = @_;
 7104:     if (!$old_name) {
 7105: 	$old_name=$env{'form.scantron_CODElist'};
 7106:     }
 7107:     if (!$cdom) {
 7108: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7109:     }
 7110:     if (!$cnum) {
 7111: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7112:     }
 7113:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7114: 				    $cdom,$cnum);
 7115:     my %allcodes;
 7116:     if ($result{"type\0$old_name"} eq 'number') {
 7117: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7118:     } else {
 7119: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7120:     }
 7121:     return %allcodes;
 7122: }
 7123: 
 7124: =pod
 7125: 
 7126: =item scantron_validate_CODE
 7127: 
 7128:    Validates all scanlines in the selected file to not have any
 7129:    invalid or underspecified CODEs and that none of the codes are
 7130:    duplicated if this was requested.
 7131: 
 7132: =cut
 7133: 
 7134: sub scantron_validate_CODE {
 7135:     my ($r,$currentphase) = @_;
 7136:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7137:     if ($scantron_config{'CODElocation'} &&
 7138: 	$scantron_config{'CODEstart'} &&
 7139: 	$scantron_config{'CODElength'}) {
 7140: 	if (!defined($env{'form.scantron_CODElist'})) {
 7141: 	    &FIXME_blow_up()
 7142: 	}
 7143:     } else {
 7144: 	return (0,$currentphase+1);
 7145:     }
 7146:     
 7147:     my %usedCODEs;
 7148: 
 7149:     my %allcodes=&get_codes();
 7150: 
 7151:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7152: 
 7153:     my ($scanlines,$scan_data)=&scantron_getfile();
 7154:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7155: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7156: 	if ($line=~/^[\s\cz]*$/) { next; }
 7157: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7158: 						 $scan_data);
 7159: 	my $CODE=$$scan_record{'scantron.CODE'};
 7160: 	my $error=0;
 7161: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7162: 	    &scantron_get_correction($r,$i,$scan_record,
 7163: 				     \%scantron_config,
 7164: 				     $line,'incorrectCODE',\%allcodes);
 7165: 	    return(1,$currentphase);
 7166: 	}
 7167: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7168: 	    && !$$scan_record{'scantron.useCODE'}) {
 7169: 	    &scantron_get_correction($r,$i,$scan_record,
 7170: 				     \%scantron_config,
 7171: 				     $line,'incorrectCODE',\%allcodes);
 7172: 	    return(1,$currentphase);
 7173: 	}
 7174: 	if (exists($usedCODEs{$CODE}) 
 7175: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7176: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7177: 	    &scantron_get_correction($r,$i,$scan_record,
 7178: 				     \%scantron_config,
 7179: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7180: 	    return(1,$currentphase);
 7181: 	}
 7182: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7183:     }
 7184:     return (0,$currentphase+1);
 7185: }
 7186: 
 7187: =pod
 7188: 
 7189: =item scantron_validate_doublebubble
 7190: 
 7191:    Validates all scanlines in the selected file to not have any
 7192:    bubble lines with multiple bubbles marked.
 7193: 
 7194: =cut
 7195: 
 7196: sub scantron_validate_doublebubble {
 7197:     my ($r,$currentphase) = @_;
 7198:     #get student info
 7199:     my $classlist=&Apache::loncoursedata::get_classlist();
 7200:     my %idmap=&username_to_idmap($classlist);
 7201: 
 7202:     #get scantron line setup
 7203:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7204:     my ($scanlines,$scan_data)=&scantron_getfile();
 7205:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7206: 
 7207:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7208: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7209: 	if ($line=~/^[\s\cz]*$/) { next; }
 7210: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7211: 						 $scan_data);
 7212: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7213: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7214: 				 'doublebubble',
 7215: 				 $$scan_record{'scantron.doubleerror'});
 7216:     	return (1,$currentphase);
 7217:     }
 7218:     return (0,$currentphase+1);
 7219: }
 7220: 
 7221: 
 7222: sub scantron_get_maxbubble {
 7223:     if (defined($env{'form.scantron_maxbubble'}) &&
 7224: 	$env{'form.scantron_maxbubble'}) {
 7225: 	&restore_bubble_lines();
 7226: 	return $env{'form.scantron_maxbubble'};
 7227:     }
 7228: 
 7229:     my (undef, undef, $sequence) =
 7230: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7231: 
 7232:     my $navmap=Apache::lonnavmaps::navmap->new();
 7233:     my $map=$navmap->getResourceByUrl($sequence);
 7234:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7235: 
 7236:     &Apache::lonxml::clear_problem_counter();
 7237: 
 7238:     my $uname       = $env{'form.student'};
 7239:     my $udom        = $env{'form.userdom'};
 7240:     my $cid         = $env{'request.course.id'};
 7241:     my $total_lines = 0;
 7242:     %bubble_lines_per_response = ();
 7243:     %first_bubble_line         = ();
 7244:     %subdivided_bubble_lines   = ();
 7245:     %responsetype_per_response = ();
 7246:   
 7247:     my $response_number = 0;
 7248:     my $bubble_line     = 0;
 7249:     foreach my $resource (@resources) {
 7250:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7251:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7252: 	    foreach my $part_id (@{$parts}) {
 7253:                 my $lines;
 7254: 
 7255: 	        # TODO - make this a persistent hash not an array.
 7256: 
 7257:                 # optionresponse, matchresponse and rankresponse type items 
 7258:                 # render as separate sub-questions in exam mode.
 7259:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7260:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7261:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7262:                     my ($numbub,$numshown);
 7263:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7264:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7265:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7266:                         }
 7267:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7268:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7269:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7270:                         }
 7271:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7272:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7273:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7274:                         }
 7275:                     }
 7276:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7277:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7278:                     }
 7279:                     my $bubbles_per_line = 10;
 7280:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7281:                     if (($numbub % $bubbles_per_line) != 0) {
 7282:                         $inner_bubble_lines++;
 7283:                     }
 7284:                     for (my $i=0; $i<$numshown; $i++) {
 7285:                         $subdivided_bubble_lines{$response_number} .= 
 7286:                             $inner_bubble_lines.',';
 7287:                     }
 7288:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7289:                     $lines = $numshown * $inner_bubble_lines;
 7290:                 } else {
 7291:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7292:                 } 
 7293: 
 7294:                 $first_bubble_line{$response_number} = $bubble_line;
 7295: 	        $bubble_lines_per_response{$response_number} = $lines;
 7296:                 $responsetype_per_response{$response_number} = 
 7297:                     $analysis->{$part_id.'.type'};
 7298: 	        $response_number++;
 7299: 
 7300: 	        $bubble_line +=  $lines;
 7301: 	        $total_lines +=  $lines;
 7302: 	    }
 7303:         }
 7304:     }
 7305:     &Apache::lonnet::delenv('scantron.');
 7306: 
 7307:     &save_bubble_lines();
 7308:     $env{'form.scantron_maxbubble'} =
 7309: 	$total_lines;
 7310:     return $env{'form.scantron_maxbubble'};
 7311: }
 7312: 
 7313: sub scantron_partids_tograde {
 7314:     my ($resource,$cid,$uname,$udom) = @_;
 7315:     my (%analysis,@parts); 
 7316: 
 7317:     if (ref($resource)) {
 7318:         my $symb = $resource->symb();
 7319:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
 7320:                                         ('symb' => $symb,
 7321:                                          'grade_target' => 'analyze',
 7322:                                          'grade_courseid' => $cid,
 7323:                                          'grade_domain' => $udom,
 7324:                                          'grade_username' => $uname));
 7325:         my (undef, $an) = split(/_HASH_REF__/,$result, 2);
 7326:         %analysis = &Apache::lonnet::str2hash($an);
 7327: 
 7328:         if (ref($analysis{'parts'}) eq 'ARRAY') {
 7329:             foreach my $part (@{$analysis{'parts'}}) {
 7330:                 my ($id,$respid) = split(/\./,$part);
 7331:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
 7332:                     push(@parts,$part);
 7333:                 }
 7334:             }
 7335:         }
 7336:     }
 7337:     return (\%analysis,\@parts);
 7338: }
 7339: 
 7340: sub scantron_validate_missingbubbles {
 7341:     my ($r,$currentphase) = @_;
 7342:     #get student info
 7343:     my $classlist=&Apache::loncoursedata::get_classlist();
 7344:     my %idmap=&username_to_idmap($classlist);
 7345: 
 7346:     #get scantron line setup
 7347:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7348:     my ($scanlines,$scan_data)=&scantron_getfile();
 7349:     my $max_bubble=&scantron_get_maxbubble();
 7350:     if (!$max_bubble) { $max_bubble=2**31; }
 7351:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7352: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7353: 	if ($line=~/^[\s\cz]*$/) { next; }
 7354: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7355: 						 $scan_data);
 7356: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7357: 	my @to_correct;
 7358: 	
 7359: 	# Probably here's where the error is...
 7360: 
 7361: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7362:             my $lastbubble;
 7363:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7364:                my $question = $1;
 7365:                my $subquestion = $2;
 7366:                if (!defined($first_bubble_line{$question -1})) { next; }
 7367:                my $first = $first_bubble_line{$question-1};
 7368:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7369:                my $subcount = 1;
 7370:                while ($subcount<$subquestion) {
 7371:                    $first += $subans[$subcount-1];
 7372:                    $subcount ++;
 7373:                }
 7374:                my $count = $subans[$subquestion-1];
 7375:                $lastbubble = $first + $count;
 7376:             } else {
 7377:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7378:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7379:             }
 7380:             if ($lastbubble > $max_bubble) { next; }
 7381: 	    push(@to_correct,$missing);
 7382: 	}
 7383: 	if (@to_correct) {
 7384: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7385: 				     $line,'missingbubble',\@to_correct);
 7386: 	    return (1,$currentphase);
 7387: 	}
 7388: 
 7389:     }
 7390:     return (0,$currentphase+1);
 7391: }
 7392: 
 7393: 
 7394: sub scantron_process_students {
 7395:     my ($r) = @_;
 7396: 
 7397:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7398:     my ($symb)=&get_symb($r);
 7399:     if (!$symb) {
 7400: 	return '';
 7401:     }
 7402:     my $default_form_data=&defaultFormData($symb);
 7403: 
 7404:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7405:     my ($scanlines,$scan_data)=&scantron_getfile();
 7406:     my $classlist=&Apache::loncoursedata::get_classlist();
 7407:     my %idmap=&username_to_idmap($classlist);
 7408:     my $navmap=Apache::lonnavmaps::navmap->new();
 7409:     my $map=$navmap->getResourceByUrl($sequence);
 7410:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7411: 
 7412:     my ($uname,$udom,%partids_by_symb);
 7413:     foreach my $resource (@resources) {
 7414:         my $ressymb = $resource->symb(); 
 7415:         my ($analysis,$parts) = 
 7416:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7417:         $partids_by_symb{$ressymb} = $parts;
 7418:     }
 7419: #    $r->print("geto ".scalar(@resources)."<br />");
 7420:     my $result= <<SCANTRONFORM;
 7421: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7422:   <input type="hidden" name="command" value="scantron_configphase" />
 7423:   $default_form_data
 7424: SCANTRONFORM
 7425:     $r->print($result);
 7426: 
 7427:     my @delayqueue;
 7428:     my (%completedstudents,%scandata);
 7429:     
 7430:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7431:     my $count=&get_todo_count($scanlines,$scan_data);
 7432:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7433:  				    'Scantron Progress',$count,
 7434: 				    'inline',undef,'scantronupload');
 7435:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7436: 					  'Processing first student');
 7437:     $r->print('<br />');
 7438:     my $start=&Time::HiRes::time();
 7439:     my $i=-1;
 7440:     my $started;
 7441: 
 7442:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7443:     
 7444: 
 7445:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7446:     # the user and return.
 7447: 
 7448:     if ($ssi_error) {
 7449: 	$r->print("</form>");
 7450: 	&ssi_print_error($r);
 7451: 	$r->print(&show_grading_menu_form($symb));
 7452:         &Apache::lonnet::remove_lock($lock);
 7453: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7454:     }
 7455: 
 7456:     my %lettdig = &letter_to_digits();
 7457:     my $numletts = scalar(keys(%lettdig));
 7458: 
 7459:     while ($i<$scanlines->{'count'}) {
 7460:  	($uname,$udom)=('','');
 7461:  	$i++;
 7462:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7463:  	if ($line=~/^[\s\cz]*$/) { next; }
 7464: 	if ($started) {
 7465: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7466: 						     'last student');
 7467: 	}
 7468: 	$started=1;
 7469:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7470:  						 $scan_data);
 7471:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7472:  					      \%idmap,$i)) {
 7473:   	    &scantron_add_delay(\@delayqueue,$line,
 7474:  				'Unable to find a student that matches',1);
 7475:  	    next;
 7476:   	}
 7477:  	if (exists $completedstudents{$uname}) {
 7478:  	    &scantron_add_delay(\@delayqueue,$line,
 7479:  				'Student '.$uname.' has multiple sheets',2);
 7480:  	    next;
 7481:  	}
 7482:   	($uname,$udom)=split(/:/,$uname);
 7483: 
 7484: 	&Apache::lonxml::clear_problem_counter();
 7485:   	&Apache::lonnet::appenv($scan_record);
 7486: 
 7487: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7488: 	    &scantron_putfile($scanlines,$scan_data);
 7489: 	}
 7490: 	
 7491:         my $scancode;
 7492:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7493:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7494:             $scancode = $scan_record->{'scantron.CODE'};
 7495:         } else {
 7496:             $scancode = '';
 7497:         }
 7498: 
 7499:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7500:                                    @resources) eq 'ssi_error') {
 7501:             $ssi_error = 0; # So end of handler error message does not trigger.
 7502:             $r->print("</form>");
 7503:             &ssi_print_error($r);
 7504:             $r->print(&show_grading_menu_form($symb));
 7505:             &Apache::lonnet::remove_lock($lock);
 7506:             return '';      # Why return ''?  Beats me.
 7507:         }
 7508: 
 7509: 	$completedstudents{$uname}={'line'=>$line};
 7510:         if ($env{'form.verifyrecord'}) {
 7511:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7512:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7513:             chomp($studentdata);
 7514:             $studentdata =~ s/\r$//;
 7515:             my $studentrecord = '';
 7516:             my $counter = -1;
 7517:             foreach my $resource (@resources) {
 7518:                 ($counter,my $recording) =
 7519:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7520:                                              $counter,$studentdata,\%partids_by_symb,
 7521:                                              \%scantron_config,\%lettdig,$numletts);
 7522:                 $studentrecord .= $recording;
 7523:             }
 7524:             if ($studentrecord ne $studentdata) {
 7525:                 $counter = -1;
 7526:                 $studentrecord = '';
 7527:                 foreach my $resource (@resources) {
 7528:                     ($counter,my $recording) =
 7529:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7530:                                                  $counter,$studentdata,\%partids_by_symb,
 7531:                                                  \%scantron_config,\%lettdig,$numletts);
 7532:                     $studentrecord .= $recording;
 7533:                 }
 7534:                 if ($studentrecord ne $studentdata) {
 7535:                     $r->print('<p><span class="LC_error">');
 7536:                     if ($scancode eq '') {
 7537:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7538:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7539:                     } else {
 7540:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7541:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7542:                     }
 7543:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7544:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7545:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7546:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7547:                               &Apache::loncommon::start_data_table_row().
 7548:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7549:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7550:                               &Apache::loncommon::end_data_table_row().
 7551:                               &Apache::loncommon::start_data_table_row().
 7552:                               '<td>Stored submissions</td>'.
 7553:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7554:                               &Apache::loncommon::end_data_table_row().
 7555:                               &Apache::loncommon::end_data_table().'</p>');
 7556:                 } else {
 7557:                     $r->print('<br /><span class="LC_warning">'.
 7558:                              &mt('A second grading pass was needed for user: [_1] with ID: [_2], because a mismatch was seen on the first pass.',$uname.':'.$udom,$scan_record->{'scantron.ID'}).'<br />'.
 7559:                              &mt("As a consequence, this user's submission history records two tries.").
 7560:                                  '</span><br />');
 7561:                 }
 7562:             }
 7563:         }
 7564:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7565:     } continue {
 7566: 	&Apache::lonxml::clear_problem_counter();
 7567: 	&Apache::lonnet::delenv('scantron.');
 7568:     }
 7569:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7570:     &Apache::lonnet::remove_lock($lock);
 7571: #    my $lasttime = &Time::HiRes::time()-$start;
 7572: #    $r->print("<p>took $lasttime</p>");
 7573: 
 7574:     $r->print("</form>");
 7575:     $r->print(&show_grading_menu_form($symb));
 7576:     return '';
 7577: }
 7578: 
 7579: sub grade_student_bubbles {
 7580:     my ($r,$uname,$udom,$scan_record,$scancode,@resources) = @_;
 7581:     foreach my $resource (@resources) {
 7582:         my %form = ('submitted'     => 'scantron',
 7583:                     'grade_target'  => 'grade',
 7584:                     'grade_username'=> $uname,
 7585:                     'grade_domain'  => $udom,
 7586:                     'grade_courseid'=> $env{'request.course.id'},
 7587:                     'grade_symb'    => $resource->symb(),
 7588:                     'CODE'          => $scancode);
 7589:         my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7590:         return 'ssi_error' if ($ssi_error);
 7591:         last if (&Apache::loncommon::connection_aborted($r));
 7592:     }
 7593:     return;
 7594: }
 7595: 
 7596: sub scantron_upload_scantron_data {
 7597:     my ($r)=@_;
 7598:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7599:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7600: 							  'domainid',
 7601: 							  'coursename');
 7602:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7603: 						   'domainid');
 7604:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7605:     $r->print('
 7606: <script type="text/javascript" language="javascript">
 7607:     function checkUpload(formname) {
 7608: 	if (formname.upfile.value == "") {
 7609: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 7610: 	    return false;
 7611: 	}
 7612: 	formname.submit();
 7613:     }
 7614: </script>
 7615: 
 7616: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7617: '.$default_form_data.'
 7618: <table>
 7619: <tr><td>'.$select_link.'                             </td></tr>
 7620: <tr><td>'.&mt('Course ID:').'     </td>
 7621:     <td><input name="courseid"   type="text" />      </td></tr>
 7622: <tr><td>'.&mt('Course Name:').'   </td>
 7623:     <td><input name="coursename" type="text" />      </td></tr>
 7624: <tr><td>'.&mt('Domain:').'        </td>
 7625:     <td>'.$domsel.'                                  </td></tr>
 7626: <tr><td>'.&mt('File to upload:').'</td>
 7627:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7628: </table>
 7629: <input name="command" value="scantronupload_save" type="hidden" />
 7630: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7631: </form>
 7632: ');
 7633:     return '';
 7634: }
 7635: 
 7636: 
 7637: sub scantron_upload_scantron_data_save {
 7638:     my($r)=@_;
 7639:     my ($symb)=&get_symb($r,1);
 7640:     my $doanotherupload=
 7641: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7642: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7643: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7644: 	'</form>'."\n";
 7645:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7646: 	!&Apache::lonnet::allowed('usc',
 7647: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7648: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7649: 	if ($symb) {
 7650: 	    $r->print(&show_grading_menu_form($symb));
 7651: 	} else {
 7652: 	    $r->print($doanotherupload);
 7653: 	}
 7654: 	return '';
 7655:     }
 7656:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7657:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7658:     my $fname=$env{'form.upfile.filename'};
 7659:     #FIXME
 7660:     #copied from lonnet::userfileupload()
 7661:     #make that function able to target a specified course
 7662:     # Replace Windows backslashes by forward slashes
 7663:     $fname=~s/\\/\//g;
 7664:     # Get rid of everything but the actual filename
 7665:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7666:     # Replace spaces by underscores
 7667:     $fname=~s/\s+/\_/g;
 7668:     # Replace all other weird characters by nothing
 7669:     $fname=~s/[^\w\.\-]//g;
 7670:     # See if there is anything left
 7671:     unless ($fname) { return 'error: no uploaded file'; }
 7672:     my $uploadedfile=$fname;
 7673:     $fname='scantron_orig_'.$fname;
 7674:     if (length($env{'form.upfile'}) < 2) {
 7675: 	$r->print(&mt("<span class=\"LC_error\">Error:</span> The file you attempted to upload, [_1]  contained no information. Please check that you entered the correct filename.",'<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7676:     } else {
 7677: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7678: 	if ($result =~ m|^/uploaded/|) {
 7679: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7680: 			  (length($env{'form.upfile'})-1),
 7681: 			  '<span class="LC_filename">'.$result."</span>"));
 7682: 	} else {
 7683: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7684: 			  $result,
 7685: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7686: 
 7687: 	}
 7688:     }
 7689:     if ($symb) {
 7690: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7691:     } else {
 7692: 	$r->print($doanotherupload);
 7693:     }
 7694:     return '';
 7695: }
 7696: 
 7697: sub valid_file {
 7698:     my ($requested_file)=@_;
 7699:     foreach my $filename (sort(&scantron_filenames())) {
 7700: 	if ($requested_file eq $filename) { return 1; }
 7701:     }
 7702:     return 0;
 7703: }
 7704: 
 7705: sub scantron_download_scantron_data {
 7706:     my ($r)=@_;
 7707:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7708:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7709:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7710:     my $file=$env{'form.scantron_selectfile'};
 7711:     if (! &valid_file($file)) {
 7712: 	$r->print('
 7713: 	<p>
 7714: 	    '.&mt('The requested file name was invalid.').'
 7715:         </p>
 7716: ');
 7717: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7718: 	return;
 7719:     }
 7720:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7721:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7722:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7723:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7724:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7725:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7726:     $r->print('
 7727:     <p>
 7728: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7729: 	      '<a href="'.$orig.'">','</a>').'
 7730:     </p>
 7731:     <p>
 7732: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7733: 	      '<a href="'.$corrected.'">','</a>').'
 7734:     </p>
 7735:     <p>
 7736: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7737: 	      '<a href="'.$skipped.'">','</a>').'
 7738:     </p>
 7739: ');
 7740:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7741:     return '';
 7742: }
 7743: 
 7744: sub checkscantron_results {
 7745:     my ($r) = @_;
 7746:     my ($symb)=&get_symb($r);
 7747:     if (!$symb) {return '';}
 7748:     my $grading_menu_button=&show_grading_menu_form($symb);
 7749:     my $cid = $env{'request.course.id'};
 7750:     my %lettdig = &letter_to_digits();
 7751:     my $numletts = scalar(keys(%lettdig));
 7752:     my $cnum = $env{'course.'.$cid.'.num'};
 7753:     my $cdom = $env{'course.'.$cid.'.domain'};
 7754:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7755:     my %record;
 7756:     my %scantron_config =
 7757:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7758:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7759:     my $classlist=&Apache::loncoursedata::get_classlist();
 7760:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7761:     my $navmap=Apache::lonnavmaps::navmap->new();
 7762:     my $map=$navmap->getResourceByUrl($sequence);
 7763:     my @resources=$navmap->retrieveResources($map,undef,1,0);
 7764:     my ($uname,$udom,%partids_by_symb);
 7765:     foreach my $resource (@resources) {
 7766:         my $ressymb = $resource->symb();
 7767:         my ($analysis,$parts) =
 7768:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7769:         $partids_by_symb{$ressymb} = $parts;
 7770:     }
 7771:     my (%scandata,%lastname,%bylast);
 7772:     $r->print('
 7773: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7774: 
 7775:     my @delayqueue;
 7776:     my %completedstudents;
 7777: 
 7778:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7779:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7780:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7781:                                     'inline',undef,'checkscantron');
 7782:     my ($username,$domain,$started);
 7783: 
 7784:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7785: 
 7786:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7787:                                           'Processing first student');
 7788:     my $start=&Time::HiRes::time();
 7789:     my $i=-1;
 7790: 
 7791:     while ($i<$scanlines->{'count'}) {
 7792:         ($username,$domain,$uname)=('','','');
 7793:         $i++;
 7794:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7795:         if ($line=~/^[\s\cz]*$/) { next; }
 7796:         if ($started) {
 7797:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7798:                                                      'last student');
 7799:         }
 7800:         $started=1;
 7801:         my $scan_record=
 7802:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7803:                                                      $scan_data);
 7804:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7805:                                                               \%idmap,$i)) {
 7806:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7807:                                 'Unable to find a student that matches',1);
 7808:             next;
 7809:         }
 7810:         if (exists $completedstudents{$uname}) {
 7811:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7812:                                 'Student '.$uname.' has multiple sheets',2);
 7813:             next;
 7814:         }
 7815:         my $pid = $scan_record->{'scantron.ID'};
 7816:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7817:         push(@{$bylast{$lastname{$pid}}},$pid);
 7818:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7819:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7820:         chomp($scandata{$pid});
 7821:         $scandata{$pid} =~ s/\r$//;
 7822:         ($username,$domain)=split(/:/,$uname);
 7823:         my $counter = -1;
 7824:         foreach my $resource (@resources) {
 7825:             ($counter,my $recording) =
 7826:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 7827:                                          $scandata{$pid},\%partids_by_symb,
 7828:                                          \%scantron_config,\%lettdig,$numletts);
 7829:             $record{$pid} .= $recording;
 7830:         }
 7831:     }
 7832:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7833:     $r->print('<br />');
 7834:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 7835:     $passed = 0;
 7836:     $failed = 0;
 7837:     $numstudents = 0;
 7838:     foreach my $last (sort(keys(%bylast))) {
 7839:         if (ref($bylast{$last}) eq 'ARRAY') {
 7840:             foreach my $pid (sort(@{$bylast{$last}})) {
 7841:                 my $showscandata = $scandata{$pid};
 7842:                 my $showrecord = $record{$pid};
 7843:                 $showscandata =~ s/\s/&nbsp;/g;
 7844:                 $showrecord =~ s/\s/&nbsp;/g;
 7845:                 if ($scandata{$pid} eq $record{$pid}) {
 7846:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 7847:                     $okstudents .= '<tr class="'.$css_class.'">'.
 7848: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 7849: '</tr>'."\n".
 7850: '<tr class="'.$css_class.'">'."\n".
 7851: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 7852:                     $passed ++;
 7853:                 } else {
 7854:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 7855:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 7856: '</tr>'."\n".
 7857: '<tr class="'.$css_class.'">'."\n".
 7858: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 7859: '</tr>'."\n";
 7860:                     $failed ++;
 7861:                 }
 7862:                 $numstudents ++;
 7863:             }
 7864:         }
 7865:     }
 7866:     $r->print('<p>'.&mt('Comparison of scantron data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
 7867:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
 7868:     if ($passed) {
 7869:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 7870:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7871:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7872:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7873:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7874:                  $okstudents."\n".
 7875:                  &Apache::loncommon::end_data_table().'<br />');
 7876:     }
 7877:     if ($failed) {
 7878:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 7879:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7880:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7881:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7882:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7883:                  $badstudents."\n".
 7884:                  &Apache::loncommon::end_data_table()).'<br />'.
 7885:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
 7886:     }
 7887:     $r->print('</form><br />'.$grading_menu_button);
 7888:     return;
 7889: }
 7890: 
 7891: sub verify_scantron_grading {
 7892:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids_by_symb,
 7893:         $scantron_config,$lettdig,$numletts) = @_;
 7894:     my ($record,%expected,%startpos);
 7895:     return ($counter,$record) if (!ref($resource));
 7896:     return ($counter,$record) if (!$resource->is_problem());
 7897:     my $symb = $resource->symb();
 7898:     return ($counter,$record) if (ref($partids_by_symb) ne 'HASH');
 7899:     return ($counter,$record) if (ref($partids_by_symb->{$symb}) ne 'ARRAY');
 7900:     foreach my $part_id (@{$partids_by_symb->{$symb}}) {
 7901:         $counter ++;
 7902:         $expected{$part_id} = 0;
 7903:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 7904:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 7905:             foreach my $item (@sub_lines) {
 7906:                 $expected{$part_id} += $item;
 7907:             }
 7908:         } else {
 7909:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 7910:         }
 7911:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 7912:     }
 7913:     if ($symb) {
 7914:         my %recorded;
 7915:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 7916:         if ($returnhash{'version'}) {
 7917:             my %lasthash=();
 7918:             my $version;
 7919:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 7920:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 7921:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 7922:                 }
 7923:             }
 7924:             foreach my $key (keys(%lasthash)) {
 7925:                 if ($key =~ /\.scantron$/) {
 7926:                     my $value = &unescape($lasthash{$key});
 7927:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 7928:                     if ($value eq '') {
 7929:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 7930:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 7931:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 7932:                             }
 7933:                         }
 7934:                     } else {
 7935:                         my @tocheck;
 7936:                         my @items = split(//,$value);
 7937:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 7938:                             ($scantron_config->{'Qon'} eq 'number')) {
 7939:                             if (@items < $expected{$part_id}) {
 7940:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 7941:                                 my @singles = split(//,$fragment);
 7942:                                 foreach my $pos (@singles) {
 7943:                                     if ($pos eq ' ') {
 7944:                                         push(@tocheck,$pos);
 7945:                                     } else {
 7946:                                         my $next = shift(@items);
 7947:                                         push(@tocheck,$next);
 7948:                                     }
 7949:                                 }
 7950:                             } else {
 7951:                                 @tocheck = @items;
 7952:                             }
 7953:                             foreach my $letter (@tocheck) {
 7954:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 7955:                                     if ($letter !~ /^[A-J]$/) {
 7956:                                         $letter = $scantron_config->{'Qoff'};
 7957:                                     }
 7958:                                     $recorded{$part_id} .= $letter;
 7959:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 7960:                                     my $digit;
 7961:                                     if ($letter !~ /^[A-J]$/) {
 7962:                                         $digit = $scantron_config->{'Qoff'};
 7963:                                     } else {
 7964:                                         $digit = $lettdig->{$letter};
 7965:                                     }
 7966:                                     $recorded{$part_id} .= $digit;
 7967:                                 }
 7968:                             }
 7969:                         } else {
 7970:                             @tocheck = @items;
 7971:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 7972:                                 my $curr_sub = shift(@tocheck);
 7973:                                 my $digit;
 7974:                                 if ($curr_sub =~ /^[A-J]$/) {
 7975:                                     $digit = $lettdig->{$curr_sub}-1;
 7976:                                 }
 7977:                                 if ($curr_sub eq 'J') {
 7978:                                     $digit += scalar($numletts);
 7979:                                 }
 7980:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 7981:                                     if ($j == $digit) {
 7982:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 7983:                                     } else {
 7984:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 7985:                                     }
 7986:                                 }
 7987:                             }
 7988:                         }
 7989:                     }
 7990:                 }
 7991:             }
 7992:         }
 7993:         foreach my $part_id (@{$partids_by_symb->{$symb}}) {
 7994:             if ($recorded{$part_id} eq '') {
 7995:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 7996:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 7997:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 7998:                     }
 7999:                 }
 8000:             }
 8001:             $record .= $recorded{$part_id};
 8002:         }
 8003:     }
 8004:     return ($counter,$record);
 8005: }
 8006: 
 8007: sub letter_to_digits { 
 8008:     my %lettdig = (
 8009:                     A => 1,
 8010:                     B => 2,
 8011:                     C => 3,
 8012:                     D => 4,
 8013:                     E => 5,
 8014:                     F => 6,
 8015:                     G => 7,
 8016:                     H => 8,
 8017:                     I => 9,
 8018:                     J => 0,
 8019:                   );
 8020:     return %lettdig;
 8021: }
 8022: 
 8023: 
 8024: #-------- end of section for handling grading scantron forms -------
 8025: #
 8026: #-------------------------------------------------------------------
 8027: 
 8028: #-------------------------- Menu interface -------------------------
 8029: #
 8030: #--- Show a Grading Menu button - Calls the next routine ---
 8031: sub show_grading_menu_form {
 8032:     my ($symb)=@_;
 8033:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8034: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8035: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8036: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8037: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8038: 	'</form>'."\n";
 8039:     return $result;
 8040: }
 8041: 
 8042: # -- Retrieve choices for grading form
 8043: sub savedState {
 8044:     my %savedState = ();
 8045:     if ($env{'form.saveState'}) {
 8046: 	foreach (split(/:/,$env{'form.saveState'})) {
 8047: 	    my ($key,$value) = split(/=/,$_,2);
 8048: 	    $savedState{$key} = $value;
 8049: 	}
 8050:     }
 8051:     return \%savedState;
 8052: }
 8053: 
 8054: sub grading_menu {
 8055:     my ($request) = @_;
 8056:     my ($symb)=&get_symb($request);
 8057:     if (!$symb) {return '';}
 8058:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8059:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8060: 
 8061:     $request->print($table);
 8062:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8063:                   'handgrade'=>$hdgrade,
 8064:                   'probTitle'=>$probTitle,
 8065:                   'command'=>'submit_options',
 8066:                   'saveState'=>"",
 8067:                   'gradingMenu'=>1,
 8068:                   'showgrading'=>"yes");
 8069:     
 8070:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8071:     
 8072:     $fields{'command'} = 'csvform';
 8073:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8074:     
 8075:     $fields{'command'} = 'processclicker';
 8076:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8077:     
 8078:     $fields{'command'} = 'scantron_selectphase';
 8079:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8080:     
 8081:     my @menu = ({	categorytitle=>'Course Grading',
 8082:             items =>[
 8083:                         {	linktext => 'Manual Grading/View Submissions',
 8084:                     		url => $url1,
 8085:                     		permission => 'F',
 8086:                     		icon => 'edit-find-replace.png',
 8087:                     		linktitle => 'Start the process of hand grading submissions.'
 8088:                         },
 8089:                 	    {	linktext => 'Upload Scores',
 8090:                     		url => $url2,
 8091:                     		permission => 'F',
 8092:                     		icon => 'uploadscores.png',
 8093:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8094:                 	    },
 8095:                 	    {	linktext => 'Process Clicker',
 8096:                     		url => $url3,
 8097:                     		permission => 'F',
 8098:                     		icon => 'addClickerInfoFile.png',
 8099:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8100:                 	    },
 8101:                 	    {	linktext => 'Grade/Manage/Review Scantron Forms',
 8102:                     		url => $url4,
 8103:                     		permission => 'F',
 8104:                     		icon => 'stat.png',
 8105:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8106:                 	    }
 8107:                     ]
 8108:             });
 8109: 
 8110:     #$fields{'command'} = 'verify';
 8111:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8112:     #
 8113:     # Create the menu
 8114:     my $Str;
 8115:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8116:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8117:     $Str .= '<input type="hidden" name="command" value="" />'.
 8118:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8119: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8120: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8121: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8122: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8123: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8124: 
 8125:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8126:     #$menudata->{'jscript'}
 8127:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8128:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8129:         ' /> '.
 8130:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8131:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8132: 
 8133:     $Str .="</form>\n";
 8134:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8135:     $request->print(<<GRADINGMENUJS);
 8136: <script type="text/javascript" language="javascript">
 8137:     function checkChoice(formname,val,cmdx) {
 8138: 	if (val <= 2) {
 8139: 	    var cmd = radioSelection(formname.radioChoice);
 8140: 	    var cmdsave = cmd;
 8141: 	} else {
 8142: 	    cmd = cmdx;
 8143: 	    cmdsave = 'submission';
 8144: 	}
 8145: 	formname.command.value = cmd;
 8146: 	if (val < 5) formname.submit();
 8147: 	if (val == 5) {
 8148: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8149: 	        return false;
 8150: 	    } else {
 8151: 	        formname.submit();
 8152: 	    }
 8153: 	}
 8154:     }
 8155: 
 8156:     function checkReceiptNo(formname,nospace) {
 8157: 	var receiptNo = formname.receipt.value;
 8158: 	var checkOpt = false;
 8159: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8160: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8161: 	if (checkOpt) {
 8162: 	    alert("$receiptalert");
 8163: 	    formname.receipt.value = "";
 8164: 	    formname.receipt.focus();
 8165: 	    return false;
 8166: 	}
 8167: 	return true;
 8168:     }
 8169: </script>
 8170: GRADINGMENUJS
 8171:     &commonJSfunctions($request);
 8172:     return $Str;    
 8173: }
 8174: 
 8175: 
 8176: #--- Displays the submissions first page -------
 8177: sub submit_options {
 8178:     my ($request) = @_;
 8179:     my ($symb)=&get_symb($request);
 8180:     if (!$symb) {return '';}
 8181:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8182: 
 8183:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8184:     $request->print(<<GRADINGMENUJS);
 8185: <script type="text/javascript" language="javascript">
 8186:     function checkChoice(formname,val,cmdx) {
 8187: 	if (val <= 2) {
 8188: 	    var cmd = radioSelection(formname.radioChoice);
 8189: 	    var cmdsave = cmd;
 8190: 	} else {
 8191: 	    cmd = cmdx;
 8192: 	    cmdsave = 'submission';
 8193: 	}
 8194: 	formname.command.value = cmd;
 8195: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8196: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8197: 	if (val < 5) formname.submit();
 8198: 	if (val == 5) {
 8199: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8200: 	    formname.submit();
 8201: 	}
 8202: 	if (val < 7) formname.submit();
 8203:     }
 8204: 
 8205:     function checkReceiptNo(formname,nospace) {
 8206: 	var receiptNo = formname.receipt.value;
 8207: 	var checkOpt = false;
 8208: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8209: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8210: 	if (checkOpt) {
 8211: 	    alert("$receiptalert");
 8212: 	    formname.receipt.value = "";
 8213: 	    formname.receipt.focus();
 8214: 	    return false;
 8215: 	}
 8216: 	return true;
 8217:     }
 8218: </script>
 8219: GRADINGMENUJS
 8220:     &commonJSfunctions($request);
 8221:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8222:     my $result;
 8223:     my (undef,$sections) = &getclasslist('all','0');
 8224:     my $savedState = &savedState();
 8225:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8226:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8227:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8228:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8229: 
 8230:     # Preselect sections
 8231:     my $selsec="";
 8232:     if (ref($sections)) {
 8233:         foreach my $section (sort(@$sections)) {
 8234:             $selsec.='<option value="'.$section.'" '.
 8235:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8236:         }
 8237:     }
 8238: 
 8239:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8240: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8241: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8242: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8243: 	'<input type="hidden" name="command"     value="" />'."\n".
 8244: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8245: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8246: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8247: 
 8248:     $result.='
 8249: <h2>
 8250:   '.&mt('Grade Current Resource').'
 8251: </h2>
 8252: <div>
 8253:   '.$table.'
 8254: </div>
 8255: 
 8256: <div class="LC_columnSection">
 8257:   
 8258:     <fieldset>
 8259:       <legend>
 8260:        '.&mt('Sections').'
 8261:       </legend>
 8262:       <select name="section" multiple="multiple" size="5">'."\n";
 8263:     $result.= $selsec;
 8264:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8265:     $result.='
 8266:     </fieldset>
 8267:   
 8268:     <fieldset>
 8269:       <legend>
 8270:         '.&mt('Groups').'
 8271:       </legend>
 8272:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8273:     </fieldset>
 8274:   
 8275:     <fieldset>
 8276:       <legend>
 8277:         '.&mt('Access Status').'
 8278:       </legend>
 8279:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8280:     </fieldset>
 8281:   
 8282:     <fieldset>
 8283:       <legend>
 8284:         '.&mt('Submission Status').'
 8285:       </legend>
 8286:       <select name="submitonly" size="5">
 8287: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8288: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8289: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8290: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8291:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8292:       </select>
 8293:     </fieldset>
 8294:   
 8295: </div>
 8296: 
 8297: <br />
 8298:           <div>
 8299:             <div>
 8300:               <label>
 8301:                 <input type="radio" name="radioChoice" value="submission" '.
 8302:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8303:              &mt('Select individual students to grade and view submissions.').'
 8304: 	      </label> 
 8305:             </div>
 8306:             <div>
 8307: 	      <label>
 8308:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8309:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8310:                     &mt('Grade all selected students in a grading table.').'
 8311:               </label>
 8312:             </div>
 8313:             <div>
 8314: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8315:             </div>
 8316:           </div>
 8317: 
 8318: 
 8319:         <h2>
 8320:          '.&mt('Grade Complete Folder for One Student').'
 8321:         </h2>
 8322:         <div>
 8323:             <div>
 8324:               <label>
 8325:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8326: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8327:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8328:               </label>
 8329:             </div>
 8330:             <div>
 8331: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8332:             </div>
 8333:         </div>
 8334:   </form>';
 8335:     $result .= &show_grading_menu_form($symb);
 8336:     return $result;
 8337: }
 8338: 
 8339: sub reset_perm {
 8340:     undef(%perm);
 8341: }
 8342: 
 8343: sub init_perm {
 8344:     &reset_perm();
 8345:     foreach my $test_perm ('vgr','mgr','opa') {
 8346: 
 8347: 	my $scope = $env{'request.course.id'};
 8348: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8349: 
 8350: 	    $scope .= '/'.$env{'request.course.sec'};
 8351: 	    if ( $perm{$test_perm}=
 8352: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8353: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8354: 	    } else {
 8355: 		delete($perm{$test_perm});
 8356: 	    }
 8357: 	}
 8358:     }
 8359: }
 8360: 
 8361: sub gather_clicker_ids {
 8362:     my %clicker_ids;
 8363: 
 8364:     my $classlist = &Apache::loncoursedata::get_classlist();
 8365: 
 8366:     # Set up a couple variables.
 8367:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8368:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8369:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8370: 
 8371:     foreach my $student (keys(%$classlist)) {
 8372:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8373:         my $username = $classlist->{$student}->[$username_idx];
 8374:         my $domain   = $classlist->{$student}->[$domain_idx];
 8375:         my $clickers =
 8376: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8377:         foreach my $id (split(/\,/,$clickers)) {
 8378:             $id=~s/^[\#0]+//;
 8379:             $id=~s/[\-\:]//g;
 8380:             if (exists($clicker_ids{$id})) {
 8381: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8382:             } else {
 8383: 		$clicker_ids{$id}=$username.':'.$domain;
 8384:             }
 8385:         }
 8386:     }
 8387:     return %clicker_ids;
 8388: }
 8389: 
 8390: sub gather_adv_clicker_ids {
 8391:     my %clicker_ids;
 8392:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8393:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8394:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8395:     foreach my $element (sort(keys(%coursepersonnel))) {
 8396:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8397:             my ($puname,$pudom)=split(/\:/,$person);
 8398:             my $clickers =
 8399: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8400:             foreach my $id (split(/\,/,$clickers)) {
 8401: 		$id=~s/^[\#0]+//;
 8402:                 $id=~s/[\-\:]//g;
 8403: 		if (exists($clicker_ids{$id})) {
 8404: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8405: 		} else {
 8406: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8407: 		}
 8408:             }
 8409:         }
 8410:     }
 8411:     return %clicker_ids;
 8412: }
 8413: 
 8414: sub clicker_grading_parameters {
 8415:     return ('gradingmechanism' => 'scalar',
 8416:             'upfiletype' => 'scalar',
 8417:             'specificid' => 'scalar',
 8418:             'pcorrect' => 'scalar',
 8419:             'pincorrect' => 'scalar');
 8420: }
 8421: 
 8422: sub process_clicker {
 8423:     my ($r)=@_;
 8424:     my ($symb)=&get_symb($r);
 8425:     if (!$symb) {return '';}
 8426:     my $result=&checkforfile_js();
 8427:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8428:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8429:     $result.=$table;
 8430:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8431:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8432:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8433:         '</b></td></tr>'."\n";
 8434:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8435: # Attempt to restore parameters from last session, set defaults if not present
 8436:     my %Saveable_Parameters=&clicker_grading_parameters();
 8437:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8438:                                                  \%Saveable_Parameters);
 8439:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8440:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8441:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8442:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8443: 
 8444:     my %checked;
 8445:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8446:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8447:           $checked{$gradingmechanism}="checked='checked'";
 8448:        }
 8449:     }
 8450: 
 8451:     my $upload=&mt("Upload File");
 8452:     my $type=&mt("Type");
 8453:     my $attendance=&mt("Award points just for participation");
 8454:     my $personnel=&mt("Correctness determined from response by course personnel");
 8455:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8456:     my $given=&mt("Correctness determined from given list of answers").' '.
 8457:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8458:     my $pcorrect=&mt("Percentage points for correct solution");
 8459:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8460:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8461: 						   ('iclicker' => 'i>clicker',
 8462:                                                     'interwrite' => 'interwrite PRS'));
 8463:     $symb = &Apache::lonenc::check_encrypt($symb);
 8464:     $result.=<<ENDUPFORM;
 8465: <script type="text/javascript">
 8466: function sanitycheck() {
 8467: // Accept only integer percentages
 8468:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8469:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8470: // Find out grading choice
 8471:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8472:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8473:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8474:       }
 8475:    }
 8476: // By default, new choice equals user selection
 8477:    newgradingchoice=gradingchoice;
 8478: // Not good to give more points for false answers than correct ones
 8479:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8480:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8481:    }
 8482: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8483:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8484:       document.forms.gradesupload.pcorrect.value=100;
 8485:       document.forms.gradesupload.pincorrect.value=100;
 8486:    }
 8487: // If the values are different, cannot be attendance only
 8488:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8489:        (gradingchoice=='attendance')) {
 8490:        newgradingchoice='personnel';
 8491:    }
 8492: // Change grading choice to new one
 8493:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8494:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8495:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8496:       } else {
 8497:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8498:       }
 8499:    }
 8500: // Remember the old state
 8501:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8502: }
 8503: </script>
 8504: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8505: <input type="hidden" name="symb" value="$symb" />
 8506: <input type="hidden" name="command" value="processclickerfile" />
 8507: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8508: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8509: <input type="file" name="upfile" size="50" />
 8510: <br /><label>$type: $selectform</label>
 8511: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8512: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8513: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8514: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8515: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8516: <br />&nbsp;&nbsp;&nbsp;
 8517: <input type="text" name="givenanswer" size="50" />
 8518: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8519: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8520: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8521: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8522: </form>
 8523: ENDUPFORM
 8524:     $result.='</td></tr></table>'."\n".
 8525:              '</td></tr></table><br /><br />'."\n";
 8526:     $result.=&show_grading_menu_form($symb);
 8527:     return $result;
 8528: }
 8529: 
 8530: sub process_clicker_file {
 8531:     my ($r)=@_;
 8532:     my ($symb)=&get_symb($r);
 8533:     if (!$symb) {return '';}
 8534: 
 8535:     my %Saveable_Parameters=&clicker_grading_parameters();
 8536:     &Apache::loncommon::store_course_settings('grades_clicker',
 8537:                                               \%Saveable_Parameters);
 8538: 
 8539:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8540:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8541: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8542: 	return $result.&show_grading_menu_form($symb);
 8543:     }
 8544:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8545:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8546:         return $result.&show_grading_menu_form($symb);
 8547:     }
 8548:     my $foundgiven=0;
 8549:     if ($env{'form.gradingmechanism'} eq 'given') {
 8550:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8551:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8552:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8553:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8554:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8555:         $foundgiven=$#answers+1;
 8556:     }
 8557:     my %clicker_ids=&gather_clicker_ids();
 8558:     my %correct_ids;
 8559:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8560: 	%correct_ids=&gather_adv_clicker_ids();
 8561:     }
 8562:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8563: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8564: 	   $correct_id=~tr/a-z/A-Z/;
 8565: 	   $correct_id=~s/\s//gs;
 8566: 	   $correct_id=~s/^[\#0]+//;
 8567:            $correct_id=~s/[\-\:]//g;
 8568:            if ($correct_id) {
 8569: 	      $correct_ids{$correct_id}='specified';
 8570:            }
 8571:         }
 8572:     }
 8573:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8574: 	$result.=&mt('Score based on attendance only');
 8575:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8576:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8577:     } else {
 8578: 	my $number=0;
 8579: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8580: 	foreach my $id (sort(keys(%correct_ids))) {
 8581: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8582: 	    if ($correct_ids{$id} eq 'specified') {
 8583: 		$result.=&mt('specified');
 8584: 	    } else {
 8585: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8586: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8587: 	    }
 8588: 	    $number++;
 8589: 	}
 8590:         $result.="</p>\n";
 8591: 	if ($number==0) {
 8592: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8593: 	    return $result.&show_grading_menu_form($symb);
 8594: 	}
 8595:     }
 8596:     if (length($env{'form.upfile'}) < 2) {
 8597:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8598: 		     '<span class="LC_error">',
 8599: 		     '</span>',
 8600: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8601:         return $result.&show_grading_menu_form($symb);
 8602:     }
 8603: 
 8604: # Were able to get all the info needed, now analyze the file
 8605: 
 8606:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8607:     $symb = &Apache::lonenc::check_encrypt($symb);
 8608:     my $heading=&mt('Scanning clicker file');
 8609:     $result.=(<<ENDHEADER);
 8610: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8611: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8612: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8613: <form method="post" action="/adm/grades" name="clickeranalysis">
 8614: <input type="hidden" name="symb" value="$symb" />
 8615: <input type="hidden" name="command" value="assignclickergrades" />
 8616: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8617: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8618: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8619: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8620: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8621: ENDHEADER
 8622:     if ($env{'form.gradingmechanism'} eq 'given') {
 8623:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8624:     } 
 8625:     my %responses;
 8626:     my @questiontitles;
 8627:     my $errormsg='';
 8628:     my $number=0;
 8629:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8630: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8631:     }
 8632:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8633:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8634:     }
 8635:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8636:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8637:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8638:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8639:              '<br />';
 8640:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8641:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8642:        return $result.&show_grading_menu_form($symb);
 8643:     } 
 8644: # Remember Question Titles
 8645: # FIXME: Possibly need delimiter other than ":"
 8646:     for (my $i=0;$i<$number;$i++) {
 8647:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8648:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8649:     }
 8650:     my $correct_count=0;
 8651:     my $student_count=0;
 8652:     my $unknown_count=0;
 8653: # Match answers with usernames
 8654: # FIXME: Possibly need delimiter other than ":"
 8655:     foreach my $id (keys(%responses)) {
 8656:        if ($correct_ids{$id}) {
 8657:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8658:           $correct_count++;
 8659:        } elsif ($clicker_ids{$id}) {
 8660:           if ($clicker_ids{$id}=~/\,/) {
 8661: # More than one user with the same clicker!
 8662:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8663:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8664:                            "<select name='multi".$id."'>";
 8665:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8666:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8667:              }
 8668:              $result.='</select>';
 8669:              $unknown_count++;
 8670:           } else {
 8671: # Good: found one and only one user with the right clicker
 8672:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8673:              $student_count++;
 8674:           }
 8675:        } else {
 8676:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8677:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8678:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8679:                    "\n".&mt("Domain").": ".
 8680:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8681:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8682:           $unknown_count++;
 8683:        }
 8684:     }
 8685:     $result.='<hr />'.
 8686:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8687:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8688:        if ($correct_count==0) {
 8689:           $errormsg.="Found no correct answers answers for grading!";
 8690:        } elsif ($correct_count>1) {
 8691:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8692:        }
 8693:     }
 8694:     if ($number<1) {
 8695:        $errormsg.="Found no questions.";
 8696:     }
 8697:     if ($errormsg) {
 8698:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8699:     } else {
 8700:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8701:     }
 8702:     $result.='</form></td></tr></table>'."\n".
 8703:              '</td></tr></table><br /><br />'."\n";
 8704:     return $result.&show_grading_menu_form($symb);
 8705: }
 8706: 
 8707: sub iclicker_eval {
 8708:     my ($questiontitles,$responses)=@_;
 8709:     my $number=0;
 8710:     my $errormsg='';
 8711:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8712:         my %components=&Apache::loncommon::record_sep($line);
 8713:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8714: 	if ($entries[0] eq 'Question') {
 8715: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8716: 		$$questiontitles[$number]=$entries[$i];
 8717: 		$number++;
 8718: 	    }
 8719: 	}
 8720: 	if ($entries[0]=~/^\#/) {
 8721: 	    my $id=$entries[0];
 8722: 	    my @idresponses;
 8723: 	    $id=~s/^[\#0]+//;
 8724: 	    for (my $i=0;$i<$number;$i++) {
 8725: 		my $idx=3+$i*6;
 8726: 		push(@idresponses,$entries[$idx]);
 8727: 	    }
 8728: 	    $$responses{$id}=join(',',@idresponses);
 8729: 	}
 8730:     }
 8731:     return ($errormsg,$number);
 8732: }
 8733: 
 8734: sub interwrite_eval {
 8735:     my ($questiontitles,$responses)=@_;
 8736:     my $number=0;
 8737:     my $errormsg='';
 8738:     my $skipline=1;
 8739:     my $questionnumber=0;
 8740:     my %idresponses=();
 8741:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8742:         my %components=&Apache::loncommon::record_sep($line);
 8743:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8744:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8745:         if ($entries[1] eq 'Response') { $skipline=1; }
 8746:         next if $skipline;
 8747:         if ($entries[0]!=$questionnumber) {
 8748:            $questionnumber=$entries[0];
 8749:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8750:            $number++;
 8751:         }
 8752:         my $id=$entries[4];
 8753:         $id=~s/^[\#0]+//;
 8754:         $id=~s/^v\d*\://i;
 8755:         $id=~s/[\-\:]//g;
 8756:         $idresponses{$id}[$number]=$entries[6];
 8757:     }
 8758:     foreach my $id (keys(%idresponses)) {
 8759:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8760:        $$responses{$id}=~s/^\s*\,//;
 8761:     }
 8762:     return ($errormsg,$number);
 8763: }
 8764: 
 8765: sub assign_clicker_grades {
 8766:     my ($r)=@_;
 8767:     my ($symb)=&get_symb($r);
 8768:     if (!$symb) {return '';}
 8769: # See which part we are saving to
 8770:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8771: # FIXME: This should probably look for the first handgradeable part
 8772:     my $part=$$partlist[0];
 8773: # Start screen output
 8774:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8775: 
 8776:     my $heading=&mt('Assigning grades based on clicker file');
 8777:     $result.=(<<ENDHEADER);
 8778: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8779: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8780: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8781: ENDHEADER
 8782: # Get correct result
 8783: # FIXME: Possibly need delimiter other than ":"
 8784:     my @correct=();
 8785:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8786:     my $number=$env{'form.number'};
 8787:     if ($gradingmechanism ne 'attendance') {
 8788:        foreach my $key (keys(%env)) {
 8789:           if ($key=~/^form\.correct\:/) {
 8790:              my @input=split(/\,/,$env{$key});
 8791:              for (my $i=0;$i<=$#input;$i++) {
 8792:                  if (($correct[$i]) && ($input[$i]) &&
 8793:                      ($correct[$i] ne $input[$i])) {
 8794:                     $result.='<br /><span class="LC_warning">'.
 8795:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8796:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8797:                  } elsif ($input[$i]) {
 8798:                     $correct[$i]=$input[$i];
 8799:                  }
 8800:              }
 8801:           }
 8802:        }
 8803:        for (my $i=0;$i<$number;$i++) {
 8804:           if (!$correct[$i]) {
 8805:              $result.='<br /><span class="LC_error">'.
 8806:                       &mt('No correct result given for question "[_1]"!',
 8807:                           $env{'form.question:'.$i}).'</span>';
 8808:           }
 8809:        }
 8810:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8811:     }
 8812: # Start grading
 8813:     my $pcorrect=$env{'form.pcorrect'};
 8814:     my $pincorrect=$env{'form.pincorrect'};
 8815:     my $storecount=0;
 8816:     foreach my $key (keys(%env)) {
 8817:        my $user='';
 8818:        if ($key=~/^form\.student\:(.*)$/) {
 8819:           $user=$1;
 8820:        }
 8821:        if ($key=~/^form\.unknown\:(.*)$/) {
 8822:           my $id=$1;
 8823:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8824:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8825:           } elsif ($env{'form.multi'.$id}) {
 8826:              $user=$env{'form.multi'.$id};
 8827:           }
 8828:        }
 8829:        if ($user) { 
 8830:           my @answer=split(/\,/,$env{$key});
 8831:           my $sum=0;
 8832:           my $realnumber=$number;
 8833:           for (my $i=0;$i<$number;$i++) {
 8834:              if ($answer[$i]) {
 8835:                 if ($gradingmechanism eq 'attendance') {
 8836:                    $sum+=$pcorrect;
 8837:                 } elsif ($answer[$i] eq '*') {
 8838:                    $sum+=$pcorrect;
 8839:                 } elsif ($answer[$i] eq '-') {
 8840:                    $realnumber--;
 8841:                 } else {
 8842:                    if ($answer[$i] eq $correct[$i]) {
 8843:                       $sum+=$pcorrect;
 8844:                    } else {
 8845:                       $sum+=$pincorrect;
 8846:                    }
 8847:                 }
 8848:              }
 8849:           }
 8850:           my $ave=$sum/(100*$realnumber);
 8851: # Store
 8852:           my ($username,$domain)=split(/\:/,$user);
 8853:           my %grades=();
 8854:           $grades{"resource.$part.solved"}='correct_by_override';
 8855:           $grades{"resource.$part.awarded"}=$ave;
 8856:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8857:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8858:                                                  $env{'request.course.id'},
 8859:                                                  $domain,$username);
 8860:           if ($returncode ne 'ok') {
 8861:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8862:           } else {
 8863:              $storecount++;
 8864:           }
 8865:        }
 8866:     }
 8867: # We are done
 8868:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 8869:              '</td></tr></table>'."\n".
 8870:              '</td></tr></table><br /><br />'."\n";
 8871:     return $result.&show_grading_menu_form($symb);
 8872: }
 8873: 
 8874: sub handler {
 8875:     my $request=$_[0];
 8876:     &reset_caches();
 8877:     if ($env{'browser.mathml'}) {
 8878: 	&Apache::loncommon::content_type($request,'text/xml');
 8879:     } else {
 8880: 	&Apache::loncommon::content_type($request,'text/html');
 8881:     }
 8882:     $request->send_http_header;
 8883:     return '' if $request->header_only;
 8884:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8885:     my $symb=&get_symb($request,1);
 8886:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8887:     my $command=$commands[0];
 8888: 
 8889:     if ($#commands > 0) {
 8890: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8891:     }
 8892: 
 8893:     $ssi_error = 0;
 8894:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 8895:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 8896:                                           {'bread_crumbs' => $brcrum}));
 8897:     if ($symb eq '' && $command eq '') {
 8898: 	if ($env{'user.adv'}) {
 8899: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8900: 		($env{'form.codethree'})) {
 8901: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8902: 		    $env{'form.codethree'};
 8903: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8904: 		    &Apache::lonnet::checkin($token);
 8905: 		if ($tsymb) {
 8906: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8907: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8908: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 8909: 					  ('grade_username' => $tuname,
 8910: 					   'grade_domain' => $tudom,
 8911: 					   'grade_courseid' => $tcrsid,
 8912: 					   'grade_symb' => $tsymb)));
 8913: 		    } else {
 8914: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8915: 		    }
 8916: 		} else {
 8917: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8918: 		}
 8919: 	    } else {
 8920: 		$request->print(&Apache::lonxml::tokeninputfield());
 8921: 	    }
 8922: 	}
 8923:     } else {
 8924: 	&init_perm();
 8925: 	if ($command eq 'submission' && $perm{'vgr'}) {
 8926: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 8927: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 8928: 	    &pickStudentPage($request);
 8929: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 8930: 	    &displayPage($request);
 8931: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 8932: 	    &updateGradeByPage($request);
 8933: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 8934: 	    &processGroup($request);
 8935: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 8936: 	    $request->print(&grading_menu($request));
 8937: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 8938: 	    $request->print(&submit_options($request));
 8939: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 8940: 	    $request->print(&viewgrades($request));
 8941: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 8942: 	    $request->print(&processHandGrade($request));
 8943: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 8944: 	    $request->print(&editgrades($request));
 8945: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 8946: 	    $request->print(&verifyreceipt($request));
 8947:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 8948:             $request->print(&process_clicker($request));
 8949:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 8950:             $request->print(&process_clicker_file($request));
 8951:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 8952:             $request->print(&assign_clicker_grades($request));
 8953: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 8954: 	    $request->print(&upcsvScores_form($request));
 8955: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 8956: 	    $request->print(&csvupload($request));
 8957: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 8958: 	    $request->print(&csvuploadmap($request));
 8959: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 8960: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 8961: 		$request->print(&csvuploadoptions($request));
 8962: 	    } else {
 8963: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 8964: 		    $env{'form.upfile_associate'} = 'reverse';
 8965: 		} else {
 8966: 		    $env{'form.upfile_associate'} = 'forward';
 8967: 		}
 8968: 		$request->print(&csvuploadmap($request));
 8969: 	    }
 8970: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 8971: 	    $request->print(&csvuploadassign($request));
 8972: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 8973: 	    $request->print(&scantron_selectphase($request));
 8974:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 8975:  	    $request->print(&scantron_do_warning($request));
 8976: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 8977: 	    $request->print(&scantron_validate_file($request));
 8978: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 8979: 	    $request->print(&scantron_process_students($request));
 8980:  	} elsif ($command eq 'scantronupload' && 
 8981:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8982: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8983:  	    $request->print(&scantron_upload_scantron_data($request)); 
 8984:  	} elsif ($command eq 'scantronupload_save' &&
 8985:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8986: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8987:  	    $request->print(&scantron_upload_scantron_data_save($request));
 8988:  	} elsif ($command eq 'scantron_download' &&
 8989: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 8990:  	    $request->print(&scantron_download_scantron_data($request));
 8991:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 8992:             $request->print(&checkscantron_results($request));     
 8993: 	} elsif ($command) {
 8994: 	    $request->print("Access Denied ($command)");
 8995: 	}
 8996:     }
 8997:     if ($ssi_error) {
 8998: 	&ssi_print_error($request);
 8999:     }
 9000:     $request->print(&Apache::loncommon::end_page());
 9001:     &reset_caches();
 9002:     return '';
 9003: }
 9004: 
 9005: 1;
 9006: 
 9007: __END__;
 9008: 
 9009: 
 9010: =head1 NAME
 9011: 
 9012: Apache::grades
 9013: 
 9014: =head1 SYNOPSIS
 9015: 
 9016: Handles the viewing of grades.
 9017: 
 9018: This is part of the LearningOnline Network with CAPA project
 9019: described at http://www.lon-capa.org.
 9020: 
 9021: =head1 OVERVIEW
 9022: 
 9023: Do an ssi with retries:
 9024: While I'd love to factor out this with the vesrion in lonprintout,
 9025: that would either require a data coupling between modules, which I refuse to perpetuate (there's quite enough of that already), or would require the invention of another infrastructure
 9026: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9027: 
 9028: At least the logic that drives this has been pulled out into loncommon.
 9029: 
 9030: 
 9031: 
 9032: ssi_with_retries - Does the server side include of a resource.
 9033:                      if the ssi call returns an error we'll retry it up to
 9034:                      the number of times requested by the caller.
 9035:                      If we still have a proble, no text is appended to the
 9036:                      output and we set some global variables.
 9037:                      to indicate to the caller an SSI error occurred.  
 9038:                      All of this is supposed to deal with the issues described
 9039:                      in LonCAPA BZ 5631 see:
 9040:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9041:                      by informing the user that this happened.
 9042: 
 9043: Parameters:
 9044:   resource   - The resource to include.  This is passed directly, without
 9045:                interpretation to lonnet::ssi.
 9046:   form       - The form hash parameters that guide the interpretation of the resource
 9047:                
 9048:   retries    - Number of retries allowed before giving up completely.
 9049: Returns:
 9050:   On success, returns the rendered resource identified by the resource parameter.
 9051: Side Effects:
 9052:   The following global variables can be set:
 9053:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9054:                               It is up to the caller to initialize this to false
 9055:                               if desired.
 9056:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9057:                               of the resource that could not be rendered by the ssi
 9058:                               call.
 9059:    ssi_error_message   - The error string fetched from the ssi response
 9060:                               in the event of an error.
 9061: 
 9062: 
 9063: =head1 HANDLER SUBROUTINE
 9064: 
 9065: ssi_with_retries()
 9066: 
 9067: =head1 SUBROUTINES
 9068: 
 9069: =over
 9070: 
 9071: =item scantron_get_correction() : 
 9072: 
 9073:    Builds the interface screen to interact with the operator to fix a
 9074:    specific error condition in a specific scanline
 9075: 
 9076:  Arguments:
 9077:     $r           - Apache request object
 9078:     $i           - number of the current scanline
 9079:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9080:     $scan_config - hash ref as returned from &get_scantron_config()
 9081:     $line        - full contents of the current scanline
 9082:     $error       - error condition, valid values are
 9083:                    'incorrectCODE', 'duplicateCODE',
 9084:                    'doublebubble', 'missingbubble',
 9085:                    'duplicateID', 'incorrectID'
 9086:     $arg         - extra information needed
 9087:        For errors:
 9088:          - duplicateID   - paper number that this studentID was seen before on
 9089:          - duplicateCODE - array ref of the paper numbers this CODE was
 9090:                            seen on before
 9091:          - incorrectCODE - current incorrect CODE 
 9092:          - doublebubble  - array ref of the bubble lines that have double
 9093:                            bubble errors
 9094:          - missingbubble - array ref of the bubble lines that have missing
 9095:                            bubble errors
 9096: 
 9097: =item  scantron_get_maxbubble() : 
 9098: 
 9099:    Returns the maximum number of bubble lines that are expected to
 9100:    occur. Does this by walking the selected sequence rendering the
 9101:    resource and then checking &Apache::lonxml::get_problem_counter()
 9102:    for what the current value of the problem counter is.
 9103: 
 9104:    Caches the results to $env{'form.scantron_maxbubble'},
 9105:    $env{'form.scantron.bubble_lines.n'}, 
 9106:    $env{'form.scantron.first_bubble_line.n'} and
 9107:    $env{"form.scantron.sub_bubblelines.n"}
 9108:    which are the total number of bubble, lines, the number of bubble
 9109:    lines for response n and number of the first bubble line for response n,
 9110:    and a comma separated list of numbers of bubble lines for sub-questions
 9111:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9112: 
 9113: 
 9114: =item  scantron_validate_missingbubbles() : 
 9115: 
 9116:    Validates all scanlines in the selected file to not have any
 9117:     answers that don't have bubbles that have not been verified
 9118:     to be bubble free.
 9119: 
 9120: =item  scantron_process_students() : 
 9121: 
 9122:    Routine that does the actual grading of the bubble sheet information.
 9123: 
 9124:    The parsed scanline hash is added to %env 
 9125: 
 9126:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9127:    foreach resource , with the form data of
 9128: 
 9129: 	'submitted'     =>'scantron' 
 9130: 	'grade_target'  =>'grade',
 9131: 	'grade_username'=> username of student
 9132: 	'grade_domain'  => domain of student
 9133: 	'grade_courseid'=> of course
 9134: 	'grade_symb'    => symb of resource to grade
 9135: 
 9136:     This triggers a grading pass. The problem grading code takes care
 9137:     of converting the bubbled letter information (now in %env) into a
 9138:     valid submission.
 9139: 
 9140: =item  scantron_upload_scantron_data() :
 9141: 
 9142:     Creates the screen for adding a new bubble sheet data file to a course.
 9143: 
 9144: =item  scantron_upload_scantron_data_save() : 
 9145: 
 9146:    Adds a provided bubble information data file to the course if user
 9147:    has the correct privileges to do so. 
 9148: 
 9149: =item  valid_file() :
 9150: 
 9151:    Validates that the requested bubble data file exists in the course.
 9152: 
 9153: =item  scantron_download_scantron_data() : 
 9154: 
 9155:    Shows a list of the three internal files (original, corrected,
 9156:    skipped) for a specific bubble sheet data file that exists in the
 9157:    course.
 9158: 
 9159: =item  scantron_validate_ID() : 
 9160: 
 9161:    Validates all scanlines in the selected file to not have any
 9162:    invalid or underspecified student IDs
 9163: 
 9164: =back
 9165: 
 9166: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>
500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.