File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.593: download - view: text, annotated - select for diffs
Mon Feb 8 01:09:36 2010 UTC (14 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_9_99_0, HEAD
- Prevent ISE.
 Can be triggered if a user has multiple tabs open switched course,
 then tries to view grading screen in originally selected course.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.593 2010/02/08 01:09:36 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,$errorref) = @_;
  101: 
  102:     my $navmap   = Apache::lonnavmaps::navmap->new();
  103:     unless (ref($navmap)) {
  104:         if (ref($errorref)) { 
  105:             $$errorref = 'navmap';
  106:             return;
  107:         }
  108:     }
  109:     my $res      = $navmap->getBySymb($symb);
  110:     my $partlist = $res->parts();
  111:     my $url      = $res->src();
  112:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  113: 
  114:     my @stores;
  115:     foreach my $part (@{ $partlist }) {
  116: 	foreach my $key (@metakeys) {
  117: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  118: 	}
  119:     }
  120:     return @stores;
  121: }
  122: 
  123: # --- Get the symbolic name of a problem and the url
  124: sub get_symb {
  125:     my ($request,$silent) = @_;
  126:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  127:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  128:     if ($symb eq '') { 
  129: 	if (!$silent) {
  130: 	    $request->print("Unable to handle ambiguous references:$url:.");
  131: 	    return ();
  132: 	}
  133:     }
  134:     &Apache::lonenc::check_decrypt(\$symb);
  135:     return ($symb);
  136: }
  137: 
  138: #--- Format fullname, username:domain if different for display
  139: #--- Use anywhere where the student names are listed
  140: sub nameUserString {
  141:     my ($type,$fullname,$uname,$udom) = @_;
  142:     if ($type eq 'header') {
  143: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  144:     } else {
  145: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  146: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  147:     }
  148: }
  149: 
  150: #--- Get the partlist and the response type for a given problem. ---
  151: #--- Indicate if a response type is coded handgraded or not. ---
  152: sub response_type {
  153:     my ($symb,$response_error) = @_;
  154: 
  155:     my $navmap = Apache::lonnavmaps::navmap->new();
  156:     unless (ref($navmap)) {
  157:         if (ref($response_error)) {
  158:             $$response_error = 1;
  159:         }
  160:         return;
  161:     }
  162:     my $res = $navmap->getBySymb($symb);
  163:     unless (ref($res)) {
  164:         $$response_error = 1;
  165:         return;
  166:     }
  167:     my $partlist = $res->parts();
  168:     my %vPart = 
  169: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  170:     my (%response_types,%handgrade);
  171:     foreach my $part (@{ $partlist }) {
  172: 	next if (%vPart && !exists($vPart{$part}));
  173: 
  174: 	my @types = $res->responseType($part);
  175: 	my @ids = $res->responseIds($part);
  176: 	for (my $i=0; $i < scalar(@ids); $i++) {
  177: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  178: 	    $handgrade{$part.'_'.$ids[$i]} = 
  179: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  180: 				     '.handgrade',$symb);
  181: 	}
  182:     }
  183:     return ($partlist,\%handgrade,\%response_types);
  184: }
  185: 
  186: sub flatten_responseType {
  187:     my ($responseType) = @_;
  188:     my @part_response_id =
  189: 	map { 
  190: 	    my $part = $_;
  191: 	    map {
  192: 		[$part,$_]
  193: 		} sort(keys(%{ $responseType->{$part} }));
  194: 	} sort(keys(%$responseType));
  195:     return @part_response_id;
  196: }
  197: 
  198: sub get_display_part {
  199:     my ($partID,$symb)=@_;
  200:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  201:     if (defined($display) and $display ne '') {
  202:         $display.= ' (<span class="LC_internal_info">'
  203:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  204:     } else {
  205: 	$display=$partID;
  206:     }
  207:     return $display;
  208: }
  209: 
  210: #--- Show resource title
  211: #--- and parts and response type
  212: sub showResourceInfo {
  213:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  214:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  215:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  216:     if (ref($res_error)) {
  217:         if ($$res_error) {
  218:             return;
  219:         }
  220:     }
  221:     $result.=&Apache::loncommon::start_data_table()
  222:             .&Apache::loncommon::start_data_table_header_row();
  223:     if ($checkboxes) {
  224:         $result.='<th>&nbsp;</th>';
  225:     }
  226:     $result.='<th>'.&mt('Problem Part').'</th>'
  227:             .'<th>'.&mt('Res. ID').'</th>'
  228:             .'<th>'.&mt('Type').'</th>'
  229:             .&Apache::loncommon::end_data_table_header_row();
  230:     my %resptype = ();
  231:     my $hdgrade='no';
  232:     my %partsseen;
  233:     foreach my $partID (sort(keys(%$responseType))) {
  234:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  235:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  236:             my $responsetype = $responseType->{$partID}->{$resID};
  237:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  238:             $result.=&Apache::loncommon::start_data_table_row();
  239:             if ($checkboxes) {
  240:                 if (exists($partsseen{$partID})) {
  241:                     $result.="<td>&nbsp;</td>";
  242:                 } else {
  243:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  244:                 }
  245:                 $partsseen{$partID}=1;
  246:             }
  247:             my $display_part=&get_display_part($partID,$symb);
  248:             $result.='<td>'.$display_part.'</td>'
  249:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  250:                     .'<td>'.&mt($responsetype).'</td>'
  251: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
  252:                     .&Apache::loncommon::end_data_table_row();
  253:         }
  254:     }
  255:     $result.=&Apache::loncommon::end_data_table();
  256:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  257: }
  258: 
  259: sub reset_caches {
  260:     &reset_analyze_cache();
  261:     &reset_perm();
  262: }
  263: 
  264: {
  265:     my %analyze_cache;
  266:     my %analyze_cache_formkeys;
  267: 
  268:     sub reset_analyze_cache {
  269: 	undef(%analyze_cache);
  270:         undef(%analyze_cache_formkeys);
  271:     }
  272: 
  273:     sub get_analyze {
  274: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  275: 	my $key = "$symb\0$uname\0$udom";
  276: 	if (exists($analyze_cache{$key})) {
  277:             my $getupdate = 0;
  278:             if (ref($add_to_hash) eq 'HASH') {
  279:                 foreach my $item (keys(%{$add_to_hash})) {
  280:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  281:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  282:                             $getupdate = 1;
  283:                             last;
  284:                         }
  285:                     } else {
  286:                         $getupdate = 1;
  287:                     }
  288:                 }
  289:             }
  290:             if (!$getupdate) {
  291:                 return $analyze_cache{$key};
  292:             }
  293:         }
  294: 
  295: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  296: 	$url=&Apache::lonnet::clutter($url);
  297:         my %form = ('grade_target'      => 'analyze',
  298:                     'grade_domain'      => $udom,
  299:                     'grade_symb'        => $symb,
  300:                     'grade_courseid'    =>  $env{'request.course.id'},
  301:                     'grade_username'    => $uname,
  302:                     'grade_noincrement' => $no_increment);
  303:         if (ref($add_to_hash)) {
  304:             %form = (%form,%{$add_to_hash});
  305:         } 
  306: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  307: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  308: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  309:         if (ref($add_to_hash) eq 'HASH') {
  310:             $analyze_cache_formkeys{$key} = $add_to_hash;
  311:         } else {
  312:             $analyze_cache_formkeys{$key} = {};
  313:         }
  314: 	return $analyze_cache{$key} = \%analyze;
  315:     }
  316: 
  317:     sub get_order {
  318: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  319: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  320: 	return $analyze->{"$partid.$respid.shown"};
  321:     }
  322: 
  323:     sub get_radiobutton_correct_foil {
  324: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  325: 	my $analyze = &get_analyze($symb,$uname,$udom);
  326:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  327:         if (ref($foils) eq 'ARRAY') {
  328: 	    foreach my $foil (@{$foils}) {
  329: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  330: 		    return $foil;
  331: 	        }
  332: 	    }
  333: 	}
  334:     }
  335: 
  336:     sub scantron_partids_tograde {
  337:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  338:         my (%analysis,@parts);
  339:         if (ref($resource)) {
  340:             my $symb = $resource->symb();
  341:             my $add_to_form;
  342:             if ($check_for_randomlist) {
  343:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  344:             }
  345:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  346:             if (ref($analyze) eq 'HASH') {
  347:                 %analysis = %{$analyze};
  348:             }
  349:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  350:                 foreach my $part (@{$analysis{'parts'}}) {
  351:                     my ($id,$respid) = split(/\./,$part);
  352:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  353:                         push(@parts,$part);
  354:                     }
  355:                 }
  356:             }
  357:         }
  358:         return (\%analysis,\@parts);
  359:     }
  360: 
  361: }
  362: 
  363: #--- Clean response type for display
  364: #--- Currently filters option/rank/radiobutton/match/essay/Task
  365: #        response types only.
  366: sub cleanRecord {
  367:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  368: 	$uname,$udom) = @_;
  369:     my $grayFont = '<span class="LC_internal_info">';
  370:     if ($response =~ /^(option|rank)$/) {
  371: 	my %answer=&Apache::lonnet::str2hash($answer);
  372: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  373: 	my ($toprow,$bottomrow);
  374: 	foreach my $foil (@$order) {
  375: 	    if ($grading{$foil} == 1) {
  376: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  377: 	    } else {
  378: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  379: 	    }
  380: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  381: 	}
  382: 	return '<blockquote><table border="1">'.
  383: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  384: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  385: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  386:     } elsif ($response eq 'match') {
  387: 	my %answer=&Apache::lonnet::str2hash($answer);
  388: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  389: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  390: 	my ($toprow,$middlerow,$bottomrow);
  391: 	foreach my $foil (@$order) {
  392: 	    my $item=shift(@items);
  393: 	    if ($grading{$foil} == 1) {
  394: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  395: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  396: 	    } else {
  397: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  398: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  399: 	    }
  400: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  401: 	}
  402: 	return '<blockquote><table border="1">'.
  403: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  404: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  405: 	    $middlerow.'</tr>'.
  406: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  407: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  408:     } elsif ($response eq 'radiobutton') {
  409: 	my %answer=&Apache::lonnet::str2hash($answer);
  410: 	my ($toprow,$bottomrow);
  411: 	my $correct = 
  412: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  413: 	foreach my $foil (@$order) {
  414: 	    if (exists($answer{$foil})) {
  415: 		if ($foil eq $correct) {
  416: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  417: 		} else {
  418: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  419: 		}
  420: 	    } else {
  421: 		$toprow.='<td>'.&mt('false').'</td>';
  422: 	    }
  423: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  424: 	}
  425: 	return '<blockquote><table border="1">'.
  426: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  427: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  428: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  429:     } elsif ($response eq 'essay') {
  430: 	if (! exists ($env{'form.'.$symb})) {
  431: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  432: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  433: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  434: 
  435: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  436: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  437: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  438: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  439: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  440: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  441: 	}
  442: 	$answer =~ s-\n-<br />-g;
  443: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  444:     } elsif ( $response eq 'organic') {
  445: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  446: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  447: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  448: 	return $result;
  449:     } elsif ( $response eq 'Task') {
  450: 	if ( $answer eq 'SUBMITTED') {
  451: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  452: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  453: 	    return $result;
  454: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  455: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  456: 			       keys(%{$record}));
  457: 	    return join('<br />',($version,@matches));
  458: 			       
  459: 			       
  460: 	} else {
  461: 	    my $result =
  462: 		'<p>'
  463: 		.&mt('Overall result: [_1]',
  464: 		     $record->{$version."resource.$respid.$partid.status"})
  465: 		.'</p>';
  466: 	    
  467: 	    $result .= '<ul>';
  468: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  469: 			     keys(%{$record}));
  470: 	    foreach my $grade (sort(@grade)) {
  471: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  472: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  473: 				     $dim, $record->{$grade}).
  474: 			  '</li>';
  475: 	    }
  476: 	    $result.='</ul>';
  477: 	    return $result;
  478: 	}
  479:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  480: 	$answer = 
  481: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  482: 							      $answer);
  483:     }
  484:     return $answer;
  485: }
  486: 
  487: #-- A couple of common js functions
  488: sub commonJSfunctions {
  489:     my $request = shift;
  490:     $request->print(<<COMMONJSFUNCTIONS);
  491: <script type="text/javascript" language="javascript">
  492:     function radioSelection(radioButton) {
  493: 	var selection=null;
  494: 	if (radioButton.length > 1) {
  495: 	    for (var i=0; i<radioButton.length; i++) {
  496: 		if (radioButton[i].checked) {
  497: 		    return radioButton[i].value;
  498: 		}
  499: 	    }
  500: 	} else {
  501: 	    if (radioButton.checked) return radioButton.value;
  502: 	}
  503: 	return selection;
  504:     }
  505: 
  506:     function pullDownSelection(selectOne) {
  507: 	var selection="";
  508: 	if (selectOne.length > 1) {
  509: 	    for (var i=0; i<selectOne.length; i++) {
  510: 		if (selectOne[i].selected) {
  511: 		    return selectOne[i].value;
  512: 		}
  513: 	    }
  514: 	} else {
  515:             // only one value it must be the selected one
  516: 	    return selectOne.value;
  517: 	}
  518:     }
  519: </script>
  520: COMMONJSFUNCTIONS
  521: }
  522: 
  523: #--- Dumps the class list with usernames,list of sections,
  524: #--- section, ids and fullnames for each user.
  525: sub getclasslist {
  526:     my ($getsec,$filterlist,$getgroup) = @_;
  527:     my @getsec;
  528:     my @getgroup;
  529:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  530:     if (!ref($getsec)) {
  531: 	if ($getsec ne '' && $getsec ne 'all') {
  532: 	    @getsec=($getsec);
  533: 	}
  534:     } else {
  535: 	@getsec=@{$getsec};
  536:     }
  537:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  538:     if (!ref($getgroup)) {
  539: 	if ($getgroup ne '' && $getgroup ne 'all') {
  540: 	    @getgroup=($getgroup);
  541: 	}
  542:     } else {
  543: 	@getgroup=@{$getgroup};
  544:     }
  545:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  546: 
  547:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  548:     # Bail out if we were unable to get the classlist
  549:     return if (! defined($classlist));
  550:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  551:     #
  552:     my %sections;
  553:     my %fullnames;
  554:     foreach my $student (keys(%$classlist)) {
  555:         my $end      = 
  556:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  557:         my $start    = 
  558:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  559:         my $id       = 
  560:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  561:         my $section  = 
  562:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  563:         my $fullname = 
  564:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  565:         my $status   = 
  566:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  567:         my $group   = 
  568:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  569: 	# filter students according to status selected
  570: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  571: 	    if (!($stu_status =~ $status)) {
  572: 		delete($classlist->{$student});
  573: 		next;
  574: 	    }
  575: 	}
  576: 	# filter students according to groups selected
  577: 	my @stu_groups = split(/,/,$group);
  578: 	if (@getgroup) {
  579: 	    my $exclude = 1;
  580: 	    foreach my $grp (@getgroup) {
  581: 	        foreach my $stu_group (@stu_groups) {
  582: 	            if ($stu_group eq $grp) {
  583: 	                $exclude = 0;
  584:     	            } 
  585: 	        }
  586:     	        if (($grp eq 'none') && !$group) {
  587:         	        $exclude = 0;
  588:         	}
  589: 	    }
  590: 	    if ($exclude) {
  591: 	        delete($classlist->{$student});
  592: 	    }
  593: 	}
  594: 	$section = ($section ne '' ? $section : 'none');
  595: 	if (&canview($section)) {
  596: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  597: 		$sections{$section}++;
  598: 		if ($classlist->{$student}) {
  599: 		    $fullnames{$student}=$fullname;
  600: 		}
  601: 	    } else {
  602: 		delete($classlist->{$student});
  603: 	    }
  604: 	} else {
  605: 	    delete($classlist->{$student});
  606: 	}
  607:     }
  608:     my %seen = ();
  609:     my @sections = sort(keys(%sections));
  610:     return ($classlist,\@sections,\%fullnames);
  611: }
  612: 
  613: sub canmodify {
  614:     my ($sec)=@_;
  615:     if ($perm{'mgr'}) {
  616: 	if (!defined($perm{'mgr_section'})) {
  617: 	    # can modify whole class
  618: 	    return 1;
  619: 	} else {
  620: 	    if ($sec eq $perm{'mgr_section'}) {
  621: 		#can modify the requested section
  622: 		return 1;
  623: 	    } else {
  624: 		# can't modify the request section
  625: 		return 0;
  626: 	    }
  627: 	}
  628:     }
  629:     #can't modify
  630:     return 0;
  631: }
  632: 
  633: sub canview {
  634:     my ($sec)=@_;
  635:     if ($perm{'vgr'}) {
  636: 	if (!defined($perm{'vgr_section'})) {
  637: 	    # can modify whole class
  638: 	    return 1;
  639: 	} else {
  640: 	    if ($sec eq $perm{'vgr_section'}) {
  641: 		#can modify the requested section
  642: 		return 1;
  643: 	    } else {
  644: 		# can't modify the request section
  645: 		return 0;
  646: 	    }
  647: 	}
  648:     }
  649:     #can't modify
  650:     return 0;
  651: }
  652: 
  653: #--- Retrieve the grade status of a student for all the parts
  654: sub student_gradeStatus {
  655:     my ($symb,$udom,$uname,$partlist) = @_;
  656:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  657:     my %partstatus = ();
  658:     foreach (@$partlist) {
  659: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  660: 	$status              = 'nothing' if ($status eq '');
  661: 	$partstatus{$_}      = $status;
  662: 	my $subkey           = "resource.$_.submitted_by";
  663: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  664:     }
  665:     return %partstatus;
  666: }
  667: 
  668: # hidden form and javascript that calls the form
  669: # Use by verifyscript and viewgrades
  670: # Shows a student's view of problem and submission
  671: sub jscriptNform {
  672:     my ($symb) = @_;
  673:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  674:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  675: 	'    function viewOneStudent(user,domain) {'."\n".
  676: 	'	document.onestudent.student.value = user;'."\n".
  677: 	'	document.onestudent.userdom.value = domain;'."\n".
  678: 	'	document.onestudent.submit();'."\n".
  679: 	'    }'."\n".
  680: 	'</script>'."\n";
  681:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  682: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  683: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  684: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  685: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  686: 	'<input type="hidden" name="command" value="submission" />'."\n".
  687: 	'<input type="hidden" name="student" value="" />'."\n".
  688: 	'<input type="hidden" name="userdom" value="" />'."\n".
  689: 	'</form>'."\n";
  690:     return $jscript;
  691: }
  692: 
  693: 
  694: 
  695: # Given the score (as a number [0-1] and the weight) what is the final
  696: # point value? This function will round to the nearest tenth, third,
  697: # or quarter if one of those is within the tolerance of .00001.
  698: sub compute_points {
  699:     my ($score, $weight) = @_;
  700:     
  701:     my $tolerance = .00001;
  702:     my $points = $score * $weight;
  703: 
  704:     # Check for nearness to 1/x.
  705:     my $check_for_nearness = sub {
  706:         my ($factor) = @_;
  707:         my $num = ($points * $factor) + $tolerance;
  708:         my $floored_num = floor($num);
  709:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  710:             return $floored_num / $factor;
  711:         }
  712:         return $points;
  713:     };
  714: 
  715:     $points = $check_for_nearness->(10);
  716:     $points = $check_for_nearness->(3);
  717:     $points = $check_for_nearness->(4);
  718:     
  719:     return $points;
  720: }
  721: 
  722: #------------------ End of general use routines --------------------
  723: 
  724: #
  725: # Find most similar essay
  726: #
  727: 
  728: sub most_similar {
  729:     my ($uname,$udom,$uessay,$old_essays)=@_;
  730: 
  731: # ignore spaces and punctuation
  732: 
  733:     $uessay=~s/\W+/ /gs;
  734: 
  735: # ignore empty submissions (occuring when only files are sent)
  736: 
  737:     unless ($uessay=~/\w+/) { return ''; }
  738: 
  739: # these will be returned. Do not care if not at least 50 percent similar
  740:     my $limit=0.6;
  741:     my $sname='';
  742:     my $sdom='';
  743:     my $scrsid='';
  744:     my $sessay='';
  745: # go through all essays ...
  746:     foreach my $tkey (keys(%$old_essays)) {
  747: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  748: # ... except the same student
  749:         next if (($tname eq $uname) && ($tdom eq $udom));
  750: 	my $tessay=$old_essays->{$tkey};
  751: 	$tessay=~s/\W+/ /gs;
  752: # String similarity gives up if not even limit
  753: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  754: # Found one
  755: 	if ($tsimilar>$limit) {
  756: 	    $limit=$tsimilar;
  757: 	    $sname=$tname;
  758: 	    $sdom=$tdom;
  759: 	    $scrsid=$tcrsid;
  760: 	    $sessay=$old_essays->{$tkey};
  761: 	}
  762:     }
  763:     if ($limit>0.6) {
  764:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  765:     } else {
  766:        return ('','','','',0);
  767:     }
  768: }
  769: 
  770: #-------------------------------------------------------------------
  771: 
  772: #------------------------------------ Receipt Verification Routines
  773: #
  774: #--- Check whether a receipt number is valid.---
  775: sub verifyreceipt {
  776:     my $request  = shift;
  777: 
  778:     my $courseid = $env{'request.course.id'};
  779:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  780: 	$env{'form.receipt'};
  781:     $receipt     =~ s/[^\-\d]//g;
  782:     my ($symb)   = &get_symb($request);
  783: 
  784:     my $title.=
  785: 	'<h3><span class="LC_info">'.
  786: 	&mt('Verifying Receipt No. [_1]',$receipt).
  787: 	'</span></h3>'."\n".
  788: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  789: 	'</h4>'."\n";
  790: 
  791:     my ($string,$contents,$matches) = ('','',0);
  792:     my (undef,undef,$fullname) = &getclasslist('all','0');
  793:     
  794:     my $receiptparts=0;
  795:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  796: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  797:     my $parts=['0'];
  798:     if ($receiptparts) {
  799:         my $res_error; 
  800:         ($parts)=&response_type($symb,\$res_error);
  801:         if ($res_error) {
  802:             return &navmap_errormsg();
  803:         } 
  804:     }
  805:     
  806:     my $header = 
  807: 	&Apache::loncommon::start_data_table().
  808: 	&Apache::loncommon::start_data_table_header_row().
  809: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  810: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  811: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  812:     if ($receiptparts) {
  813: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  814:     }
  815:     $header.=
  816: 	&Apache::loncommon::end_data_table_header_row();
  817: 
  818:     foreach (sort 
  819: 	     {
  820: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  821: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  822: 		 }
  823: 		 return $a cmp $b;
  824: 	     } (keys(%$fullname))) {
  825: 	my ($uname,$udom)=split(/\:/);
  826: 	foreach my $part (@$parts) {
  827: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  828: 		$contents.=
  829: 		    &Apache::loncommon::start_data_table_row().
  830: 		    '<td>&nbsp;'."\n".
  831: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  832: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  833: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  834: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  835: 		if ($receiptparts) {
  836: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  837: 		}
  838: 		$contents.= 
  839: 		    &Apache::loncommon::end_data_table_row()."\n";
  840: 		
  841: 		$matches++;
  842: 	    }
  843: 	}
  844:     }
  845:     if ($matches == 0) {
  846:         $string = $title
  847:                  .'<p class="LC_warning">'
  848:                  .&mt('No match found for the above receipt number.')
  849:                  .'</p>';
  850:     } else {
  851: 	$string = &jscriptNform($symb).$title.
  852: 	    '<p>'.
  853: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  854: 	    '</p>'.
  855: 	    $header.
  856: 	    $contents.
  857: 	    &Apache::loncommon::end_data_table()."\n";
  858:     }
  859:     return $string.&show_grading_menu_form($symb);
  860: }
  861: 
  862: #--- This is called by a number of programs.
  863: #--- Called from the Grading Menu - View/Grade an individual student
  864: #--- Also called directly when one clicks on the subm button 
  865: #    on the problem page.
  866: sub listStudents {
  867:     my ($request) = shift;
  868: 
  869:     my ($symb) = &get_symb($request);
  870:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  871:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  872:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  873:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  874:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  875:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  876:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  877: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  878: 
  879:     my $result='<h3><span class="LC_info">&nbsp;'
  880: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  881: 	.'</span></h3>';
  882: 
  883:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  884: 
  885:     my %lt = &Apache::lonlocal::texthash (
  886: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  887: 		'single'   => 'Please select the student before clicking on the Next button.',
  888: 	     );
  889:     $request->print(<<LISTJAVASCRIPT);
  890: <script type="text/javascript" language="javascript">
  891:     function checkSelect(checkBox) {
  892: 	var ctr=0;
  893: 	var sense="";
  894: 	if (checkBox.length > 1) {
  895: 	    for (var i=0; i<checkBox.length; i++) {
  896: 		if (checkBox[i].checked) {
  897: 		    ctr++;
  898: 		}
  899: 	    }
  900: 	    sense = '$lt{'multiple'}';
  901: 	} else {
  902: 	    if (checkBox.checked) {
  903: 		ctr = 1;
  904: 	    }
  905: 	    sense = '$lt{'single'}';
  906: 	}
  907: 	if (ctr == 0) {
  908: 	    alert(sense);
  909: 	    return false;
  910: 	}
  911: 	document.gradesub.submit();
  912:     }
  913: 
  914:     function reLoadList(formname) {
  915: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  916: 	formname.command.value = 'submission';
  917: 	formname.submit();
  918:     }
  919: </script>
  920: LISTJAVASCRIPT
  921: 
  922:     &commonJSfunctions($request);
  923:     $request->print($result);
  924: 
  925:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  926:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  927:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  928: 	"\n".$table;
  929: 	
  930:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  931:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  932:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  933:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  934:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  935:                   .&Apache::lonhtmlcommon::row_closure();
  936:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  937:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  938:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  939:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  940:                   .&Apache::lonhtmlcommon::row_closure();
  941: 
  942:     my $submission_options;
  943:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  944: 	$submission_options.=
  945: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  946:     }
  947:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  948:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  949:     $env{'form.Status'} = $saveStatus;
  950:     $submission_options.=
  951:         '<span class="LC_nobreak">'.
  952:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  953:         &mt('last submission only').' </label></span>'."\n".
  954:         '<span class="LC_nobreak">'.
  955:         '<label><input type="radio" name="lastSub" value="last" /> '.
  956:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  957:         '<span class="LC_nobreak">'.
  958:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  959:         &mt('by dates and submissions').'</label></span>'."\n".
  960:         '<span class="LC_nobreak">'.
  961:         '<label><input type="radio" name="lastSub" value="all" /> '.
  962:         &mt('all details').'</label></span>';
  963:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  964:                   .$submission_options
  965:                   .&Apache::lonhtmlcommon::row_closure();
  966: 
  967:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  968:                   .'<select name="increment">'
  969:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  970:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  971:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  972:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  973:                   .'</select>'
  974:                   .&Apache::lonhtmlcommon::row_closure();
  975: 
  976:     $gradeTable .= 
  977:         &build_section_inputs().
  978: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  979: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  980: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  981: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  982: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  983: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  984: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  985: 
  986:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  987: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  988:     } else {
  989:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  990:                       .&Apache::lonhtmlcommon::StatusOptions(
  991:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  992:                       .&Apache::lonhtmlcommon::row_closure();
  993:     }
  994: 
  995:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  996:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  997:                   .&Apache::lonhtmlcommon::row_closure(1)
  998:                   .&Apache::lonhtmlcommon::end_pick_box();
  999: 
 1000:     $gradeTable .= '<p>'
 1001:                   .&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.")."\n"
 1002:                   .'<input type="hidden" name="command" value="processGroup" />'
 1003:                   .'</p>';
 1004: 
 1005: # checkall buttons
 1006:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1007:     $gradeTable.='<input type="button" '."\n".
 1008:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1009:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1010:     $gradeTable.=&check_buttons();
 1011:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1012:     $gradeTable.= &Apache::loncommon::start_data_table().
 1013: 	&Apache::loncommon::start_data_table_header_row();
 1014:     my $loop = 0;
 1015:     while ($loop < 2) {
 1016: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1017: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1018: 	if ($env{'form.showgrading'} eq 'yes' 
 1019: 	    && $submitonly ne 'queued'
 1020: 	    && $submitonly ne 'all') {
 1021: 	    foreach my $part (sort(@$partlist)) {
 1022: 		my $display_part=
 1023: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1024: 		$gradeTable.=
 1025: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1026: 	    }
 1027: 	} elsif ($submitonly eq 'queued') {
 1028: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1029: 	}
 1030: 	$loop++;
 1031: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1032:     }
 1033:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1034: 
 1035:     my $ctr = 0;
 1036:     foreach my $student (sort 
 1037: 			 {
 1038: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1039: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1040: 			     }
 1041: 			     return $a cmp $b;
 1042: 			 }
 1043: 			 (keys(%$fullname))) {
 1044: 	my ($uname,$udom) = split(/:/,$student);
 1045: 
 1046: 	my %status = ();
 1047: 
 1048: 	if ($submitonly eq 'queued') {
 1049: 	    my %queue_status = 
 1050: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1051: 							$udom,$uname);
 1052: 	    next if (!defined($queue_status{'gradingqueue'}));
 1053: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1054: 	}
 1055: 
 1056: 	if ($env{'form.showgrading'} eq 'yes' 
 1057: 	    && $submitonly ne 'queued'
 1058: 	    && $submitonly ne 'all') {
 1059: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1060: 	    my $submitted = 0;
 1061: 	    my $graded = 0;
 1062: 	    my $incorrect = 0;
 1063: 	    foreach (keys(%status)) {
 1064: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1065: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1066: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1067: 		
 1068: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1069: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1070: 		    $submitted = 0;
 1071: 		    my ($part)=split(/\./,$partid);
 1072: 		    $gradeTable.='<input type="hidden" name="'.
 1073: 			$student.':'.$part.':submitted_by" value="'.
 1074: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1075: 		}
 1076: 	    }
 1077: 	    
 1078: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1079: 				     $submitonly eq 'incorrect' ||
 1080: 				     $submitonly eq 'graded'));
 1081: 	    next if (!$graded && ($submitonly eq 'graded'));
 1082: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1083: 	}
 1084: 
 1085: 	$ctr++;
 1086: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1087:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1088: 	if ( $perm{'vgr'} eq 'F' ) {
 1089: 	    if ($ctr%2 ==1) {
 1090: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1091: 	    }
 1092: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1093:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1094:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1095: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1096: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1097: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1098: 
 1099: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1100: 		foreach (sort(keys(%status))) {
 1101: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1102: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1103: 		}
 1104: 	    }
 1105: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1106: 	    if ($ctr%2 ==0) {
 1107: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1108: 	    }
 1109: 	}
 1110:     }
 1111:     if ($ctr%2 ==1) {
 1112: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1113: 	    if ($env{'form.showgrading'} eq 'yes' 
 1114: 		&& $submitonly ne 'queued'
 1115: 		&& $submitonly ne 'all') {
 1116: 		foreach (@$partlist) {
 1117: 		    $gradeTable.='<td>&nbsp;</td>';
 1118: 		}
 1119: 	    } elsif ($submitonly eq 'queued') {
 1120: 		$gradeTable.='<td>&nbsp;</td>';
 1121: 	    }
 1122: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1123:     }
 1124: 
 1125:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1126:         '<input type="button" '.
 1127:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1128:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1129:     if ($ctr == 0) {
 1130: 	my $num_students=(scalar(keys(%$fullname)));
 1131: 	if ($num_students eq 0) {
 1132: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1133: 	} else {
 1134: 	    my $submissions='submissions';
 1135: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1136: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1137: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1138: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1139: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1140: 		    $num_students).
 1141: 		'</span><br />';
 1142: 	}
 1143:     } elsif ($ctr == 1) {
 1144: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1145:     }
 1146:     $gradeTable.=&show_grading_menu_form($symb);
 1147:     $request->print($gradeTable);
 1148:     return '';
 1149: }
 1150: 
 1151: #---- Called from the listStudents routine
 1152: 
 1153: sub check_script {
 1154:     my ($form, $type)=@_;
 1155:     my $chkallscript='<script type="text/javascript">
 1156:     function checkall() {
 1157:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1158:             ele = document.forms.'.$form.'.elements[i];
 1159:             if (ele.name == "'.$type.'") {
 1160:             document.forms.'.$form.'.elements[i].checked=true;
 1161:                                        }
 1162:         }
 1163:     }
 1164: 
 1165:     function checksec() {
 1166:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1167:             ele = document.forms.'.$form.'.elements[i];
 1168:            string = document.forms.'.$form.'.chksec.value;
 1169:            if
 1170:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1171:               document.forms.'.$form.'.elements[i].checked=true;
 1172:             }
 1173:         }
 1174:     }
 1175: 
 1176: 
 1177:     function uncheckall() {
 1178:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1179:             ele = document.forms.'.$form.'.elements[i];
 1180:             if (ele.name == "'.$type.'") {
 1181:             document.forms.'.$form.'.elements[i].checked=false;
 1182:                                        }
 1183:         }
 1184:     }
 1185: 
 1186: </script>'."\n";
 1187:     return $chkallscript;
 1188: }
 1189: 
 1190: sub check_buttons {
 1191:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1192:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1193:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1194:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1195:     return $buttons;
 1196: }
 1197: 
 1198: #     Displays the submissions for one student or a group of students
 1199: sub processGroup {
 1200:     my ($request)  = shift;
 1201:     my $ctr        = 0;
 1202:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1203:     my $total      = scalar(@stuchecked)-1;
 1204: 
 1205:     foreach my $student (@stuchecked) {
 1206: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1207: 	$env{'form.student'}        = $uname;
 1208: 	$env{'form.userdom'}        = $udom;
 1209: 	$env{'form.fullname'}       = $fullname;
 1210: 	&submission($request,$ctr,$total);
 1211: 	$ctr++;
 1212:     }
 1213:     return '';
 1214: }
 1215: 
 1216: #------------------------------------------------------------------------------------
 1217: #
 1218: #-------------------------- Next few routines handles grading by student, essentially
 1219: #                           handles essay response type problem/part
 1220: #
 1221: #--- Javascript to handle the submission page functionality ---
 1222: sub sub_page_js {
 1223:     my $request = shift;
 1224: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1225:     $request->print(<<SUBJAVASCRIPT);
 1226: <script type="text/javascript" language="javascript">
 1227:     function updateRadio(formname,id,weight) {
 1228: 	var gradeBox = formname["GD_BOX"+id];
 1229: 	var radioButton = formname["RADVAL"+id];
 1230: 	var oldpts = formname["oldpts"+id].value;
 1231: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1232: 	gradeBox.value = pts;
 1233: 	var resetbox = false;
 1234: 	if (isNaN(pts) || pts < 0) {
 1235: 	    alert("$alertmsg"+pts);
 1236: 	    for (var i=0; i<radioButton.length; i++) {
 1237: 		if (radioButton[i].checked) {
 1238: 		    gradeBox.value = i;
 1239: 		    resetbox = true;
 1240: 		}
 1241: 	    }
 1242: 	    if (!resetbox) {
 1243: 		formtextbox.value = "";
 1244: 	    }
 1245: 	    return;
 1246: 	}
 1247: 
 1248: 	if (pts > weight) {
 1249: 	    var resp = confirm("You entered a value ("+pts+
 1250: 			       ") greater than the weight for the part. Accept?");
 1251: 	    if (resp == false) {
 1252: 		gradeBox.value = oldpts;
 1253: 		return;
 1254: 	    }
 1255: 	}
 1256: 
 1257: 	for (var i=0; i<radioButton.length; i++) {
 1258: 	    radioButton[i].checked=false;
 1259: 	    if (pts == i && pts != "") {
 1260: 		radioButton[i].checked=true;
 1261: 	    }
 1262: 	}
 1263: 	updateSelect(formname,id);
 1264: 	formname["stores"+id].value = "0";
 1265:     }
 1266: 
 1267:     function writeBox(formname,id,pts) {
 1268: 	var gradeBox = formname["GD_BOX"+id];
 1269: 	if (checkSolved(formname,id) == 'update') {
 1270: 	    gradeBox.value = pts;
 1271: 	} else {
 1272: 	    var oldpts = formname["oldpts"+id].value;
 1273: 	    gradeBox.value = oldpts;
 1274: 	    var radioButton = formname["RADVAL"+id];
 1275: 	    for (var i=0; i<radioButton.length; i++) {
 1276: 		radioButton[i].checked=false;
 1277: 		if (i == oldpts) {
 1278: 		    radioButton[i].checked=true;
 1279: 		}
 1280: 	    }
 1281: 	}
 1282: 	formname["stores"+id].value = "0";
 1283: 	updateSelect(formname,id);
 1284: 	return;
 1285:     }
 1286: 
 1287:     function clearRadBox(formname,id) {
 1288: 	if (checkSolved(formname,id) == 'noupdate') {
 1289: 	    updateSelect(formname,id);
 1290: 	    return;
 1291: 	}
 1292: 	gradeSelect = formname["GD_SEL"+id];
 1293: 	for (var i=0; i<gradeSelect.length; i++) {
 1294: 	    if (gradeSelect[i].selected) {
 1295: 		var selectx=i;
 1296: 	    }
 1297: 	}
 1298: 	var stores = formname["stores"+id];
 1299: 	if (selectx == stores.value) { return };
 1300: 	var gradeBox = formname["GD_BOX"+id];
 1301: 	gradeBox.value = "";
 1302: 	var radioButton = formname["RADVAL"+id];
 1303: 	for (var i=0; i<radioButton.length; i++) {
 1304: 	    radioButton[i].checked=false;
 1305: 	}
 1306: 	stores.value = selectx;
 1307:     }
 1308: 
 1309:     function checkSolved(formname,id) {
 1310: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1311: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1312: 	    if (!reply) {return "noupdate";}
 1313: 	    formname.overRideScore.value = 'yes';
 1314: 	}
 1315: 	return "update";
 1316:     }
 1317: 
 1318:     function updateSelect(formname,id) {
 1319: 	formname["GD_SEL"+id][0].selected = true;
 1320: 	return;
 1321:     }
 1322: 
 1323: //=========== Check that a point is assigned for all the parts  ============
 1324:     function checksubmit(formname,val,total,parttot) {
 1325: 	formname.gradeOpt.value = val;
 1326: 	if (val == "Save & Next") {
 1327: 	    for (i=0;i<=total;i++) {
 1328: 		for (j=0;j<parttot;j++) {
 1329: 		    var partid = formname["partid"+i+"_"+j].value;
 1330: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1331: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1332: 			if (points == "") {
 1333: 			    var name = formname["name"+i].value;
 1334: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1335: 			    var resp = confirm("You did not assign a score for "+studentID+
 1336: 					       ", part "+partid+". Continue?");
 1337: 			    if (resp == false) {
 1338: 				formname["GD_BOX"+i+"_"+partid].focus();
 1339: 				return false;
 1340: 			    }
 1341: 			}
 1342: 		    }
 1343: 		    
 1344: 		}
 1345: 	    }
 1346: 	    
 1347: 	}
 1348: 	if (val == "Grade Student") {
 1349: 	    formname.showgrading.value = "yes";
 1350: 	    if (formname.Status.value == "") {
 1351: 		formname.Status.value = "Active";
 1352: 	    }
 1353: 	    formname.studentNo.value = total;
 1354: 	}
 1355: 	formname.submit();
 1356:     }
 1357: 
 1358: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1359:     function checkSubmitPage(formname,total) {
 1360: 	noscore = new Array(100);
 1361: 	var ptr = 0;
 1362: 	for (i=1;i<total;i++) {
 1363: 	    var partid = formname["q_"+i].value;
 1364: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1365: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1366: 		var status = formname["solved"+i+"_"+partid].value;
 1367: 		if (points == "" && status != "correct_by_student") {
 1368: 		    noscore[ptr] = i;
 1369: 		    ptr++;
 1370: 		}
 1371: 	    }
 1372: 	}
 1373: 	if (ptr != 0) {
 1374: 	    var sense = ptr == 1 ? ": " : "s: ";
 1375: 	    var prolist = "";
 1376: 	    if (ptr == 1) {
 1377: 		prolist = noscore[0];
 1378: 	    } else {
 1379: 		var i = 0;
 1380: 		while (i < ptr-1) {
 1381: 		    prolist += noscore[i]+", ";
 1382: 		    i++;
 1383: 		}
 1384: 		prolist += "and "+noscore[i];
 1385: 	    }
 1386: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1387: 	    if (resp == false) {
 1388: 		return false;
 1389: 	    }
 1390: 	}
 1391: 
 1392: 	formname.submit();
 1393:     }
 1394: </script>
 1395: SUBJAVASCRIPT
 1396: }
 1397: 
 1398: #--- javascript for essay type problem --
 1399: sub sub_page_kw_js {
 1400:     my $request = shift;
 1401:     my $iconpath = $request->dir_config('lonIconsURL');
 1402:     &commonJSfunctions($request);
 1403: 
 1404:     my $inner_js_msg_central=<<INNERJS;
 1405:     <script text="text/javascript">
 1406:     function checkInput() {
 1407:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1408:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1409:       var usrctr = document.msgcenter.usrctr.value;
 1410:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1411:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1412: 
 1413:       var msgchk = "";
 1414:       if (document.msgcenter.subchk.checked) {
 1415:          msgchk = "msgsub,";
 1416:       }
 1417:       var includemsg = 0;
 1418:       for (var i=1; i<=nmsg; i++) {
 1419:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1420:           var frmmsg = document.msgcenter["msg"+i];
 1421:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1422:           var showflg = opener.document.SCORE["shownOnce"+i];
 1423:           showflg.value = "1";
 1424:           var chkbox = document.msgcenter["msgn"+i];
 1425:           if (chkbox.checked) {
 1426:              msgchk += "savemsg"+i+",";
 1427:              includemsg = 1;
 1428:           }
 1429:       }
 1430:       if (document.msgcenter.newmsgchk.checked) {
 1431:          msgchk += "newmsg"+usrctr;
 1432:          includemsg = 1;
 1433:       }
 1434:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1435:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1436:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1437:       includemsg.value = msgchk;
 1438: 
 1439:       self.close()
 1440: 
 1441:     }
 1442:     </script>
 1443: INNERJS
 1444: 
 1445:     my $inner_js_highlight_central=<<INNERJS;
 1446:  <script type="text/javascript">
 1447:     function updateChoice(flag) {
 1448:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1449:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1450:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1451:       opener.document.SCORE.refresh.value = "on";
 1452:       if (opener.document.SCORE.keywords.value!=""){
 1453:          opener.document.SCORE.submit();
 1454:       }
 1455:       self.close()
 1456:     }
 1457: </script>
 1458: INNERJS
 1459: 
 1460:     my $start_page_msg_central = 
 1461:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1462: 				       {'js_ready'  => 1,
 1463: 					'only_body' => 1,
 1464: 					'bgcolor'   =>'#FFFFFF',});
 1465:     my $end_page_msg_central = 
 1466: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1467: 
 1468: 
 1469:     my $start_page_highlight_central = 
 1470:         &Apache::loncommon::start_page('Highlight Central',
 1471: 				       $inner_js_highlight_central,
 1472: 				       {'js_ready'  => 1,
 1473: 					'only_body' => 1,
 1474: 					'bgcolor'   =>'#FFFFFF',});
 1475:     my $end_page_highlight_central = 
 1476: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1477: 
 1478:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1479:     $docopen=~s/^document\.//;
 1480:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1481:     $request->print(<<SUBJAVASCRIPT);
 1482: <script type="text/javascript" language="javascript">
 1483: 
 1484: //===================== Show list of keywords ====================
 1485:   function keywords(formname) {
 1486:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1487:     if (nret==null) return;
 1488:     formname.keywords.value = nret;
 1489: 
 1490:     if (formname.keywords.value != "") {
 1491: 	formname.refresh.value = "on";
 1492: 	formname.submit();
 1493:     }
 1494:     return;
 1495:   }
 1496: 
 1497: //===================== Script to view submitted by ==================
 1498:   function viewSubmitter(submitter) {
 1499:     document.SCORE.refresh.value = "on";
 1500:     document.SCORE.NCT.value = "1";
 1501:     document.SCORE.unamedom0.value = submitter;
 1502:     document.SCORE.submit();
 1503:     return;
 1504:   }
 1505: 
 1506: //===================== Script to add keyword(s) ==================
 1507:   function getSel() {
 1508:     if (document.getSelection) txt = document.getSelection();
 1509:     else if (document.selection) txt = document.selection.createRange().text;
 1510:     else return;
 1511:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1512:     if (cleantxt=="") {
 1513: 	alert("$alertmsg");
 1514: 	return;
 1515:     }
 1516:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1517:     if (nret==null) return;
 1518:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1519:     if (document.SCORE.keywords.value != "") {
 1520: 	document.SCORE.refresh.value = "on";
 1521: 	document.SCORE.submit();
 1522:     }
 1523:     return;
 1524:   }
 1525: 
 1526: //====================== Script for composing message ==============
 1527:    // preload images
 1528:    img1 = new Image();
 1529:    img1.src = "$iconpath/mailbkgrd.gif";
 1530:    img2 = new Image();
 1531:    img2.src = "$iconpath/mailto.gif";
 1532: 
 1533:   function msgCenter(msgform,usrctr,fullname) {
 1534:     var Nmsg  = msgform.savemsgN.value;
 1535:     savedMsgHeader(Nmsg,usrctr,fullname);
 1536:     var subject = msgform.msgsub.value;
 1537:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1538:     re = /msgsub/;
 1539:     var shwsel = "";
 1540:     if (re.test(msgchk)) { shwsel = "checked" }
 1541:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1542:     displaySubject(checkEntities(subject),shwsel);
 1543:     for (var i=1; i<=Nmsg; i++) {
 1544: 	var testmsg = "savemsg"+i+",";
 1545: 	re = new RegExp(testmsg,"g");
 1546: 	shwsel = "";
 1547: 	if (re.test(msgchk)) { shwsel = "checked" }
 1548: 	var message = document.SCORE["savemsg"+i].value;
 1549: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1550: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1551: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1552:     }
 1553:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1554:     shwsel = "";
 1555:     re = /newmsg/;
 1556:     if (re.test(msgchk)) { shwsel = "checked" }
 1557:     newMsg(newmsg,shwsel);
 1558:     msgTail(); 
 1559:     return;
 1560:   }
 1561: 
 1562:   function checkEntities(strx) {
 1563:     if (strx.length == 0) return strx;
 1564:     var orgStr = ["&", "<", ">", '"']; 
 1565:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1566:     var counter = 0;
 1567:     while (counter < 4) {
 1568: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1569: 	counter++;
 1570:     }
 1571:     return strx;
 1572:   }
 1573: 
 1574:   function strReplace(strx, orgStr, newStr) {
 1575:     return strx.split(orgStr).join(newStr);
 1576:   }
 1577: 
 1578:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1579:     var height = 70*Nmsg+250;
 1580:     var scrollbar = "no";
 1581:     if (height > 600) {
 1582: 	height = 600;
 1583: 	scrollbar = "yes";
 1584:     }
 1585:     var xpos = (screen.width-600)/2;
 1586:     xpos = (xpos < 0) ? '0' : xpos;
 1587:     var ypos = (screen.height-height)/2-30;
 1588:     ypos = (ypos < 0) ? '0' : ypos;
 1589: 
 1590:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1591:     pWin.focus();
 1592:     pDoc = pWin.document;
 1593:     pDoc.$docopen;
 1594:     pDoc.write('$start_page_msg_central');
 1595: 
 1596:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1597:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1598:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1599: 
 1600:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1601:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1602:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1603: }
 1604:     function displaySubject(msg,shwsel) {
 1605:     pDoc = pWin.document;
 1606:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1607:     pDoc.write("<td>Subject<\\/td>");
 1608:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1609:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1610: }
 1611: 
 1612:   function displaySavedMsg(ctr,msg,shwsel) {
 1613:     pDoc = pWin.document;
 1614:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1615:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1616:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1617:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1618: }
 1619: 
 1620:   function newMsg(newmsg,shwsel) {
 1621:     pDoc = pWin.document;
 1622:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1623:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1624:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1625:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1626: }
 1627: 
 1628:   function msgTail() {
 1629:     pDoc = pWin.document;
 1630:     pDoc.write("<\\/table>");
 1631:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1632:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1633:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1634:     pDoc.write("<\\/form>");
 1635:     pDoc.write('$end_page_msg_central');
 1636:     pDoc.close();
 1637: }
 1638: 
 1639: //====================== Script for keyword highlight options ==============
 1640:   function kwhighlight() {
 1641:     var kwclr    = document.SCORE.kwclr.value;
 1642:     var kwsize   = document.SCORE.kwsize.value;
 1643:     var kwstyle  = document.SCORE.kwstyle.value;
 1644:     var redsel = "";
 1645:     var grnsel = "";
 1646:     var blusel = "";
 1647:     if (kwclr=="red")   {var redsel="checked"};
 1648:     if (kwclr=="green") {var grnsel="checked"};
 1649:     if (kwclr=="blue")  {var blusel="checked"};
 1650:     var sznsel = "";
 1651:     var sz1sel = "";
 1652:     var sz2sel = "";
 1653:     if (kwsize=="0")  {var sznsel="checked"};
 1654:     if (kwsize=="+1") {var sz1sel="checked"};
 1655:     if (kwsize=="+2") {var sz2sel="checked"};
 1656:     var synsel = "";
 1657:     var syisel = "";
 1658:     var sybsel = "";
 1659:     if (kwstyle=="")    {var synsel="checked"};
 1660:     if (kwstyle=="<i>") {var syisel="checked"};
 1661:     if (kwstyle=="<b>") {var sybsel="checked"};
 1662:     highlightCentral();
 1663:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1664:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1665:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1666:     highlightend();
 1667:     return;
 1668:   }
 1669: 
 1670:   function highlightCentral() {
 1671: //    if (window.hwdWin) window.hwdWin.close();
 1672:     var xpos = (screen.width-400)/2;
 1673:     xpos = (xpos < 0) ? '0' : xpos;
 1674:     var ypos = (screen.height-330)/2-30;
 1675:     ypos = (ypos < 0) ? '0' : ypos;
 1676: 
 1677:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1678:     hwdWin.focus();
 1679:     var hDoc = hwdWin.document;
 1680:     hDoc.$docopen;
 1681:     hDoc.write('$start_page_highlight_central');
 1682:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1683:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1684: 
 1685:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1686:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1687:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1688:   }
 1689: 
 1690:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1691:     var hDoc = hwdWin.document;
 1692:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1693:     hDoc.write("<td align=\\"left\\">");
 1694:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1695:     hDoc.write("<td align=\\"left\\">");
 1696:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1697:     hDoc.write("<td align=\\"left\\">");
 1698:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1699:     hDoc.write("<\\/tr>");
 1700:   }
 1701: 
 1702:   function highlightend() { 
 1703:     var hDoc = hwdWin.document;
 1704:     hDoc.write("<\\/table>");
 1705:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1706:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1707:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1708:     hDoc.write("<\\/form>");
 1709:     hDoc.write('$end_page_highlight_central');
 1710:     hDoc.close();
 1711:   }
 1712: 
 1713: </script>
 1714: SUBJAVASCRIPT
 1715: }
 1716: 
 1717: sub get_increment {
 1718:     my $increment = $env{'form.increment'};
 1719:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1720:         $increment != .1) {
 1721:         $increment = 1;
 1722:     }
 1723:     return $increment;
 1724: }
 1725: 
 1726: sub gradeBox_start {
 1727:     return (
 1728:         &Apache::loncommon::start_data_table()
 1729:        .&Apache::loncommon::start_data_table_header_row()
 1730:        .'<th>'.&mt('Part').'</th>'
 1731:        .'<th>'.&mt('Points').'</th>'
 1732:        .'<th>&nbsp;</th>'
 1733:        .'<th>'.&mt('Assign Grade').'</th>'
 1734:        .'<th>'.&mt('Weight').'</th>'
 1735:        .'<th>'.&mt('Grade Status').'</th>'
 1736:        .&Apache::loncommon::end_data_table_header_row()
 1737:     );
 1738: }
 1739: 
 1740: sub gradeBox_end {
 1741:     return (
 1742:         &Apache::loncommon::end_data_table()
 1743:     );
 1744: }
 1745: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1746: sub gradeBox {
 1747:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1748:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1749: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1750:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1751:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1752:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1753:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1754:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1755: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1756:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1757:     my $display_part= &get_display_part($partid,$symb);
 1758:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1759: 				       [$partid]);
 1760:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1761:     if ($last_resets{$partid}) {
 1762:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1763:     }
 1764:     $result.=&Apache::loncommon::start_data_table_row();
 1765:     my $ctr = 0;
 1766:     my $thisweight = 0;
 1767:     my $increment = &get_increment();
 1768: 
 1769:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1770:     while ($thisweight<=$wgt) {
 1771: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1772:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1773: 	    $thisweight.')" value="'.$thisweight.'" '.
 1774: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1775: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1776:         $thisweight += $increment;
 1777: 	$ctr++;
 1778:     }
 1779:     $radio.='</tr></table>';
 1780: 
 1781:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1782: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1783: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1784: 	$wgt.')" /></td>'."\n";
 1785:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1786: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1787: 	' </td>'."\n";
 1788:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1789: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1790:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1791: 	$line.='<option></option>'.
 1792: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1793:     } else {
 1794: 	$line.='<option selected="selected"></option>'.
 1795: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1796:     }
 1797:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1798: 
 1799: 
 1800: 	#&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);
 1801:     $result .= 
 1802: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1803:     $result.=&Apache::loncommon::end_data_table_row();
 1804:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1805: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1806: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1807: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1808:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1809:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1810:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1811:         $aggtries.'" />'."\n";
 1812:     my $res_error;
 1813:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1814:     if ($res_error) {
 1815:         return &navmap_errormsg();
 1816:     }
 1817:     return $result;
 1818: }
 1819: 
 1820: sub handback_box {
 1821:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1822:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1823:     my (@respids);
 1824:      my @part_response_id = &flatten_responseType($responseType);
 1825:     foreach my $part_response_id (@part_response_id) {
 1826:     	my ($part,$resp) = @{ $part_response_id };
 1827:         if ($part eq $partid) {
 1828:             push(@respids,$resp);
 1829:         }
 1830:     }
 1831:     my $result;
 1832:     foreach my $respid (@respids) {
 1833: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1834: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1835: 	next if (!@$files);
 1836: 	my $file_counter = 1;
 1837: 	foreach my $file (@$files) {
 1838: 	    if ($file =~ /\/portfolio\//) {
 1839:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1840:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1841:     	        $file_disp = "$name.$ext";
 1842:     	        $file = $file_path.$file_disp;
 1843:     	        $result.=&mt('Return commented version of [_1] to student.',
 1844:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1845:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1846:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1847:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1848:     	        $file_counter++;
 1849: 	    }
 1850: 	}
 1851:     }
 1852:     return $result;    
 1853: }
 1854: 
 1855: sub show_problem {
 1856:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1857:     my $rendered;
 1858:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1859:     &Apache::lonxml::remember_problem_counter();
 1860:     if ($mode eq 'both' or $mode eq 'text') {
 1861: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1862: 						       $env{'request.course.id'},
 1863: 						       undef,\%form);
 1864:     }
 1865:     if ($removeform) {
 1866: 	$rendered=~s|<form(.*?)>||g;
 1867: 	$rendered=~s|</form>||g;
 1868: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1869:     }
 1870:     my $companswer;
 1871:     if ($mode eq 'both' or $mode eq 'answer') {
 1872: 	&Apache::lonxml::restore_problem_counter();
 1873: 	$companswer=
 1874: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1875: 						    $env{'request.course.id'},
 1876: 						    %form);
 1877:     }
 1878:     if ($removeform) {
 1879: 	$companswer=~s|<form(.*?)>||g;
 1880: 	$companswer=~s|</form>||g;
 1881: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1882:     }
 1883:     $rendered=
 1884:         '<div class="LC_Box">'
 1885:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1886:        .$rendered
 1887:        .'</div>';
 1888:     $companswer=
 1889:         '<div class="LC_Box">'
 1890:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1891:        .$companswer
 1892:        .'</div>';
 1893:     my $result;
 1894:     if ($mode eq 'both') {
 1895:         $result=$rendered.$companswer;
 1896:     } elsif ($mode eq 'text') {
 1897:         $result=$rendered;
 1898:     } elsif ($mode eq 'answer') {
 1899:         $result=$companswer;
 1900:     }
 1901:     return $result;
 1902: }
 1903: 
 1904: sub files_exist {
 1905:     my ($r, $symb) = @_;
 1906:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1907: 
 1908:     foreach my $student (@students) {
 1909:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1910:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1911: 					      $udom,$uname);
 1912:         my ($string,$timestamp)= &get_last_submission(\%record);
 1913:         foreach my $submission (@$string) {
 1914:             my ($partid,$respid) =
 1915: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1916:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1917: 					   \%record);
 1918:             return 1 if (@$files);
 1919:         }
 1920:     }
 1921:     return 0;
 1922: }
 1923: 
 1924: sub download_all_link {
 1925:     my ($r,$symb) = @_;
 1926:     my $all_students = 
 1927: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1928: 
 1929:     my $parts =
 1930: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1931: 
 1932:     my $identifier = &Apache::loncommon::get_cgi_id();
 1933:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1934:                              'cgi.'.$identifier.'.symb' => $symb,
 1935:                              'cgi.'.$identifier.'.parts' => $parts,});
 1936:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1937: 	      &mt('Download All Submitted Documents').'</a>');
 1938:     return
 1939: }
 1940: 
 1941: sub build_section_inputs {
 1942:     my $section_inputs;
 1943:     if ($env{'form.section'} eq '') {
 1944:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1945:     } else {
 1946:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1947:         foreach my $section (@sections) {
 1948:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1949:         }
 1950:     }
 1951:     return $section_inputs;
 1952: }
 1953: 
 1954: # --------------------------- show submissions of a student, option to grade 
 1955: sub submission {
 1956:     my ($request,$counter,$total) = @_;
 1957:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1958:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1959:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1960:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1961:     my $symb = &get_symb($request); 
 1962:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1963: 
 1964:     if (!&canview($usec)) {
 1965: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1966: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1967: 			$env{'request.course.id'}.')</span>');
 1968: 	$request->print(&show_grading_menu_form($symb));
 1969: 	return;
 1970:     }
 1971: 
 1972:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1973:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1974:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1975:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1976:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1977: 	'" src="'.$request->dir_config('lonIconsURL').
 1978: 	'/check.gif" height="16" border="0" />';
 1979: 
 1980:     my %old_essays;
 1981:     # header info
 1982:     if ($counter == 0) {
 1983: 	&sub_page_js($request);
 1984: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1985: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1986: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1987: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1988: 	    &download_all_link($request, $symb);
 1989: 	}
 1990: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1991: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1992: 
 1993: 	# option to display problem, only once else it cause problems 
 1994:         # with the form later since the problem has a form.
 1995: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1996: 	    my $mode;
 1997: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1998: 		$mode='both';
 1999: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2000: 		$mode='text';
 2001: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2002: 		$mode='answer';
 2003: 	    }
 2004: 	    &Apache::lonxml::clear_problem_counter();
 2005: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2006: 	}
 2007: 
 2008: 	# kwclr is the only variable that is guaranteed to be non blank 
 2009:         # if this subroutine has been called once.
 2010: 	my %keyhash = ();
 2011: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2012: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2013: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2014: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2015: 
 2016: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2017: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2018: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2019: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2020: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2021: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2022: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2023: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2024: 	}
 2025: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2026: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2027: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2028: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2029: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2030: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2031: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2032: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2033: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2034: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2035: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2036: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2037: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2038: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2039: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2040: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2041: 			&build_section_inputs().
 2042: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2043: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2044: 			'<input type="hidden" name="NCT"'.
 2045: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2046: 	if ($env{'form.handgrade'} eq 'yes') {
 2047: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2048: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2049: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2050: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2051: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2052: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2053: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2054: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2055: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2056: 	    }
 2057: 	}
 2058: 	
 2059: 	my ($cts,$prnmsg) = (1,'');
 2060: 	while ($cts <= $env{'form.savemsgN'}) {
 2061: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2062: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2063: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2064: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2065: 		'" />'."\n".
 2066: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2067: 	    $cts++;
 2068: 	}
 2069: 	$request->print($prnmsg);
 2070: 
 2071: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2072: #
 2073: # Print out the keyword options line
 2074: #
 2075: 	    $request->print(<<KEYWORDS);
 2076: &nbsp;<b>Keyword Options:</b>&nbsp;
 2077: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2078: <a href="#" onmousedown="javascript:getSel(); return false"
 2079:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2080: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2081: KEYWORDS
 2082: #
 2083: # Load the other essays for similarity check
 2084: #
 2085:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2086: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2087: 	    $apath=&escape($apath);
 2088: 	    $apath=~s/\W/\_/gs;
 2089: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2090:         }
 2091:     }
 2092: 
 2093: # This is where output for one specific student would start
 2094:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2095:     $request->print(
 2096:         "\n\n"
 2097:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2098:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2099:        ."\n"
 2100:     );
 2101: 
 2102:     # Show additional functions if allowed
 2103:     if ($perm{'vgr'}) {
 2104:         $request->print(
 2105:             &Apache::loncommon::track_student_link(
 2106:                 &mt('View recent activity'),
 2107:                 $uname,$udom,'check')
 2108:            .' '
 2109:         );
 2110:     }
 2111:     if ($perm{'opa'}) {
 2112:         $request->print(
 2113:             &Apache::loncommon::pprmlink(
 2114:                 &mt('Set/Change parameters'),
 2115:                 $uname,$udom,$symb,'check'));
 2116:     }
 2117: 
 2118:     # Show Problem
 2119:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2120: 	my $mode;
 2121: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2122: 	    $mode='both';
 2123: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2124: 	    $mode='text';
 2125: 	} elsif ($env{'form.vAns'} eq 'all') {
 2126: 	    $mode='answer';
 2127: 	}
 2128: 	&Apache::lonxml::clear_problem_counter();
 2129: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2130:     }
 2131: 
 2132:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2133:     my $res_error;
 2134:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2135:     if ($res_error) {
 2136:         $request->print(&navmap_errormsg());
 2137:         return;
 2138:     }
 2139: 
 2140:     # Display student info
 2141:     $request->print(($counter == 0 ? '' : '<br />'));
 2142: 
 2143:     my $result='<div class="LC_Box">'
 2144:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2145:     $result.='<input type="hidden" name="name'.$counter.
 2146:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2147:     if ($env{'form.handgrade'} eq 'no') {
 2148:         $result.='<p class="LC_info">'
 2149:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2150:                 ."</p>\n";
 2151:     }
 2152: 
 2153:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2154:     my $fullname;
 2155:     my $col_fullnames = [];
 2156:     if ($env{'form.handgrade'} eq 'yes') {
 2157: 	(my $sub_result,$fullname,$col_fullnames)=
 2158: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2159: 				 $counter);
 2160: 	$result.=$sub_result;
 2161:     }
 2162:     $request->print($result."\n");
 2163: 
 2164:     # print student answer/submission
 2165:     # Options are (1) Handgraded submission only
 2166:     #             (2) Last submission, includes submission that is not handgraded 
 2167:     #                  (for multi-response type part)
 2168:     #             (3) Last submission plus the parts info
 2169:     #             (4) The whole record for this student
 2170:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2171: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2172: 	
 2173: 	my $lastsubonly;
 2174: 
 2175:         if ($$timestamp eq '') {
 2176:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2177:         } else {
 2178:             $lastsubonly =
 2179:                 '<div class="LC_grade_submissions_body">'
 2180:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2181: 
 2182: 	    my %seenparts;
 2183: 	    my @part_response_id = &flatten_responseType($responseType);
 2184: 	    foreach my $part (@part_response_id) {
 2185: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2186: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2187: 
 2188: 		my ($partid,$respid) = @{ $part };
 2189: 		my $display_part=&get_display_part($partid,$symb);
 2190: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2191: 		    if (exists($seenparts{$partid})) { next; }
 2192: 		    $seenparts{$partid}=1;
 2193: 		    my $submitby='<b>Part:</b> '.$display_part.
 2194: 			' <b>Collaborative submission by:</b> '.
 2195: 			'<a href="javascript:viewSubmitter(\''.
 2196: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2197: 			'\');" target="_self">'.
 2198: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2199: 		    $request->print($submitby);
 2200: 		    next;
 2201: 		}
 2202: 		my $responsetype = $responseType->{$partid}->{$respid};
 2203: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2204:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2205:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2206:                         ' <span class="LC_internal_info">'.
 2207:                         '('.&mt('Part ID: [_1]',$respid).')</b>'.
 2208:                         '</span>&nbsp; &nbsp;'.
 2209: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2210: 		    next;
 2211: 		}
 2212: 		foreach my $submission (@$string) {
 2213: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2214: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2215: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2216: 		    # Similarity check
 2217: 		    my $similar='';
 2218: 		    if($env{'form.checkPlag'}){
 2219: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2220: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2221: 			if ($osim) {
 2222: 			    $osim=int($osim*100.0);
 2223: 			    my %old_course_desc = 
 2224: 				&Apache::lonnet::coursedescription($ocrsid,
 2225: 								   {'one_time' => 1});
 2226: 
 2227: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2228: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2229: 				    $osim,
 2230: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2231: 				    $old_course_desc{'description'},
 2232: 				    $old_course_desc{'num'},
 2233: 				    $old_course_desc{'domain'}).
 2234: 				'</span></h3><blockquote><i>'.
 2235: 				&keywords_highlight($oessay).
 2236: 				'</i></blockquote><hr />';
 2237: 			}
 2238: 		    }
 2239: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2240: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2241: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2242: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2243: 			my $display_part=&get_display_part($partid,$symb);
 2244:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2245:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2246:                             ' <span class="LC_internal_info">'.
 2247:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2248:                             '</b></span>&nbsp; &nbsp;';
 2249: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2250: 			if (@$files) {
 2251: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2252: 			    my $file_counter = 0;
 2253: 			    foreach my $file (@$files) {
 2254: 			        $file_counter++;
 2255: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2256: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2257: 			    }
 2258: 			    $lastsubonly.='<br />';
 2259: 			}
 2260: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2261: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2262: 					 $respid,\%record,$order,undef,$uname,$udom);
 2263: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2264: 			$lastsubonly.='</div>';
 2265: 		    }
 2266: 		}
 2267: 	    }
 2268: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2269: 	}
 2270: 	$request->print($lastsubonly);
 2271:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2272: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2273: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2274:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2275: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2276: 								 $env{'request.course.id'},
 2277: 								 $last,'.submission',
 2278: 								 'Apache::grades::keywords_highlight'));
 2279:     }
 2280: 
 2281:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2282: 	.$udom.'" />'."\n");
 2283:     # return if view submission with no grading option
 2284:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2285: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2286: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2287: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2288: 	$toGrade.='</div>'."\n";
 2289: 	if (($env{'form.command'} eq 'submission') || 
 2290: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2291: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2292: 	}
 2293: 	$request->print($toGrade);
 2294: 	return;
 2295:     } else {
 2296: 	$request->print('</div>'."\n");
 2297:     }
 2298: 
 2299:     # essay grading message center
 2300:     if ($env{'form.handgrade'} eq 'yes') {
 2301: 	my $result='<div class="LC_grade_message_center">';
 2302:     
 2303: 	$result.='<div class="LC_grade_message_center_header">'.
 2304: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2305: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2306: 	my $msgfor = $givenn.' '.$lastname;
 2307: 	if (scalar(@$col_fullnames) > 0) {
 2308: 	    my $lastone = pop(@$col_fullnames);
 2309: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2310: 	}
 2311: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2312: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2313: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2314: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2315: 	    ',\''.$msgfor.'\');" target="_self">'.
 2316: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2317: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2318: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2319: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2320: 	    '<br />&nbsp;('.
 2321: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2322: 	$result.='</div></div>';
 2323: 	$request->print($result);
 2324:     }
 2325: 
 2326:     my %seen = ();
 2327:     my @partlist;
 2328:     my @gradePartRespid;
 2329:     my @part_response_id = &flatten_responseType($responseType);
 2330:     $request->print(
 2331:         '<div class="LC_Box">'
 2332:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2333:     );
 2334:     $request->print(&gradeBox_start());
 2335:     foreach my $part_response_id (@part_response_id) {
 2336:     	my ($partid,$respid) = @{ $part_response_id };
 2337: 	my $part_resp = join('_',@{ $part_response_id });
 2338: 	next if ($seen{$partid} > 0);
 2339: 	$seen{$partid}++;
 2340: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2341: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2342: 	push(@partlist,$partid);
 2343: 	push(@gradePartRespid,$partid.'.'.$respid);
 2344: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2345:     }
 2346:     $request->print(&gradeBox_end()); # </div>
 2347:     $request->print('</div>');
 2348: 
 2349:     $request->print('<div class="LC_grade_info_links">');
 2350:     $request->print('</div>');
 2351: 
 2352:     $result='<input type="hidden" name="partlist'.$counter.
 2353: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2354:     $result.='<input type="hidden" name="gradePartRespid'.
 2355: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2356:     my $ctr = 0;
 2357:     while ($ctr < scalar(@partlist)) {
 2358: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2359: 	    $partlist[$ctr].'" />'."\n";
 2360: 	$ctr++;
 2361:     }
 2362:     $request->print($result.''."\n");
 2363: 
 2364: # Done with printing info for one student
 2365: 
 2366:     $request->print('</div>');#LC_grade_show_user
 2367: 
 2368: 
 2369:     # print end of form
 2370:     if ($counter == $total) {
 2371:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2372: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2373: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2374: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2375: 	my $ntstu ='<select name="NTSTU">'.
 2376: 	    '<option>1</option><option>2</option>'.
 2377: 	    '<option>3</option><option>5</option>'.
 2378: 	    '<option>7</option><option>10</option></select>'."\n";
 2379: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2380: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2381:         $endform.=&mt('[_1]student(s)',$ntstu);
 2382: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2383: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2384: 	    '<input type="button" value="'.&mt('Next').'" '.
 2385: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2386:         $endform.='<span class="LC_warning">'.
 2387:                   &mt('(Next and Previous (student) do not save the scores.)').
 2388:                   '</span>'."\n" ;
 2389:         $endform.="<input type='hidden' value='".&get_increment().
 2390:             "' name='increment' />";
 2391: 	$endform.='</td></tr></table></form>';
 2392: 	$endform.=&show_grading_menu_form($symb);
 2393: 	$request->print($endform);
 2394:     }
 2395:     return '';
 2396: }
 2397: 
 2398: sub check_collaborators {
 2399:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2400:     my ($result,@col_fullnames);
 2401:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2402:     foreach my $part (keys(%$handgrade)) {
 2403: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2404: 					'.maxcollaborators',
 2405: 					$symb,$udom,$uname);
 2406: 	next if ($ncol <= 0);
 2407: 	$part =~ s/\_/\./g;
 2408: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2409: 	my (@good_collaborators, @bad_collaborators);
 2410: 	foreach my $possible_collaborator
 2411: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2412: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2413: 	    next if ($possible_collaborator eq '');
 2414: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2415: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2416: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2417: 	    # Doing this grep allows 'fuzzy' specification
 2418: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2419: 			       keys(%$classlist));
 2420: 	    if (! scalar(@matches)) {
 2421: 		push(@bad_collaborators, $possible_collaborator);
 2422: 	    } else {
 2423: 		push(@good_collaborators, @matches);
 2424: 	    }
 2425: 	}
 2426: 	if (scalar(@good_collaborators) != 0) {
 2427: 	    $result.='<br />'.&mt('Collaborators: ');
 2428: 	    foreach my $name (@good_collaborators) {
 2429: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2430: 		push(@col_fullnames, $givenn.' '.$lastname);
 2431: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2432: 	    }
 2433: 	    $result.='<br />'."\n";
 2434: 	    my ($part)=split(/\./,$part);
 2435: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2436: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2437: 		"\n";
 2438: 	}
 2439: 	if (scalar(@bad_collaborators) > 0) {
 2440: 	    $result.='<div class="LC_warning">';
 2441: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2442: 	    $result .= '</div>';
 2443: 	}         
 2444: 	if (scalar(@bad_collaborators > $ncol)) {
 2445: 	    $result .= '<div class="LC_warning">';
 2446: 	    $result .= &mt('This student has submitted too many '.
 2447: 		'collaborators.  Maximum is [_1].',$ncol);
 2448: 	    $result .= '</div>';
 2449: 	}
 2450:     }
 2451:     return ($result,$fullname,\@col_fullnames);
 2452: }
 2453: 
 2454: #--- Retrieve the last submission for all the parts
 2455: sub get_last_submission {
 2456:     my ($returnhash)=@_;
 2457:     my (@string,$timestamp);
 2458:     if ($$returnhash{'version'}) {
 2459: 	my %lasthash=();
 2460: 	my ($version);
 2461: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2462: 	    foreach my $key (sort(split(/\:/,
 2463: 					$$returnhash{$version.':keys'}))) {
 2464: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2465: 		$timestamp = 
 2466: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2467: 	    }
 2468: 	}
 2469: 	foreach my $key (keys(%lasthash)) {
 2470: 	    next if ($key !~ /\.submission$/);
 2471: 
 2472: 	    my ($partid,$foo) = split(/submission$/,$key);
 2473: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2474: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2475: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2476: 	}
 2477:     }
 2478:     if (!@string) {
 2479: 	$string[0] =
 2480: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2481:     }
 2482:     return (\@string,\$timestamp);
 2483: }
 2484: 
 2485: #--- High light keywords, with style choosen by user.
 2486: sub keywords_highlight {
 2487:     my $string    = shift;
 2488:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2489:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2490:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2491:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2492:     foreach my $keyword (@keylist) {
 2493: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2494:     }
 2495:     return $string;
 2496: }
 2497: 
 2498: #--- Called from submission routine
 2499: sub processHandGrade {
 2500:     my ($request) = shift;
 2501:     my $symb   = &get_symb($request);
 2502:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2503:     my $button = $env{'form.gradeOpt'};
 2504:     my $ngrade = $env{'form.NCT'};
 2505:     my $ntstu  = $env{'form.NTSTU'};
 2506:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2507:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2508: 
 2509:     if ($button eq 'Save & Next') {
 2510: 	my $ctr = 0;
 2511: 	while ($ctr < $ngrade) {
 2512: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2513: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2514: 	    if ($errorflag eq 'no_score') {
 2515: 		$ctr++;
 2516: 		next;
 2517: 	    }
 2518: 	    if ($errorflag eq 'not_allowed') {
 2519: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2520: 		$ctr++;
 2521: 		next;
 2522: 	    }
 2523: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2524: 	    my ($subject,$message,$msgstatus) = ('','','');
 2525: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2526:             my ($feedurl,$showsymb) =
 2527: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2528: 	    my $messagetail;
 2529: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2530: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2531: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2532: 		$subject.=' ['.$restitle.']';
 2533: 		my (@msgnum) = split(/,/,$includemsg);
 2534: 		foreach (@msgnum) {
 2535: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2536: 		}
 2537: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2538: 		if ($env{'form.withgrades'.$ctr}) {
 2539: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2540: 		    $messagetail = " for <a href=\"".
 2541: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2542: 		}
 2543: 		$msgstatus = 
 2544:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2545: 						     $message.$messagetail,
 2546:                                                      undef,$feedurl,undef,
 2547:                                                      undef,undef,$showsymb,
 2548:                                                      $restitle);
 2549: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2550: 				$msgstatus);
 2551: 	    }
 2552: 	    if ($env{'form.collaborator'.$ctr}) {
 2553: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2554: 		foreach my $collabstr (@collabstrs) {
 2555: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2556: 		    foreach my $collaborator (@collaborators) {
 2557: 			my ($errorflag,$pts,$wgt) = 
 2558: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2559: 					   $env{'form.unamedom'.$ctr},$part);
 2560: 			if ($errorflag eq 'not_allowed') {
 2561: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2562: 			    next;
 2563: 			} elsif ($message ne '') {
 2564: 			    my ($baseurl,$showsymb) = 
 2565: 				&get_feedurl_and_symb($symb,$collaborator,
 2566: 						      $udom);
 2567: 			    if ($env{'form.withgrades'.$ctr}) {
 2568: 				$messagetail = " for <a href=\"".
 2569:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2570: 			    }
 2571: 			    $msgstatus = 
 2572: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2573: 			}
 2574: 		    }
 2575: 		}
 2576: 	    }
 2577: 	    $ctr++;
 2578: 	}
 2579:     }
 2580: 
 2581:     if ($env{'form.handgrade'} eq 'yes') {
 2582: 	# Keywords sorted in alphabatical order
 2583: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2584: 	my %keyhash = ();
 2585: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2586: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2587: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2588: 	$env{'form.keywords'} = join(' ',@keywords);
 2589: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2590: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2591: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2592: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2593: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2594: 
 2595: 	# message center - Order of message gets changed. Blank line is eliminated.
 2596: 	# New messages are saved in env for the next student.
 2597: 	# All messages are saved in nohist_handgrade.db
 2598: 	my ($ctr,$idx) = (1,1);
 2599: 	while ($ctr <= $env{'form.savemsgN'}) {
 2600: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2601: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2602: 		$idx++;
 2603: 	    }
 2604: 	    $ctr++;
 2605: 	}
 2606: 	$ctr = 0;
 2607: 	while ($ctr < $ngrade) {
 2608: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2609: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2610: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2611: 		$idx++;
 2612: 	    }
 2613: 	    $ctr++;
 2614: 	}
 2615: 	$env{'form.savemsgN'} = --$idx;
 2616: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2617: 	my $putresult = &Apache::lonnet::put
 2618: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2619:     }
 2620:     # Called by Save & Refresh from Highlight Attribute Window
 2621:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2622:     if ($env{'form.refresh'} eq 'on') {
 2623: 	my ($ctr,$total) = (0,0);
 2624: 	while ($ctr < $ngrade) {
 2625: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2626: 	    $ctr++;
 2627: 	}
 2628: 	$env{'form.NTSTU'}=$ngrade;
 2629: 	$ctr = 0;
 2630: 	while ($ctr < $total) {
 2631: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2632: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2633: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2634: 	    &submission($request,$ctr,$total-1);
 2635: 	    $ctr++;
 2636: 	}
 2637: 	return '';
 2638:     }
 2639: 
 2640: # Go directly to grade student - from submission or link from chart page
 2641:     if ($button eq 'Grade Student') {
 2642: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2643: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2644: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2645: 	$env{'form.fullname'} = $$fullname{$processUser};
 2646: 	&submission($request,0,0);
 2647: 	return '';
 2648:     }
 2649: 
 2650:     # Get the next/previous one or group of students
 2651:     my $firststu = $env{'form.unamedom0'};
 2652:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2653:     my $ctr = 2;
 2654:     while ($laststu eq '') {
 2655: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2656: 	$ctr++;
 2657: 	$laststu = $firststu if ($ctr > $ngrade);
 2658:     }
 2659: 
 2660:     my (@parsedlist,@nextlist);
 2661:     my ($nextflg) = 0;
 2662:     foreach my $item (sort 
 2663: 	     {
 2664: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2665: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2666: 		 }
 2667: 		 return $a cmp $b;
 2668: 	     } (keys(%$fullname))) {
 2669: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2670: 	    push(@parsedlist,$item);
 2671: 	}
 2672: 	$nextflg = 1 if ($item eq $laststu);
 2673: 	if ($button eq 'Previous') {
 2674: 	    last if ($item eq $firststu);
 2675: 	    push(@parsedlist,$item);
 2676: 	}
 2677:     }
 2678:     $ctr = 0;
 2679:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2680:     my $res_error;
 2681:     my ($partlist) = &response_type($symb,\$res_error);
 2682:     if ($res_error) {
 2683:         $request->print(&navmap_errormsg());
 2684:         return;
 2685:     }
 2686:     foreach my $student (@parsedlist) {
 2687: 	my $submitonly=$env{'form.submitonly'};
 2688: 	my ($uname,$udom) = split(/:/,$student);
 2689: 	
 2690: 	if ($submitonly eq 'queued') {
 2691: 	    my %queue_status = 
 2692: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2693: 							$udom,$uname);
 2694: 	    next if (!defined($queue_status{'gradingqueue'}));
 2695: 	}
 2696: 
 2697: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2698: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2699: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2700: 	    my $submitted = 0;
 2701: 	    my $ungraded = 0;
 2702: 	    my $incorrect = 0;
 2703: 	    foreach my $item (keys(%status)) {
 2704: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2705: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2706: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2707: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2708: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2709: 		    $submitted = 0;
 2710: 		}
 2711: 	    }
 2712: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2713: 				     $submitonly eq 'incorrect' ||
 2714: 				     $submitonly eq 'graded'));
 2715: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2716: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2717: 	}
 2718: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2719: 	last if ($ctr == $ntstu);
 2720: 	$ctr++;
 2721:     }
 2722: 
 2723:     $ctr = 0;
 2724:     my $total = scalar(@nextlist)-1;
 2725: 
 2726:     foreach (sort(@nextlist)) {
 2727: 	my ($uname,$udom,$submitter) = split(/:/);
 2728: 	$env{'form.student'}  = $uname;
 2729: 	$env{'form.userdom'}  = $udom;
 2730: 	$env{'form.fullname'} = $$fullname{$_};
 2731: 	&submission($request,$ctr,$total);
 2732: 	$ctr++;
 2733:     }
 2734:     if ($total < 0) {
 2735: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2736: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2737: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2738: 	$the_end.=&show_grading_menu_form($symb);
 2739: 	$request->print($the_end);
 2740:     }
 2741:     return '';
 2742: }
 2743: 
 2744: #---- Save the score and award for each student, if changed
 2745: sub saveHandGrade {
 2746:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2747:     my @version_parts;
 2748:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2749: 					   $env{'request.course.id'});
 2750:     if (!&canmodify($usec)) { return('not_allowed'); }
 2751:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2752:     my @parts_graded;
 2753:     my %newrecord  = ();
 2754:     my ($pts,$wgt) = ('','');
 2755:     my %aggregate = ();
 2756:     my $aggregateflag = 0;
 2757:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2758:     foreach my $new_part (@parts) {
 2759: 	#collaborator ($submi may vary for different parts
 2760: 	if ($submitter && $new_part ne $part) { next; }
 2761: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2762: 	if ($dropMenu eq 'excused') {
 2763: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2764: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2765: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2766: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2767: 		}
 2768: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2769: 	    }
 2770: 	} elsif ($dropMenu eq 'reset status'
 2771: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2772: 	    foreach my $key (keys(%record)) {
 2773: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2774: 	    }
 2775: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2776: 		"$env{'user.name'}:$env{'user.domain'}";
 2777:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2778: 
 2779:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2780: 					       [$new_part]);
 2781:             my $aggtries =$totaltries;
 2782:             if ($last_resets{$new_part}) {
 2783:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2784: 					   $new_part);
 2785:             }
 2786: 
 2787:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2788:             if ($aggtries > 0) {
 2789:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2790:                 $aggregateflag = 1;
 2791:             }
 2792: 	} elsif ($dropMenu eq '') {
 2793: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2794: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2795: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2796: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2797: 		next;
 2798: 	    }
 2799: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2800: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2801: 	    my $partial= $pts/$wgt;
 2802: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2803: 		#do not update score for part if not changed.
 2804:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2805: 		next;
 2806: 	    } else {
 2807: 	        push(@parts_graded,$new_part);
 2808: 	    }
 2809: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2810: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2811: 	    }
 2812: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2813: 	    if ($partial == 0) {
 2814: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2815: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2816: 		}
 2817: 	    } else {
 2818: 		if ($record{$reckey} ne 'correct_by_override') {
 2819: 		    $newrecord{$reckey} = 'correct_by_override';
 2820: 		}
 2821: 	    }	    
 2822: 	    if ($submitter && 
 2823: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2824: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2825: 	    }
 2826: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2827: 		"$env{'user.name'}:$env{'user.domain'}";
 2828: 	}
 2829: 	# unless problem has been graded, set flag to version the submitted files
 2830: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2831: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2832: 	        $dropMenu eq 'reset status')
 2833: 	   {
 2834: 	    push(@version_parts,$new_part);
 2835: 	}
 2836:     }
 2837:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2838:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2839: 
 2840:     if (%newrecord) {
 2841:         if (@version_parts) {
 2842:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2843:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2844: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2845: 	    foreach my $new_part (@version_parts) {
 2846: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2847: 				$new_part,\%newrecord);
 2848: 	    }
 2849:         }
 2850: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2851: 				$env{'request.course.id'},$domain,$stuname);
 2852: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2853: 				     $cdom,$cnum,$domain,$stuname);
 2854:     }
 2855:     if ($aggregateflag) {
 2856:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2857: 			      $cdom,$cnum);
 2858:     }
 2859:     return ('',$pts,$wgt);
 2860: }
 2861: 
 2862: sub check_and_remove_from_queue {
 2863:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2864:     my @ungraded_parts;
 2865:     foreach my $part (@{$parts}) {
 2866: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2867: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2868: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2869: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2870: 		) {
 2871: 	    push(@ungraded_parts, $part);
 2872: 	}
 2873:     }
 2874:     if ( !@ungraded_parts ) {
 2875: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2876: 					       $cnum,$domain,$stuname);
 2877:     }
 2878: }
 2879: 
 2880: sub handback_files {
 2881:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2882:     my $portfolio_root = '/userfiles/portfolio';
 2883:     my $res_error;
 2884:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2885:     if ($res_error) {
 2886:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2887:         return;
 2888:     }
 2889:     my @part_response_id = &flatten_responseType($responseType);
 2890:     foreach my $part_response_id (@part_response_id) {
 2891:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2892: 	my $part_resp = join('_',@{ $part_response_id });
 2893:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2894:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2895:                 my $file_counter = 1;
 2896: 		my $file_msg;
 2897:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2898:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2899:                     my ($directory,$answer_file) = 
 2900:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2901:                     my ($answer_name,$answer_ver,$answer_ext) =
 2902: 		        &file_name_version_ext($answer_file);
 2903: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2904:                     my $getpropath = 1;
 2905: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2906: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2907:                     # fix file name
 2908:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2909:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2910:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2911:             	                                $save_file_name);
 2912:                     if ($result !~ m|^/uploaded/|) {
 2913:                         $request->print('<br /><span class="LC_error">'.
 2914:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2915:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2916:                                         '</span>');
 2917:                     } else {
 2918:                         # mark the file as read only
 2919:                         my @files = ($save_file_name);
 2920:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2921:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2922: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2923: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2924: 			}
 2925:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2926: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2927: 
 2928:                     }
 2929:                     $request->print("<br />".$fname." will be the uploaded file name");
 2930:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2931:                     $file_counter++;
 2932:                 }
 2933: 		my $subject = "File Handed Back by Instructor ";
 2934: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2935: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2936: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2937: 		$message .= " and can be found in your portfolio space.";
 2938: 		my ($feedurl,$showsymb) = 
 2939: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2940:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2941: 		my $msgstatus = 
 2942:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2943: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2944:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2945:             }
 2946:         }
 2947:     return;
 2948: }
 2949: 
 2950: sub get_feedurl_and_symb {
 2951:     my ($symb,$uname,$udom) = @_;
 2952:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2953:     $url = &Apache::lonnet::clutter($url);
 2954:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2955: 					$symb,$udom,$uname);
 2956:     if ($encrypturl =~ /^yes$/i) {
 2957: 	&Apache::lonenc::encrypted(\$url,1);
 2958: 	&Apache::lonenc::encrypted(\$symb,1);
 2959:     }
 2960:     return ($url,$symb);
 2961: }
 2962: 
 2963: sub get_submitted_files {
 2964:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2965:     my @files;
 2966:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2967:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2968:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2969:     	    push(@files,$file_url.$file);
 2970:         }
 2971:     }
 2972:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2973:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2974:     }
 2975:     return (\@files);
 2976: }
 2977: 
 2978: # ----------- Provides number of tries since last reset.
 2979: sub get_num_tries {
 2980:     my ($record,$last_reset,$part) = @_;
 2981:     my $timestamp = '';
 2982:     my $num_tries = 0;
 2983:     if ($$record{'version'}) {
 2984:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2985:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2986:                 $timestamp = $$record{$version.':timestamp'};
 2987:                 if ($timestamp > $last_reset) {
 2988:                     $num_tries ++;
 2989:                 } else {
 2990:                     last;
 2991:                 }
 2992:             }
 2993:         }
 2994:     }
 2995:     return $num_tries;
 2996: }
 2997: 
 2998: # ----------- Determine decrements required in aggregate totals 
 2999: sub decrement_aggs {
 3000:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3001:     my %decrement = (
 3002:                         attempts => 0,
 3003:                         users => 0,
 3004:                         correct => 0
 3005:                     );
 3006:     $decrement{'attempts'} = $aggtries;
 3007:     if ($solvedstatus =~ /^correct/) {
 3008:         $decrement{'correct'} = 1;
 3009:     }
 3010:     if ($aggtries == $totaltries) {
 3011:         $decrement{'users'} = 1;
 3012:     }
 3013:     foreach my $type (keys(%decrement)) {
 3014:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3015:     }
 3016:     return;
 3017: }
 3018: 
 3019: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3020: sub get_last_resets {
 3021:     my ($symb,$courseid,$partids) =@_;
 3022:     my %last_resets;
 3023:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3024:     my $cname = $env{'course.'.$courseid.'.num'};
 3025:     my @keys;
 3026:     foreach my $part (@{$partids}) {
 3027: 	push(@keys,"$symb\0$part\0resettime");
 3028:     }
 3029:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3030: 				     $cdom,$cname);
 3031:     foreach my $part (@{$partids}) {
 3032: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3033:     }
 3034:     return %last_resets;
 3035: }
 3036: 
 3037: # ----------- Handles creating versions for portfolio files as answers
 3038: sub version_portfiles {
 3039:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3040:     my $version_parts = join('|',@$v_flag);
 3041:     my @returned_keys;
 3042:     my $parts = join('|', @$parts_graded);
 3043:     my $portfolio_root = '/userfiles/portfolio';
 3044:     foreach my $key (keys(%$record)) {
 3045:         my $new_portfiles;
 3046:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3047:             my @versioned_portfiles;
 3048:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3049:             foreach my $file (@portfiles) {
 3050:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3051:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3052: 		my ($answer_name,$answer_ver,$answer_ext) =
 3053: 		    &file_name_version_ext($answer_file);
 3054:                 my $getpropath = 1;    
 3055:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3056:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3057:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3058:                 if ($new_answer ne 'problem getting file') {
 3059:                     push(@versioned_portfiles, $directory.$new_answer);
 3060:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3061:                         [$directory.$new_answer],
 3062:                         [$symb,$env{'request.course.id'},'graded']);
 3063:                 }
 3064:             }
 3065:             $$record{$key} = join(',',@versioned_portfiles);
 3066:             push(@returned_keys,$key);
 3067:         }
 3068:     } 
 3069:     return (@returned_keys);   
 3070: }
 3071: 
 3072: sub get_next_version {
 3073:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3074:     my $version;
 3075:     foreach my $row (@$dir_list) {
 3076:         my ($file) = split(/\&/,$row,2);
 3077:         my ($file_name,$file_version,$file_ext) =
 3078: 	    &file_name_version_ext($file);
 3079:         if (($file_name eq $answer_name) && 
 3080: 	    ($file_ext eq $answer_ext)) {
 3081:                 # gets here if filename and extension match, regardless of version
 3082:                 if ($file_version ne '') {
 3083:                 # a versioned file is found  so save it for later
 3084:                 if ($file_version > $version) {
 3085: 		    $version = $file_version;
 3086: 	        }
 3087:             }
 3088:         }
 3089:     } 
 3090:     $version ++;
 3091:     return($version);
 3092: }
 3093: 
 3094: sub version_selected_portfile {
 3095:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3096:     my ($answer_name,$answer_ver,$answer_ext) =
 3097:         &file_name_version_ext($file_name);
 3098:     my $new_answer;
 3099:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3100:     if($env{'form.copy'} eq '-1') {
 3101:         $new_answer = 'problem getting file';
 3102:     } else {
 3103:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3104:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3105:                             $stu_name,$domain,'copy',
 3106: 		        '/portfolio'.$directory.$new_answer);
 3107:     }    
 3108:     return ($new_answer);
 3109: }
 3110: 
 3111: sub file_name_version_ext {
 3112:     my ($file)=@_;
 3113:     my @file_parts = split(/\./, $file);
 3114:     my ($name,$version,$ext);
 3115:     if (@file_parts > 1) {
 3116: 	$ext=pop(@file_parts);
 3117: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3118: 	    $version=pop(@file_parts);
 3119: 	}
 3120: 	$name=join('.',@file_parts);
 3121:     } else {
 3122: 	$name=join('.',@file_parts);
 3123:     }
 3124:     return($name,$version,$ext);
 3125: }
 3126: 
 3127: #--------------------------------------------------------------------------------------
 3128: #
 3129: #-------------------------- Next few routines handles grading by section or whole class
 3130: #
 3131: #--- Javascript to handle grading by section or whole class
 3132: sub viewgrades_js {
 3133:     my ($request) = shift;
 3134: 
 3135:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3136:     $request->print(<<VIEWJAVASCRIPT);
 3137: <script type="text/javascript" language="javascript">
 3138:    function writePoint(partid,weight,point) {
 3139: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3140: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3141: 	if (point == "textval") {
 3142: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3143: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3144: 		alert("$alertmsg"+parseFloat(point));
 3145: 		var resetbox = false;
 3146: 		for (var i=0; i<radioButton.length; i++) {
 3147: 		    if (radioButton[i].checked) {
 3148: 			textbox.value = i;
 3149: 			resetbox = true;
 3150: 		    }
 3151: 		}
 3152: 		if (!resetbox) {
 3153: 		    textbox.value = "";
 3154: 		}
 3155: 		return;
 3156: 	    }
 3157: 	    if (parseFloat(point) > parseFloat(weight)) {
 3158: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3159: 				   ") greater than the weight for the part. Accept?");
 3160: 		if (resp == false) {
 3161: 		    textbox.value = "";
 3162: 		    return;
 3163: 		}
 3164: 	    }
 3165: 	    for (var i=0; i<radioButton.length; i++) {
 3166: 		radioButton[i].checked=false;
 3167: 		if (parseFloat(point) == i) {
 3168: 		    radioButton[i].checked=true;
 3169: 		}
 3170: 	    }
 3171: 
 3172: 	} else {
 3173: 	    textbox.value = parseFloat(point);
 3174: 	}
 3175: 	for (i=0;i<document.classgrade.total.value;i++) {
 3176: 	    var user = document.classgrade["ctr"+i].value;
 3177: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3178: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3179: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3180: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3181: 	    if (saveval != "correct") {
 3182: 		scorename.value = point;
 3183: 		if (selname[0].selected != true) {
 3184: 		    selname[0].selected = true;
 3185: 		}
 3186: 	    }
 3187: 	}
 3188: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3189:     }
 3190: 
 3191:     function writeRadText(partid,weight) {
 3192: 	var selval   = document.classgrade["SELVAL_"+partid];
 3193: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3194:         var override = document.classgrade["FORCE_"+partid].checked;
 3195: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3196: 	if (selval[1].selected || selval[2].selected) {
 3197: 	    for (var i=0; i<radioButton.length; i++) {
 3198: 		radioButton[i].checked=false;
 3199: 
 3200: 	    }
 3201: 	    textbox.value = "";
 3202: 
 3203: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3204: 		var user = document.classgrade["ctr"+i].value;
 3205: 		user = user.replace(new RegExp(':', 'g'),"_");
 3206: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3207: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3208: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3209: 		if ((saveval != "correct") || override) {
 3210: 		    scorename.value = "";
 3211: 		    if (selval[1].selected) {
 3212: 			selname[1].selected = true;
 3213: 		    } else {
 3214: 			selname[2].selected = true;
 3215: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3216: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3217: 		    }
 3218: 		}
 3219: 	    }
 3220: 	} else {
 3221: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3222: 		var user = document.classgrade["ctr"+i].value;
 3223: 		user = user.replace(new RegExp(':', 'g'),"_");
 3224: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3225: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3226: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3227: 		if ((saveval != "correct") || override) {
 3228: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3229: 		    selname[0].selected = true;
 3230: 		}
 3231: 	    }
 3232: 	}	    
 3233:     }
 3234: 
 3235:     function changeSelect(partid,user) {
 3236: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3237: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3238: 	var point  = textbox.value;
 3239: 	var weight = document.classgrade["weight_"+partid].value;
 3240: 
 3241: 	if (isNaN(point) || parseFloat(point) < 0) {
 3242: 	    alert("$alertmsg"+parseFloat(point));
 3243: 	    textbox.value = "";
 3244: 	    return;
 3245: 	}
 3246: 	if (parseFloat(point) > parseFloat(weight)) {
 3247: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3248: 			       ") greater than the weight of the part. Accept?");
 3249: 	    if (resp == false) {
 3250: 		textbox.value = "";
 3251: 		return;
 3252: 	    }
 3253: 	}
 3254: 	selval[0].selected = true;
 3255:     }
 3256: 
 3257:     function changeOneScore(partid,user) {
 3258: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3259: 	if (selval[1].selected || selval[2].selected) {
 3260: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3261: 	    if (selval[2].selected) {
 3262: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3263: 	    }
 3264:         }
 3265:     }
 3266: 
 3267:     function resetEntry(numpart) {
 3268: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3269: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3270: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3271: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3272: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3273: 	    for (var i=0; i<radioButton.length; i++) {
 3274: 		radioButton[i].checked=false;
 3275: 
 3276: 	    }
 3277: 	    textbox.value = "";
 3278: 	    selval[0].selected = true;
 3279: 
 3280: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3281: 		var user = document.classgrade["ctr"+i].value;
 3282: 		user = user.replace(new RegExp(':', 'g'),"_");
 3283: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3284: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3285: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3286: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3287: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3288: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3289: 		if (saveselval == "excused") {
 3290: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3291: 		} else {
 3292: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3293: 		}
 3294: 	    }
 3295: 	}
 3296:     }
 3297: 
 3298: </script>
 3299: VIEWJAVASCRIPT
 3300: }
 3301: 
 3302: #--- show scores for a section or whole class w/ option to change/update a score
 3303: sub viewgrades {
 3304:     my ($request) = shift;
 3305:     &viewgrades_js($request);
 3306: 
 3307:     my ($symb) = &get_symb($request);
 3308:     #need to make sure we have the correct data for later EXT calls, 
 3309:     #thus invalidate the cache
 3310:     &Apache::lonnet::devalidatecourseresdata(
 3311:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3312:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3313:     &Apache::lonnet::clear_EXT_cache_status();
 3314: 
 3315:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3316:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3317: 
 3318:     #view individual student submission form - called using Javascript viewOneStudent
 3319:     $result.=&jscriptNform($symb);
 3320: 
 3321:     #beginning of class grading form
 3322:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3323:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3324: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3325: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3326: 	&build_section_inputs().
 3327: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3328: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3329: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3330: 
 3331:     my ($common_header,$specific_header);
 3332:     if ($env{'form.section'} eq 'all') {
 3333: 	$common_header = &mt('Assign Common Grade to Class');
 3334:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3335:     } elsif ($env{'form.section'} eq 'none') {
 3336:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3337: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3338:     } else {
 3339:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3340:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3341: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3342:     }
 3343:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3344:     #radio buttons/text box for assigning points for a section or class.
 3345:     #handles different parts of a problem
 3346:     my $res_error;
 3347:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3348:     if ($res_error) {
 3349:         return &navmap_errormsg();
 3350:     }
 3351:     my %weight = ();
 3352:     my $ctsparts = 0;
 3353:     my %seen = ();
 3354:     my @part_response_id = &flatten_responseType($responseType);
 3355:     foreach my $part_response_id (@part_response_id) {
 3356:     	my ($partid,$respid) = @{ $part_response_id };
 3357: 	my $part_resp = join('_',@{ $part_response_id });
 3358: 	next if $seen{$partid};
 3359: 	$seen{$partid}++;
 3360: 	my $handgrade=$$handgrade{$part_resp};
 3361: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3362: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3363: 
 3364: 	my $display_part=&get_display_part($partid,$symb);
 3365: 	my $radio.='<table border="0"><tr>';  
 3366: 	my $ctr = 0;
 3367: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3368: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3369: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3370: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3371: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3372: 	    $ctr++;
 3373: 	}
 3374: 	$radio.='</tr></table>';
 3375: 	my $line = '<input type="text" name="TEXTVAL_'.
 3376: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3377: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3378: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3379: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3380: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3381: 		$weight{$partid}.')"> '.
 3382: 	    '<option selected="selected"> </option>'.
 3383: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3384: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3385: 	    '</select></td>'.
 3386:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3387: 	$line.='<input type="hidden" name="partid_'.
 3388: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3389: 	$line.='<input type="hidden" name="weight_'.
 3390: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3391: 
 3392: 	$result.=
 3393: 	    &Apache::loncommon::start_data_table_row()."\n".
 3394: 	    '<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>'.
 3395: 	    &Apache::loncommon::end_data_table_row()."\n";
 3396: 	$ctsparts++;
 3397:     }
 3398:     $result.=&Apache::loncommon::end_data_table()."\n".
 3399: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3400:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3401: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3402: 
 3403:     #table listing all the students in a section/class
 3404:     #header of table
 3405:     $result.= '<h3>'.$specific_header.'</h3>'.
 3406:               &Apache::loncommon::start_data_table().
 3407: 	      &Apache::loncommon::start_data_table_header_row().
 3408: 	      '<th>'.&mt('No.').'</th>'.
 3409: 	      '<th>'.&nameUserString('header')."</th>\n";
 3410:     my $partserror;
 3411:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3412:     if ($partserror) {
 3413:         return &navmap_errormsg();
 3414:     }
 3415:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3416:     my @partids = ();
 3417:     foreach my $part (@parts) {
 3418: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3419:         my $narrowtext = &mt('Tries');
 3420: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3421: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3422: 	my ($partid) = &split_part_type($part);
 3423:         push(@partids,$partid);
 3424: 	my $display_part=&get_display_part($partid,$symb);
 3425: 	if ($display =~ /^Partial Credit Factor/) {
 3426: 	    $result.='<th>'.
 3427: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3428: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3429: 	    next;
 3430: 	    
 3431: 	} else {
 3432: 	    if ($display =~ /Problem Status/) {
 3433: 		my $grade_status_mt = &mt('Grade Status');
 3434: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3435: 	    }
 3436: 	    my $part_mt = &mt('Part:');
 3437: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3438: 	}
 3439: 
 3440: 	$result.='<th>'.$display.'</th>'."\n";
 3441:     }
 3442:     $result.=&Apache::loncommon::end_data_table_header_row();
 3443: 
 3444:     my %last_resets = 
 3445: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3446: 
 3447:     #get info for each student
 3448:     #list all the students - with points and grade status
 3449:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3450:     my $ctr = 0;
 3451:     foreach (sort 
 3452: 	     {
 3453: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3454: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3455: 		 }
 3456: 		 return $a cmp $b;
 3457: 	     } (keys(%$fullname))) {
 3458: 	$ctr++;
 3459: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3460: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3461:     }
 3462:     $result.=&Apache::loncommon::end_data_table();
 3463:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3464:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3465: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3466:     if (scalar(%$fullname) eq 0) {
 3467: 	my $colspan=3+scalar(@parts);
 3468: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3469:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3470: 	$result='<span class="LC_warning">'.
 3471: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3472: 	        $section_display, $stu_status).
 3473: 	    '</span>';
 3474:     }
 3475:     $result.=&show_grading_menu_form($symb);
 3476:     return $result;
 3477: }
 3478: 
 3479: #--- call by previous routine to display each student
 3480: sub viewstudentgrade {
 3481:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3482:     my ($uname,$udom) = split(/:/,$student);
 3483:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3484:     my %aggregates = (); 
 3485:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3486: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3487: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3488: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3489: 	'\');" target="_self">'.$fullname.'</a> '.
 3490: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3491:     $student=~s/:/_/; # colon doen't work in javascript for names
 3492:     foreach my $apart (@$parts) {
 3493: 	my ($part,$type) = &split_part_type($apart);
 3494: 	my $score=$record{"resource.$part.$type"};
 3495:         $result.='<td align="center">';
 3496:         my ($aggtries,$totaltries);
 3497:         unless (exists($aggregates{$part})) {
 3498: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3499: 
 3500: 	    $aggtries = $totaltries;
 3501:             if ($$last_resets{$part}) {  
 3502:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3503: 					   $part);
 3504:             }
 3505:             $result.='<input type="hidden" name="'.
 3506:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3507:             $result.='<input type="hidden" name="'.
 3508:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3509:             $aggregates{$part} = 1;
 3510:         }
 3511: 	if ($type eq 'awarded') {
 3512: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3513: 	    $result.='<input type="hidden" name="'.
 3514: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3515: 	    $result.='<input type="text" name="'.
 3516: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3517:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3518: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3519: 	} elsif ($type eq 'solved') {
 3520: 	    my ($status,$foo)=split(/_/,$score,2);
 3521: 	    $status = 'nothing' if ($status eq '');
 3522: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3523: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3524: 	    $result.='&nbsp;<select name="'.
 3525: 		'GD_'.$student.'_'.$part.'_solved" '.
 3526:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3527: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3528: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3529: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3530: 	    $result.="</select>&nbsp;</td>\n";
 3531: 	} else {
 3532: 	    $result.='<input type="hidden" name="'.
 3533: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3534: 		    "\n";
 3535: 	    $result.='<input type="text" name="'.
 3536: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3537: 		'value="'.$score.'" size="4" /></td>'."\n";
 3538: 	}
 3539:     }
 3540:     $result.=&Apache::loncommon::end_data_table_row();
 3541:     return $result;
 3542: }
 3543: 
 3544: #--- change scores for all the students in a section/class
 3545: #    record does not get update if unchanged
 3546: sub editgrades {
 3547:     my ($request) = @_;
 3548: 
 3549:     my $symb=&get_symb($request);
 3550:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3551:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3552:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3553:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3554: 
 3555:     my $result= &Apache::loncommon::start_data_table().
 3556: 	&Apache::loncommon::start_data_table_header_row().
 3557: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3558: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3559:     my %scoreptr = (
 3560: 		    'correct'  =>'correct_by_override',
 3561: 		    'incorrect'=>'incorrect_by_override',
 3562: 		    'excused'  =>'excused',
 3563: 		    'ungraded' =>'ungraded_attempted',
 3564: 		    'nothing'  => '',
 3565: 		    );
 3566:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3567: 
 3568:     my (@partid);
 3569:     my %weight = ();
 3570:     my %columns = ();
 3571:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3572: 
 3573:     my $partserror;
 3574:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3575:     if ($partserror) {
 3576:         return &navmap_errormsg();
 3577:     }
 3578:     my $header;
 3579:     while ($ctr < $env{'form.totalparts'}) {
 3580: 	my $partid = $env{'form.partid_'.$ctr};
 3581: 	push(@partid,$partid);
 3582: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3583: 	$ctr++;
 3584:     }
 3585:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3586:     foreach my $partid (@partid) {
 3587: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3588: 	    '<th align="center">'.&mt('New Score').'</th>';
 3589: 	$columns{$partid}=2;
 3590: 	foreach my $stores (@parts) {
 3591: 	    my ($part,$type) = &split_part_type($stores);
 3592: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3593: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3594: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3595: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3596:             my $narrowtext = &mt('Tries');
 3597: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3598: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3599: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3600: 	    $columns{$partid}+=2;
 3601: 	}
 3602:     }
 3603:     foreach my $partid (@partid) {
 3604: 	my $display_part=&get_display_part($partid,$symb);
 3605: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3606: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3607: 	    '</th>';
 3608: 
 3609:     }
 3610:     $result .= &Apache::loncommon::end_data_table_header_row().
 3611: 	&Apache::loncommon::start_data_table_header_row().
 3612: 	$header.
 3613: 	&Apache::loncommon::end_data_table_header_row();
 3614:     my @noupdate;
 3615:     my ($updateCtr,$noupdateCtr) = (1,1);
 3616:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3617: 	my $line;
 3618: 	my $user = $env{'form.ctr'.$i};
 3619: 	my ($uname,$udom)=split(/:/,$user);
 3620: 	my %newrecord;
 3621: 	my $updateflag = 0;
 3622: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3623: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3624: 	if (!&canmodify($usec)) {
 3625: 	    my $numcols=scalar(@partid)*4+2;
 3626: 	    push(@noupdate,
 3627: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3628: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3629: 	    next;
 3630: 	}
 3631:         my %aggregate = ();
 3632:         my $aggregateflag = 0;
 3633: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3634: 	foreach (@partid) {
 3635: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3636: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3637: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3638: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3639: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3640: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3641: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3642: 	    my $score;
 3643: 	    if ($partial eq '') {
 3644: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3645: 	    } elsif ($partial > 0) {
 3646: 		$score = 'correct_by_override';
 3647: 	    } elsif ($partial == 0) {
 3648: 		$score = 'incorrect_by_override';
 3649: 	    }
 3650: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3651: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3652: 
 3653: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3654: 		"$env{'user.name'}:$env{'user.domain'}";
 3655: 	    if ($dropMenu eq 'reset status' &&
 3656: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3657: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3658: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3659: 		$newrecord{'resource.'.$_.'.award'} = '';
 3660: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3661: 		$updateflag = 1;
 3662:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3663:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3664:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3665:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3666:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3667:                     $aggregateflag = 1;
 3668:                 }
 3669: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3670: 		$updateflag = 1;
 3671: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3672: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3673: 		$rec_update++;
 3674: 	    }
 3675: 
 3676: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3677: 		'<td align="center">'.$awarded.
 3678: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3679: 
 3680: 
 3681: 	    my $partid=$_;
 3682: 	    foreach my $stores (@parts) {
 3683: 		my ($part,$type) = &split_part_type($stores);
 3684: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3685: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3686: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3687: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3688: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3689: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3690: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3691: 		    $updateflag=1;
 3692: 		}
 3693: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3694: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3695: 	    }
 3696: 	}
 3697: 	$line.="\n";
 3698: 
 3699: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3700: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3701: 
 3702: 	if ($updateflag) {
 3703: 	    $count++;
 3704: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3705: 				    $udom,$uname);
 3706: 
 3707: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3708: 					      $cnum,$udom,$uname)) {
 3709: 		# need to figure out if should be in queue.
 3710: 		my %record =  
 3711: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3712: 					     $udom,$uname);
 3713: 		my $all_graded = 1;
 3714: 		my $none_graded = 1;
 3715: 		foreach my $part (@parts) {
 3716: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3717: 			$all_graded = 0;
 3718: 		    } else {
 3719: 			$none_graded = 0;
 3720: 		    }
 3721: 		}
 3722: 
 3723: 		if ($all_graded || $none_graded) {
 3724: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3725: 							   $symb,$cdom,$cnum,
 3726: 							   $udom,$uname);
 3727: 		}
 3728: 	    }
 3729: 
 3730: 	    $result.=&Apache::loncommon::start_data_table_row().
 3731: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3732: 		&Apache::loncommon::end_data_table_row();
 3733: 	    $updateCtr++;
 3734: 	} else {
 3735: 	    push(@noupdate,
 3736: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3737: 	    $noupdateCtr++;
 3738: 	}
 3739:         if ($aggregateflag) {
 3740:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3741: 				  $cdom,$cnum);
 3742:         }
 3743:     }
 3744:     if (@noupdate) {
 3745: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3746: 	my $numcols=scalar(@partid)*4+2;
 3747: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3748: 	    '<td align="center" colspan="'.$numcols.'">'.
 3749: 	    &mt('No Changes Occurred For the Students Below').
 3750: 	    '</td>'.
 3751: 	    &Apache::loncommon::end_data_table_row();
 3752: 	foreach my $line (@noupdate) {
 3753: 	    $result.=
 3754: 		&Apache::loncommon::start_data_table_row().
 3755: 		$line.
 3756: 		&Apache::loncommon::end_data_table_row();
 3757: 	}
 3758:     }
 3759:     $result .= &Apache::loncommon::end_data_table().
 3760: 	&show_grading_menu_form($symb);
 3761:     my $msg = '<p><b>'.
 3762: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3763: 	    $rec_update,$count).'</b><br />'.
 3764: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3765: 	'</b></p>';
 3766:     return $title.$msg.$result;
 3767: }
 3768: 
 3769: sub split_part_type {
 3770:     my ($partstr) = @_;
 3771:     my ($temp,@allparts)=split(/_/,$partstr);
 3772:     my $type=pop(@allparts);
 3773:     my $part=join('_',@allparts);
 3774:     return ($part,$type);
 3775: }
 3776: 
 3777: #------------- end of section for handling grading by section/class ---------
 3778: #
 3779: #----------------------------------------------------------------------------
 3780: 
 3781: 
 3782: #----------------------------------------------------------------------------
 3783: #
 3784: #-------------------------- Next few routines handles grading by csv upload
 3785: #
 3786: #--- Javascript to handle csv upload
 3787: sub csvupload_javascript_reverse_associate {
 3788:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3789:     my $error2=&mt('You need to specify at least one grading field');
 3790:   return(<<ENDPICK);
 3791:   function verify(vf) {
 3792:     var foundsomething=0;
 3793:     var founduname=0;
 3794:     var foundID=0;
 3795:     for (i=0;i<=vf.nfields.value;i++) {
 3796:       tw=eval('vf.f'+i+'.selectedIndex');
 3797:       if (i==0 && tw!=0) { foundID=1; }
 3798:       if (i==1 && tw!=0) { founduname=1; }
 3799:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3800:     }
 3801:     if (founduname==0 && foundID==0) {
 3802: 	alert('$error1');
 3803: 	return;
 3804:     }
 3805:     if (foundsomething==0) {
 3806: 	alert('$error2');
 3807: 	return;
 3808:     }
 3809:     vf.submit();
 3810:   }
 3811:   function flip(vf,tf) {
 3812:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3813:     var i;
 3814:     for (i=0;i<=vf.nfields.value;i++) {
 3815:       //can not pick the same destination field for both name and domain
 3816:       if (((i ==0)||(i ==1)) && 
 3817:           ((tf==0)||(tf==1)) && 
 3818:           (i!=tf) &&
 3819:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3820:         eval('vf.f'+i+'.selectedIndex=0;')
 3821:       }
 3822:     }
 3823:   }
 3824: ENDPICK
 3825: }
 3826: 
 3827: sub csvupload_javascript_forward_associate {
 3828:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3829:     my $error2=&mt('You need to specify at least one grading field');
 3830:   return(<<ENDPICK);
 3831:   function verify(vf) {
 3832:     var foundsomething=0;
 3833:     var founduname=0;
 3834:     var foundID=0;
 3835:     for (i=0;i<=vf.nfields.value;i++) {
 3836:       tw=eval('vf.f'+i+'.selectedIndex');
 3837:       if (tw==1) { foundID=1; }
 3838:       if (tw==2) { founduname=1; }
 3839:       if (tw>3) { foundsomething=1; }
 3840:     }
 3841:     if (founduname==0 && foundID==0) {
 3842: 	alert('$error1');
 3843: 	return;
 3844:     }
 3845:     if (foundsomething==0) {
 3846: 	alert('$error2');
 3847: 	return;
 3848:     }
 3849:     vf.submit();
 3850:   }
 3851:   function flip(vf,tf) {
 3852:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3853:     var i;
 3854:     //can not pick the same destination field twice
 3855:     for (i=0;i<=vf.nfields.value;i++) {
 3856:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3857:         eval('vf.f'+i+'.selectedIndex=0;')
 3858:       }
 3859:     }
 3860:   }
 3861: ENDPICK
 3862: }
 3863: 
 3864: sub csvuploadmap_header {
 3865:     my ($request,$symb,$datatoken,$distotal)= @_;
 3866:     my $javascript;
 3867:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3868: 	$javascript=&csvupload_javascript_reverse_associate();
 3869:     } else {
 3870: 	$javascript=&csvupload_javascript_forward_associate();
 3871:     }
 3872: 
 3873:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3874:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3875:     my $ignore=&mt('Ignore First Line');
 3876:     $symb = &Apache::lonenc::check_encrypt($symb);
 3877:     $request->print(<<ENDPICK);
 3878: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3879: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3880: $result
 3881: <hr />
 3882: <h3>Identify fields</h3>
 3883: Total number of records found in file: $distotal <hr />
 3884: Enter as many fields as you can. The system will inform you and bring you back
 3885: to this page if the data selected is insufficient to run your class.<hr />
 3886: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3887: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3888: <input type="hidden" name="associate"  value="" />
 3889: <input type="hidden" name="phase"      value="three" />
 3890: <input type="hidden" name="datatoken"  value="$datatoken" />
 3891: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3892: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3893: <input type="hidden" name="upfile_associate" 
 3894:                                        value="$env{'form.upfile_associate'}" />
 3895: <input type="hidden" name="symb"       value="$symb" />
 3896: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3897: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3898: <input type="hidden" name="command"    value="csvuploadoptions" />
 3899: <hr />
 3900: <script type="text/javascript" language="Javascript">
 3901: $javascript
 3902: </script>
 3903: ENDPICK
 3904:     return '';
 3905: 
 3906: }
 3907: 
 3908: sub csvupload_fields {
 3909:     my ($symb,$errorref) = @_;
 3910:     my (@parts) = &getpartlist($symb,$errorref);
 3911:     if (ref($errorref)) {
 3912:         if ($$errorref) {
 3913:             return;
 3914:         }
 3915:     }
 3916: 
 3917:     my @fields=(['ID','Student/Employee ID'],
 3918: 		['username','Student Username'],
 3919: 		['domain','Student Domain']);
 3920:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3921:     foreach my $part (sort(@parts)) {
 3922: 	my @datum;
 3923: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3924: 	my $name=$part;
 3925: 	if  (!$display) { $display = $name; }
 3926: 	@datum=($name,$display);
 3927: 	if ($name=~/^stores_(.*)_awarded/) {
 3928: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3929: 	}
 3930: 	push(@fields,\@datum);
 3931:     }
 3932:     return (@fields);
 3933: }
 3934: 
 3935: sub csvuploadmap_footer {
 3936:     my ($request,$i,$keyfields) =@_;
 3937:     $request->print(<<ENDPICK);
 3938: </table>
 3939: <input type="hidden" name="nfields" value="$i" />
 3940: <input type="hidden" name="keyfields" value="$keyfields" />
 3941: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3942: </form>
 3943: ENDPICK
 3944: }
 3945: 
 3946: sub checkforfile_js {
 3947:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3948:     my $result =<<CSVFORMJS;
 3949: <script type="text/javascript" language="javascript">
 3950:     function checkUpload(formname) {
 3951: 	if (formname.upfile.value == "") {
 3952: 	    alert("$alertmsg");
 3953: 	    return false;
 3954: 	}
 3955: 	formname.submit();
 3956:     }
 3957:     </script>
 3958: CSVFORMJS
 3959:     return $result;
 3960: }
 3961: 
 3962: sub upcsvScores_form {
 3963:     my ($request) = shift;
 3964:     my ($symb)=&get_symb($request);
 3965:     if (!$symb) {return '';}
 3966:     my $result=&checkforfile_js();
 3967:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3968:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3969:     $result.=$table;
 3970:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3971:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3972:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3973: 	'</b></td></tr>'."\n";
 3974:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3975:     my $upload=&mt("Upload Scores");
 3976:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3977:     my $ignore=&mt('Ignore First Line');
 3978:     $symb = &Apache::lonenc::check_encrypt($symb);
 3979:     $result.=<<ENDUPFORM;
 3980: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3981: <input type="hidden" name="symb" value="$symb" />
 3982: <input type="hidden" name="command" value="csvuploadmap" />
 3983: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3984: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3985: $upfile_select
 3986: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3987: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3988: </form>
 3989: ENDUPFORM
 3990:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3991:                            &mt("How do I create a CSV file from a spreadsheet"))
 3992:     .'</td></tr></table>'."\n";
 3993:     $result.='</td></tr></table><br /><br />'."\n";
 3994:     $result.=&show_grading_menu_form($symb);
 3995:     return $result;
 3996: }
 3997: 
 3998: 
 3999: sub csvuploadmap {
 4000:     my ($request)= @_;
 4001:     my ($symb)=&get_symb($request);
 4002:     if (!$symb) {return '';}
 4003: 
 4004:     my $datatoken;
 4005:     if (!$env{'form.datatoken'}) {
 4006: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4007:     } else {
 4008: 	$datatoken=$env{'form.datatoken'};
 4009: 	&Apache::loncommon::load_tmp_file($request);
 4010:     }
 4011:     my @records=&Apache::loncommon::upfile_record_sep();
 4012:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4013:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4014:     my ($i,$keyfields);
 4015:     if (@records) {
 4016:         my $fieldserror;
 4017: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4018:         if ($fieldserror) {
 4019:             $request->print(&navmap_errormsg());
 4020:             return;
 4021:         }
 4022: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4023: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4024: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4025: 							  \@fields);
 4026: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4027: 	    chop($keyfields);
 4028: 	} else {
 4029: 	    unshift(@fields,['none','']);
 4030: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4031: 							    \@fields);
 4032:             foreach my $rec (@records) {
 4033:                 my %temp = &Apache::loncommon::record_sep($rec);
 4034:                 if (%temp) {
 4035:                     $keyfields=join(',',sort(keys(%temp)));
 4036:                     last;
 4037:                 }
 4038:             }
 4039: 	}
 4040:     }
 4041:     &csvuploadmap_footer($request,$i,$keyfields);
 4042:     $request->print(&show_grading_menu_form($symb));
 4043: 
 4044:     return '';
 4045: }
 4046: 
 4047: sub csvuploadoptions {
 4048:     my ($request)= @_;
 4049:     my ($symb)=&get_symb($request);
 4050:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4051:     my $ignore=&mt('Ignore First Line');
 4052:     $request->print(<<ENDPICK);
 4053: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4054: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4055: <input type="hidden" name="command"    value="csvuploadassign" />
 4056: <!--
 4057: <p>
 4058: <label>
 4059:    <input type="checkbox" name="show_full_results" />
 4060:    Show a table of all changes
 4061: </label>
 4062: </p>
 4063: -->
 4064: <p>
 4065: <label>
 4066:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4067:    Overwrite any existing score
 4068: </label>
 4069: </p>
 4070: ENDPICK
 4071:     my %fields=&get_fields();
 4072:     if (!defined($fields{'domain'})) {
 4073: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4074: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4075:     }
 4076:     foreach my $key (sort(keys(%env))) {
 4077: 	if ($key !~ /^form\.(.*)$/) { next; }
 4078: 	my $cleankey=$1;
 4079: 	if ($cleankey eq 'command') { next; }
 4080: 	$request->print('<input type="hidden" name="'.$cleankey.
 4081: 			'"  value="'.$env{$key}.'" />'."\n");
 4082:     }
 4083:     # FIXME do a check for any duplicated user ids...
 4084:     # FIXME do a check for any invalid user ids?...
 4085:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4086: <hr /></form>'."\n");
 4087:     $request->print(&show_grading_menu_form($symb));
 4088:     return '';
 4089: }
 4090: 
 4091: sub get_fields {
 4092:     my %fields;
 4093:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4094:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4095: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4096: 	    if ($env{'form.f'.$i} ne 'none') {
 4097: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4098: 	    }
 4099: 	} else {
 4100: 	    if ($env{'form.f'.$i} ne 'none') {
 4101: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4102: 	    }
 4103: 	}
 4104:     }
 4105:     return %fields;
 4106: }
 4107: 
 4108: sub csvuploadassign {
 4109:     my ($request)= @_;
 4110:     my ($symb)=&get_symb($request);
 4111:     if (!$symb) {return '';}
 4112:     my $error_msg = '';
 4113:     &Apache::loncommon::load_tmp_file($request);
 4114:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4115:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4116:     my %fields=&get_fields();
 4117:     $request->print('<h3>Assigning Grades</h3>');
 4118:     my $courseid=$env{'request.course.id'};
 4119:     my ($classlist) = &getclasslist('all',0);
 4120:     my @notallowed;
 4121:     my @skipped;
 4122:     my $countdone=0;
 4123:     foreach my $grade (@gradedata) {
 4124: 	my %entries=&Apache::loncommon::record_sep($grade);
 4125: 	my $domain;
 4126: 	if ($entries{$fields{'domain'}}) {
 4127: 	    $domain=$entries{$fields{'domain'}};
 4128: 	} else {
 4129: 	    $domain=$env{'form.default_domain'};
 4130: 	}
 4131: 	$domain=~s/\s//g;
 4132: 	my $username=$entries{$fields{'username'}};
 4133: 	$username=~s/\s//g;
 4134: 	if (!$username) {
 4135: 	    my $id=$entries{$fields{'ID'}};
 4136: 	    $id=~s/\s//g;
 4137: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4138: 	    $username=$ids{$id};
 4139: 	}
 4140: 	if (!exists($$classlist{"$username:$domain"})) {
 4141: 	    my $id=$entries{$fields{'ID'}};
 4142: 	    $id=~s/\s//g;
 4143: 	    if ($id) {
 4144: 		push(@skipped,"$id:$domain");
 4145: 	    } else {
 4146: 		push(@skipped,"$username:$domain");
 4147: 	    }
 4148: 	    next;
 4149: 	}
 4150: 	my $usec=$classlist->{"$username:$domain"}[5];
 4151: 	if (!&canmodify($usec)) {
 4152: 	    push(@notallowed,"$username:$domain");
 4153: 	    next;
 4154: 	}
 4155: 	my %points;
 4156: 	my %grades;
 4157: 	foreach my $dest (keys(%fields)) {
 4158: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4159: 		$dest eq 'domain') { next; }
 4160: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4161: 	    if ($dest=~/stores_(.*)_points/) {
 4162: 		my $part=$1;
 4163: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4164: 					      $symb,$domain,$username);
 4165:                 if ($wgt) {
 4166:                     $entries{$fields{$dest}}=~s/\s//g;
 4167:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4168:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4169:                                           : 'correct_by_override';
 4170:                     $grades{"resource.$part.awarded"}=$pcr;
 4171:                     $grades{"resource.$part.solved"}=$award;
 4172:                     $points{$part}=1;
 4173:                 } else {
 4174:                     $error_msg = "<br />" .
 4175:                         &mt("Some point values were assigned"
 4176:                             ." for problems with a weight "
 4177:                             ."of zero. These values were "
 4178:                             ."ignored.");
 4179:                 }
 4180: 	    } else {
 4181: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4182: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4183: 		my $store_key=$dest;
 4184: 		$store_key=~s/^stores/resource/;
 4185: 		$store_key=~s/_/\./g;
 4186: 		$grades{$store_key}=$entries{$fields{$dest}};
 4187: 	    }
 4188: 	}
 4189: 	if (! %grades) { 
 4190:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4191:         } else {
 4192: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4193: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4194: 					   $env{'request.course.id'},
 4195: 					   $domain,$username);
 4196: 	   if ($result eq 'ok') {
 4197: 	      $request->print('.');
 4198: 	   } else {
 4199: 	      $request->print("<p><span class=\"LC_error\">".
 4200:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4201:                                   "$username:$domain",$result)."</span></p>");
 4202: 	   }
 4203: 	   $request->rflush();
 4204: 	   $countdone++;
 4205:         }
 4206:     }
 4207:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4208:     if (@skipped) {
 4209: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4210:         $request->print(join(', ',@skipped));
 4211:     }
 4212:     if (@notallowed) {
 4213: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4214: 	$request->print(join(', ',@notallowed));
 4215:     }
 4216:     $request->print("<br />\n");
 4217:     $request->print(&show_grading_menu_form($symb));
 4218:     return $error_msg;
 4219: }
 4220: #------------- end of section for handling csv file upload ---------
 4221: #
 4222: #-------------------------------------------------------------------
 4223: #
 4224: #-------------- Next few routines handle grading by page/sequence
 4225: #
 4226: #--- Select a page/sequence and a student to grade
 4227: sub pickStudentPage {
 4228:     my ($request) = shift;
 4229: 
 4230:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4231:     $request->print(<<LISTJAVASCRIPT);
 4232: <script type="text/javascript" language="javascript">
 4233: 
 4234: function checkPickOne(formname) {
 4235:     if (radioSelection(formname.student) == null) {
 4236: 	alert("$alertmsg");
 4237: 	return;
 4238:     }
 4239:     ptr = pullDownSelection(formname.selectpage);
 4240:     formname.page.value = formname["page"+ptr].value;
 4241:     formname.title.value = formname["title"+ptr].value;
 4242:     formname.submit();
 4243: }
 4244: 
 4245: </script>
 4246: LISTJAVASCRIPT
 4247:     &commonJSfunctions($request);
 4248:     my ($symb) = &get_symb($request);
 4249:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4250:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4251:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4252: 
 4253:     my $result='<h3><span class="LC_info">&nbsp;'.
 4254: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4255: 
 4256:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4257:     my $map_error;
 4258:     my ($titles,$symbx) = &getSymbMap($map_error);
 4259:     if ($map_error) {
 4260:         $request->print(&navmap_errormsg());
 4261:         return; 
 4262:     }
 4263:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4264: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4265: #    my $type=($curpage =~ /\.(page|sequence)/);
 4266:     my $select = '<select name="selectpage">'."\n";
 4267:     my $ctr=0;
 4268:     foreach (@$titles) {
 4269: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4270: 	$select.='<option value="'.$ctr.'" '.
 4271: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4272: 	    '>'.$showtitle.'</option>'."\n";
 4273: 	$ctr++;
 4274:     }
 4275:     $select.= '</select>';
 4276:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4277: 
 4278:     $ctr=0;
 4279:     foreach (@$titles) {
 4280: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4281: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4282: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4283: 	$ctr++;
 4284:     }
 4285:     $result.='<input type="hidden" name="page" />'."\n".
 4286: 	'<input type="hidden" name="title" />'."\n";
 4287: 
 4288:     my $options =
 4289: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4290: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4291:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4292: 
 4293:     $options =
 4294: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4295: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4296: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4297:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4298:     
 4299:     $result.=&build_section_inputs();
 4300:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4301:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4302: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4303: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4304: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4305: 
 4306:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4307: 
 4308:     $result.='&nbsp;<input type="button" '.
 4309:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4310: 
 4311:     $request->print($result);
 4312: 
 4313:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4314: 	&Apache::loncommon::start_data_table().
 4315: 	&Apache::loncommon::start_data_table_header_row().
 4316: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4317: 	'<th>'.&nameUserString('header').'</th>'.
 4318: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4319: 	'<th>'.&nameUserString('header').'</th>'.
 4320: 	&Apache::loncommon::end_data_table_header_row();
 4321:  
 4322:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4323:     my $ptr = 1;
 4324:     foreach my $student (sort 
 4325: 			 {
 4326: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4327: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4328: 			     }
 4329: 			     return $a cmp $b;
 4330: 			 } (keys(%$fullname))) {
 4331: 	my ($uname,$udom) = split(/:/,$student);
 4332: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4333:                                   : '</td>');
 4334: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4335: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4336: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4337: 	$studentTable.=
 4338: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4339:                          : '');
 4340: 	$ptr++;
 4341:     }
 4342:     if ($ptr%2 == 0) {
 4343: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4344: 	    &Apache::loncommon::end_data_table_row();
 4345:     }
 4346:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4347:     $studentTable.='<input type="button" '.
 4348:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4349: 
 4350:     $studentTable.=&show_grading_menu_form($symb);
 4351:     $request->print($studentTable);
 4352: 
 4353:     return '';
 4354: }
 4355: 
 4356: sub getSymbMap {
 4357:     my ($map_error) = @_;
 4358:     my $navmap = Apache::lonnavmaps::navmap->new();
 4359:     unless (ref($navmap)) {
 4360:         if (ref($map_error)) {
 4361:             $$map_error = 'navmap';
 4362:         }
 4363:         return;
 4364:     }
 4365:     my %symbx = ();
 4366:     my @titles = ();
 4367:     my $minder = 0;
 4368: 
 4369:     # Gather every sequence that has problems.
 4370:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4371: 					       1,0,1);
 4372:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4373: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4374: 	    my $title = $minder.'.'.
 4375: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4376: 	    push(@titles, $title); # minder in case two titles are identical
 4377: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4378: 	    $minder++;
 4379: 	}
 4380:     }
 4381:     return \@titles,\%symbx;
 4382: }
 4383: 
 4384: #
 4385: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4386: sub displayPage {
 4387:     my ($request) = shift;
 4388: 
 4389:     my ($symb) = &get_symb($request);
 4390:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4391:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4392:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4393:     my $pageTitle = $env{'form.page'};
 4394:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4395:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4396:     my $usec=$classlist->{$env{'form.student'}}[5];
 4397: 
 4398:     #need to make sure we have the correct data for later EXT calls, 
 4399:     #thus invalidate the cache
 4400:     &Apache::lonnet::devalidatecourseresdata(
 4401:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4402:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4403:     &Apache::lonnet::clear_EXT_cache_status();
 4404: 
 4405:     if (!&canview($usec)) {
 4406: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4407: 	$request->print(&show_grading_menu_form($symb));
 4408: 	return;
 4409:     }
 4410:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4411:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4412: 	'</h3>'."\n";
 4413:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4414:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4415: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4416:     } else {
 4417: 	delete($env{'form.CODE'});
 4418:     }
 4419:     &sub_page_js($request);
 4420:     $request->print($result);
 4421: 
 4422:     my $navmap = Apache::lonnavmaps::navmap->new();
 4423:     unless (ref($navmap)) {
 4424:         $request->print(&navmap_errormsg());
 4425:         $request->print(&show_grading_menu_form($symb));
 4426:         return;
 4427:     }
 4428:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4429:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4430:     if (!$map) {
 4431: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4432: 	$request->print(&show_grading_menu_form($symb));
 4433: 	return; 
 4434:     }
 4435:     my $iterator = $navmap->getIterator($map->map_start(),
 4436: 					$map->map_finish());
 4437: 
 4438:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4439: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4440: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4441: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4442: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4443: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4444: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4445: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4446: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4447: 
 4448:     if (defined($env{'form.CODE'})) {
 4449: 	$studentTable.=
 4450: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4451:     }
 4452:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4453: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4454: 
 4455:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4456: 	&Apache::loncommon::start_data_table().
 4457: 	&Apache::loncommon::start_data_table_header_row().
 4458: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4459: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4460: 	&Apache::loncommon::end_data_table_header_row();
 4461: 
 4462:     &Apache::lonxml::clear_problem_counter();
 4463:     my ($depth,$question,$prob) = (1,1,1);
 4464:     $iterator->next(); # skip the first BEGIN_MAP
 4465:     my $curRes = $iterator->next(); # for "current resource"
 4466:     while ($depth > 0) {
 4467:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4468:         if($curRes == $iterator->END_MAP) { $depth--; }
 4469: 
 4470:         if (ref($curRes) && $curRes->is_problem()) {
 4471: 	    my $parts = $curRes->parts();
 4472:             my $title = $curRes->compTitle();
 4473: 	    my $symbx = $curRes->symb();
 4474: 	    $studentTable.=
 4475: 		&Apache::loncommon::start_data_table_row().
 4476: 		'<td align="center" valign="top" >'.$prob.
 4477: 		(scalar(@{$parts}) == 1 ? '' 
 4478: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4479: 							scalar(@{$parts}))
 4480: 		 ).
 4481: 		 '</td>';
 4482: 	    $studentTable.='<td valign="top">';
 4483: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4484: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4485: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4486: 					     undef,'both',\%form);
 4487: 	    } else {
 4488: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4489: 		$companswer =~ s|<form(.*?)>||g;
 4490: 		$companswer =~ s|</form>||g;
 4491: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4492: #		    $companswer =~ s/$1/ /ms;
 4493: #		    $request->print('match='.$1."<br />\n");
 4494: #		}
 4495: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4496: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4497: 	    }
 4498: 
 4499: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4500: 
 4501: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4502: 		if ($record{'version'} eq '') {
 4503: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4504: 		} else {
 4505: 		    my %responseType = ();
 4506: 		    foreach my $partid (@{$parts}) {
 4507: 			my @responseIds =$curRes->responseIds($partid);
 4508: 			my @responseType =$curRes->responseType($partid);
 4509: 			my %responseIds;
 4510: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4511: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4512: 			}
 4513: 			$responseType{$partid} = \%responseIds;
 4514: 		    }
 4515: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4516: 
 4517: 		}
 4518: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4519: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4520: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4521: 									$env{'request.course.id'},
 4522: 									'','.submission');
 4523:  
 4524: 	    }
 4525: 	    if (&canmodify($usec)) {
 4526:             $studentTable.=&gradeBox_start();
 4527: 		foreach my $partid (@{$parts}) {
 4528: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4529: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4530: 		    $question++;
 4531: 		}
 4532:             $studentTable.=&gradeBox_end();
 4533: 		$prob++;
 4534: 	    }
 4535: 	    $studentTable.='</td></tr>';
 4536: 
 4537: 	}
 4538:         $curRes = $iterator->next();
 4539:     }
 4540: 
 4541:     $studentTable.=
 4542:         '</table>'."\n".
 4543:         '<input type="button" value="'.&mt('Save').'" '.
 4544:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4545:         '</form>'."\n";
 4546:     $studentTable.=&show_grading_menu_form($symb);
 4547:     $request->print($studentTable);
 4548: 
 4549:     return '';
 4550: }
 4551: 
 4552: sub displaySubByDates {
 4553:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4554:     my $isCODE=0;
 4555:     my $isTask = ($symb =~/\.task$/);
 4556:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4557:     my $studentTable=&Apache::loncommon::start_data_table().
 4558: 	&Apache::loncommon::start_data_table_header_row().
 4559: 	'<th>'.&mt('Date/Time').'</th>'.
 4560: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4561: 	'<th>'.&mt('Submission').'</th>'.
 4562: 	'<th>'.&mt('Status').'</th>'.
 4563: 	&Apache::loncommon::end_data_table_header_row();
 4564:     my ($version);
 4565:     my %mark;
 4566:     my %orders;
 4567:     $mark{'correct_by_student'} = $checkIcon;
 4568:     if (!exists($$record{'1:timestamp'})) {
 4569: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4570:     }
 4571: 
 4572:     my $interaction;
 4573:     my $no_increment = 1;
 4574:     for ($version=1;$version<=$$record{'version'};$version++) {
 4575: 	my $timestamp = 
 4576: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4577: 	if (exists($$record{$version.':resource.0.version'})) {
 4578: 	    $interaction = $$record{$version.':resource.0.version'};
 4579: 	}
 4580: 
 4581: 	my $where = ($isTask ? "$version:resource.$interaction"
 4582: 		             : "$version:resource");
 4583: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4584: 	    '<td>'.$timestamp.'</td>';
 4585: 	if ($isCODE) {
 4586: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4587: 	}
 4588: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4589: 	my @displaySub = ();
 4590: 	foreach my $partid (@{$parts}) {
 4591: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4592: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4593: 	    
 4594: 
 4595: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4596: 	    my $display_part=&get_display_part($partid,$symb);
 4597: 	    foreach my $matchKey (@matchKey) {
 4598: 		if (exists($$record{$version.':'.$matchKey}) &&
 4599: 		    $$record{$version.':'.$matchKey} ne '') {
 4600: 
 4601: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4602: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4603:                     $displaySub[0].='<span class="LC_nobreak"';
 4604:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4605:                                    .' <span class="LC_internal_info">'
 4606:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4607:                                    .'</span>'
 4608:                                    .' <b>';
 4609: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4610: 			$displaySub[0].=&mt('Trial not counted');
 4611: 		    } else {
 4612: 			$displaySub[0].=&mt('Trial: [_1]',
 4613: 					    $$record{"$where.$partid.tries"});
 4614: 		    }
 4615: 		    my $responseType=($isTask ? 'Task'
 4616:                                               : $responseType->{$partid}->{$responseId});
 4617: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4618: 		    if (!exists($orders{$partid}->{$responseId})) {
 4619: 			$orders{$partid}->{$responseId}=
 4620: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4621:                                        $no_increment);
 4622: 		    }
 4623: 		    $displaySub[0].='</b></span>'; # /nobreak
 4624: 		    $displaySub[0].='&nbsp; '.
 4625: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4626: 		}
 4627: 	    }
 4628: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4629: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4630: 				    $$record{"$where.$partid.checkedin"},
 4631: 				    $$record{"$where.$partid.checkedin.slot"}).
 4632: 					'<br />';
 4633: 	    }
 4634: 	    if (exists $$record{"$where.$partid.award"}) {
 4635: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4636: 		    lc($$record{"$where.$partid.award"}).' '.
 4637: 		    $mark{$$record{"$where.$partid.solved"}}.
 4638: 		    '<br />';
 4639: 	    }
 4640: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4641: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4642: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4643: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4644: 		$displaySub[2].=
 4645: 		    $$record{"$version:resource.$partid.regrader"}.
 4646: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4647: 	    }
 4648: 	}
 4649: 	# needed because old essay regrader has not parts info
 4650: 	if (exists $$record{"$version:resource.regrader"}) {
 4651: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4652: 	}
 4653: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4654: 	if ($displaySub[2]) {
 4655: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4656: 	}
 4657: 	$studentTable.='&nbsp;</td>'.
 4658: 	    &Apache::loncommon::end_data_table_row();
 4659:     }
 4660:     $studentTable.=&Apache::loncommon::end_data_table();
 4661:     return $studentTable;
 4662: }
 4663: 
 4664: sub updateGradeByPage {
 4665:     my ($request) = shift;
 4666: 
 4667:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4668:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4669:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4670:     my $pageTitle = $env{'form.page'};
 4671:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4672:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4673:     my $usec=$classlist->{$env{'form.student'}}[5];
 4674:     if (!&canmodify($usec)) {
 4675: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4676: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4677: 	return;
 4678:     }
 4679:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4680:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4681: 	'</h3>'."\n";
 4682: 
 4683:     $request->print($result);
 4684: 
 4685: 
 4686:     my $navmap = Apache::lonnavmaps::navmap->new();
 4687:     unless (ref($navmap)) {
 4688:         $request->print(&navmap_errormsg());
 4689:         return;
 4690:     }
 4691:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4692:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4693:     if (!$map) {
 4694: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4695: 	my ($symb)=&get_symb($request);
 4696: 	$request->print(&show_grading_menu_form($symb));
 4697: 	return; 
 4698:     }
 4699:     my $iterator = $navmap->getIterator($map->map_start(),
 4700: 					$map->map_finish());
 4701: 
 4702:     my $studentTable=
 4703: 	&Apache::loncommon::start_data_table().
 4704: 	&Apache::loncommon::start_data_table_header_row().
 4705: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4706: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4707: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4708: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4709: 	&Apache::loncommon::end_data_table_header_row();
 4710: 
 4711:     $iterator->next(); # skip the first BEGIN_MAP
 4712:     my $curRes = $iterator->next(); # for "current resource"
 4713:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4714:     while ($depth > 0) {
 4715:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4716:         if($curRes == $iterator->END_MAP) { $depth--; }
 4717: 
 4718:         if (ref($curRes) && $curRes->is_problem()) {
 4719: 	    my $parts = $curRes->parts();
 4720:             my $title = $curRes->compTitle();
 4721: 	    my $symbx = $curRes->symb();
 4722: 	    $studentTable.=
 4723: 		&Apache::loncommon::start_data_table_row().
 4724: 		'<td align="center" valign="top" >'.$prob.
 4725: 		(scalar(@{$parts}) == 1 ? '' 
 4726:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4727: 		.')').'</td>';
 4728: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4729: 
 4730: 	    my %newrecord=();
 4731: 	    my @displayPts=();
 4732:             my %aggregate = ();
 4733:             my $aggregateflag = 0;
 4734: 	    foreach my $partid (@{$parts}) {
 4735: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4736: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4737: 
 4738: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4739: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4740: 		my $partial = $newpts/$wgt;
 4741: 		my $score;
 4742: 		if ($partial > 0) {
 4743: 		    $score = 'correct_by_override';
 4744: 		} elsif ($newpts ne '') { #empty is taken as 0
 4745: 		    $score = 'incorrect_by_override';
 4746: 		}
 4747: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4748: 		if ($dropMenu eq 'excused') {
 4749: 		    $partial = '';
 4750: 		    $score = 'excused';
 4751: 		} elsif ($dropMenu eq 'reset status'
 4752: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4753: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4754: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4755: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4756: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4757: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4758: 		    $changeflag++;
 4759: 		    $newpts = '';
 4760:                     
 4761:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4762:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4763:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4764:                     if ($aggtries > 0) {
 4765:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4766:                         $aggregateflag = 1;
 4767:                     }
 4768: 		}
 4769: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4770: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4771: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4772: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4773: 		    '&nbsp;<br />';
 4774: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4775: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4776: 		    '&nbsp;<br />';
 4777: 		$question++;
 4778: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4779: 
 4780: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4781: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4782: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4783: 		    if (scalar(keys(%newrecord)) > 0);
 4784: 
 4785: 		$changeflag++;
 4786: 	    }
 4787: 	    if (scalar(keys(%newrecord)) > 0) {
 4788: 		my %record = 
 4789: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4790: 					     $udom,$uname);
 4791: 
 4792: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4793: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4794: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4795: 		    $newrecord{'resource.CODE'} = '';
 4796: 		}
 4797: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4798: 					$udom,$uname);
 4799: 		%record = &Apache::lonnet::restore($symbx,
 4800: 						   $env{'request.course.id'},
 4801: 						   $udom,$uname);
 4802: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4803: 					     $cdom,$cnum,$udom,$uname);
 4804: 	    }
 4805: 	    
 4806:             if ($aggregateflag) {
 4807:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4808:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4809:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4810:             }
 4811: 
 4812: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4813: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4814: 		&Apache::loncommon::end_data_table_row();
 4815: 
 4816: 	    $prob++;
 4817: 	}
 4818:         $curRes = $iterator->next();
 4819:     }
 4820: 
 4821:     $studentTable.=&Apache::loncommon::end_data_table();
 4822:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4823:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4824: 		  &mt('The scores were changed for [quant,_1,problem].',
 4825: 		  $changeflag));
 4826:     $request->print($grademsg.$studentTable);
 4827: 
 4828:     return '';
 4829: }
 4830: 
 4831: #-------- end of section for handling grading by page/sequence ---------
 4832: #
 4833: #-------------------------------------------------------------------
 4834: 
 4835: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4836: #
 4837: #------ start of section for handling grading by page/sequence ---------
 4838: 
 4839: =pod
 4840: 
 4841: =head1 Bubble sheet grading routines
 4842: 
 4843:   For this documentation:
 4844: 
 4845:    'scanline' refers to the full line of characters
 4846:    from the file that we are parsing that represents one entire sheet
 4847: 
 4848:    'bubble line' refers to the data
 4849:    representing the line of bubbles that are on the physical bubble sheet
 4850: 
 4851: 
 4852: The overall process is that a scanned in bubble sheet data is uploaded
 4853: into a course. When a user wants to grade, they select a
 4854: sequence/folder of resources, a file of bubble sheet info, and pick
 4855: one of the predefined configurations for what each scanline looks
 4856: like.
 4857: 
 4858: Next each scanline is checked for any errors of either 'missing
 4859: bubbles' (it's an error because it may have been mis-scanned
 4860: because too light bubbling), 'double bubble' (each bubble line should
 4861: have no more that one letter picked), invalid or duplicated CODE,
 4862: invalid student/employee ID
 4863: 
 4864: If the CODE option is used that determines the randomization of the
 4865: homework problems, either way the student/employee ID is looked up into a
 4866: username:domain.
 4867: 
 4868: During the validation phase the instructor can choose to skip scanlines. 
 4869: 
 4870: After the validation phase, there are now 3 bubble sheet files
 4871: 
 4872:   scantron_original_filename (unmodified original file)
 4873:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4874:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4875: 
 4876: Also there is a separate hash nohist_scantrondata that contains extra
 4877: correction information that isn't representable in the bubble sheet
 4878: file (see &scantron_getfile() for more information)
 4879: 
 4880: After all scanlines are either valid, marked as valid or skipped, then
 4881: foreach line foreach problem in the picked sequence, an ssi request is
 4882: made that simulates a user submitting their selected letter(s) against
 4883: the homework problem.
 4884: 
 4885: =over 4
 4886: 
 4887: 
 4888: 
 4889: =item defaultFormData
 4890: 
 4891:   Returns html hidden inputs used to hold context/default values.
 4892: 
 4893:  Arguments:
 4894:   $symb - $symb of the current resource 
 4895: 
 4896: =cut
 4897: 
 4898: sub defaultFormData {
 4899:     my ($symb)=@_;
 4900:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4901:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4902:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4903: }
 4904: 
 4905: 
 4906: =pod 
 4907: 
 4908: =item getSequenceDropDown
 4909: 
 4910:    Return html dropdown of possible sequences to grade
 4911:  
 4912:  Arguments:
 4913:    $symb - $symb of the current resource
 4914:    $map_error - ref to scalar which will container error if
 4915:                 $navmap object is unavailable in &getSymbMap().
 4916: 
 4917: =cut
 4918: 
 4919: sub getSequenceDropDown {
 4920:     my ($symb,$map_error)=@_;
 4921:     my $result='<select name="selectpage">'."\n";
 4922:     my ($titles,$symbx) = &getSymbMap($map_error);
 4923:     if (ref($map_error)) {
 4924:         return if ($$map_error);
 4925:     }
 4926:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4927:     my $ctr=0;
 4928:     foreach (@$titles) {
 4929: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4930: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4931: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4932: 	    '>'.$showtitle.'</option>'."\n";
 4933: 	$ctr++;
 4934:     }
 4935:     $result.= '</select>';
 4936:     return $result;
 4937: }
 4938: 
 4939: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4940:                                    # key is zero-based index - 0, 1, 2 ...
 4941: 
 4942: my %first_bubble_line;             # First bubble line no. for each bubble.
 4943: 
 4944: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4945:                                    # matchresponse or rankresponse, where 
 4946:                                    # an individual response can have multiple 
 4947:                                    # lines
 4948: 
 4949: my %responsetype_per_response;     # responsetype for each response
 4950: 
 4951: # Save and restore the bubble lines array to the form env.
 4952: 
 4953: 
 4954: sub save_bubble_lines {
 4955:     foreach my $line (keys(%bubble_lines_per_response)) {
 4956: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4957: 	$env{"form.scantron.first_bubble_line.$line"} =
 4958: 	    $first_bubble_line{$line};
 4959:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4960:             $subdivided_bubble_lines{$line};
 4961:         $env{"form.scantron.responsetype.$line"} =
 4962:             $responsetype_per_response{$line};
 4963:     }
 4964: }
 4965: 
 4966: 
 4967: sub restore_bubble_lines {
 4968:     my $line = 0;
 4969:     %bubble_lines_per_response = ();
 4970:     while ($env{"form.scantron.bubblelines.$line"}) {
 4971: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4972: 	$bubble_lines_per_response{$line} = $value;
 4973: 	$first_bubble_line{$line}  =
 4974: 	    $env{"form.scantron.first_bubble_line.$line"};
 4975:         $subdivided_bubble_lines{$line} =
 4976:             $env{"form.scantron.sub_bubblelines.$line"};
 4977:         $responsetype_per_response{$line} =
 4978:             $env{"form.scantron.responsetype.$line"};
 4979: 	$line++;
 4980:     }
 4981: }
 4982: 
 4983: #  Given the parsed scanline, get the response for 
 4984: #  'answer' number n:
 4985: 
 4986: sub get_response_bubbles {
 4987:     my ($parsed_line, $response)  = @_;
 4988: 
 4989:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4990:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4991:     
 4992:     my $selected = "";
 4993: 
 4994:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4995: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4996: 	$bubble_line++;
 4997:     }
 4998:     return $selected;
 4999: }
 5000: 
 5001: =pod 
 5002: 
 5003: =item scantron_filenames
 5004: 
 5005:    Returns a list of the scantron files in the current course 
 5006: 
 5007: =cut
 5008: 
 5009: sub scantron_filenames {
 5010:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5011:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5012:     my $getpropath = 1;
 5013:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 5014:                                        $getpropath);
 5015:     my @possiblenames;
 5016:     foreach my $filename (sort(@files)) {
 5017: 	($filename)=split(/&/,$filename);
 5018: 	if ($filename!~/^scantron_orig_/) { next ; }
 5019: 	$filename=~s/^scantron_orig_//;
 5020: 	push(@possiblenames,$filename);
 5021:     }
 5022:     return @possiblenames;
 5023: }
 5024: 
 5025: =pod 
 5026: 
 5027: =item scantron_uploads
 5028: 
 5029:    Returns  html drop-down list of scantron files in current course.
 5030: 
 5031:  Arguments:
 5032:    $file2grade - filename to set as selected in the dropdown
 5033: 
 5034: =cut
 5035: 
 5036: sub scantron_uploads {
 5037:     my ($file2grade) = @_;
 5038:     my $result=	'<select name="scantron_selectfile">';
 5039:     $result.="<option></option>";
 5040:     foreach my $filename (sort(&scantron_filenames())) {
 5041: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5042:     }
 5043:     $result.="</select>";
 5044:     return $result;
 5045: }
 5046: 
 5047: =pod 
 5048: 
 5049: =item scantron_scantab
 5050: 
 5051:   Returns html drop down of the scantron formats in the scantronformat.tab
 5052:   file.
 5053: 
 5054: =cut
 5055: 
 5056: sub scantron_scantab {
 5057:     my $result='<select name="scantron_format">'."\n";
 5058:     $result.='<option></option>'."\n";
 5059:     my @lines = &get_scantronformat_file();
 5060:     if (@lines > 0) {
 5061:         foreach my $line (@lines) {
 5062:             next if (($line =~ /^\#/) || ($line eq ''));
 5063: 	    my ($name,$descrip)=split(/:/,$line);
 5064: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5065:         }
 5066:     }
 5067:     $result.='</select>'."\n";
 5068:     return $result;
 5069: }
 5070: 
 5071: =pod
 5072: 
 5073: =item get_scantronformat_file
 5074: 
 5075:   Returns an array containing lines from the scantron format file for
 5076:   the domain of the course.
 5077: 
 5078:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5079:   lines are from this file.
 5080: 
 5081:   Otherwise, if a default.tab has been published in RES space by the 
 5082:   domainconfig user, lines are from this file.
 5083: 
 5084:   Otherwise, fall back to getting lines from the legacy file on the
 5085:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5086: 
 5087: =cut
 5088: 
 5089: sub get_scantronformat_file {
 5090:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5091:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5092:     my $gottab = 0;
 5093:     my @lines;
 5094:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5095:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5096:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5097:             if ($formatfile ne '-1') {
 5098:                 @lines = split("\n",$formatfile,-1);
 5099:                 $gottab = 1;
 5100:             }
 5101:         }
 5102:     }
 5103:     if (!$gottab) {
 5104:         my $confname = $cdom.'-domainconfig';
 5105:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5106:         my $formatfile =  &Apache::lonnet::getfile($default);
 5107:         if ($formatfile ne '-1') {
 5108:             @lines = split("\n",$formatfile,-1);
 5109:             $gottab = 1;
 5110:         }
 5111:     }
 5112:     if (!$gottab) {
 5113:         my @domains = &Apache::lonnet::current_machine_domains();
 5114:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5115:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5116:             @lines = <$fh>;
 5117:             close($fh);
 5118:         } else {
 5119:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5120:             @lines = <$fh>;
 5121:             close($fh);
 5122:         }
 5123:     }
 5124:     return @lines;
 5125: }
 5126: 
 5127: =pod 
 5128: 
 5129: =item scantron_CODElist
 5130: 
 5131:   Returns html drop down of the saved CODE lists from current course,
 5132:   generated from earlier printings.
 5133: 
 5134: =cut
 5135: 
 5136: sub scantron_CODElist {
 5137:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5138:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5139:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5140:     my $namechoice='<option></option>';
 5141:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5142: 	if ($name =~ /^error: 2 /) { next; }
 5143: 	if ($name =~ /^type\0/) { next; }
 5144: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5145:     }
 5146:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5147:     return $namechoice;
 5148: }
 5149: 
 5150: =pod 
 5151: 
 5152: =item scantron_CODEunique
 5153: 
 5154:   Returns the html for "Each CODE to be used once" radio.
 5155: 
 5156: =cut
 5157: 
 5158: sub scantron_CODEunique {
 5159:     my $result='<span class="LC_nobreak">
 5160:                  <label><input type="radio" name="scantron_CODEunique"
 5161:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5162:                 </span>
 5163:                 <span class="LC_nobreak">
 5164:                  <label><input type="radio" name="scantron_CODEunique"
 5165:                         value="no" />'.&mt('No').' </label>
 5166:                 </span>';
 5167:     return $result;
 5168: }
 5169: 
 5170: =pod 
 5171: 
 5172: =item scantron_selectphase
 5173: 
 5174:   Generates the initial screen to start the bubble sheet process.
 5175:   Allows for - starting a grading run.
 5176:              - downloading existing scan data (original, corrected
 5177:                                                 or skipped info)
 5178: 
 5179:              - uploading new scan data
 5180: 
 5181:  Arguments:
 5182:   $r          - The Apache request object
 5183:   $file2grade - name of the file that contain the scanned data to score
 5184: 
 5185: =cut
 5186: 
 5187: sub scantron_selectphase {
 5188:     my ($r,$file2grade) = @_;
 5189:     my ($symb)=&get_symb($r);
 5190:     if (!$symb) {return '';}
 5191:     my $map_error;
 5192:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5193:     if ($map_error) {
 5194:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5195:         return;
 5196:     }
 5197:     my $default_form_data=&defaultFormData($symb);
 5198:     my $grading_menu_button=&show_grading_menu_form($symb);
 5199:     my $file_selector=&scantron_uploads($file2grade);
 5200:     my $format_selector=&scantron_scantab();
 5201:     my $CODE_selector=&scantron_CODElist();
 5202:     my $CODE_unique=&scantron_CODEunique();
 5203:     my $result;
 5204: 
 5205:     $ssi_error = 0;
 5206: 
 5207:     # Chunk of form to prompt for a file to grade and how:
 5208: 
 5209:     $result.= '
 5210:     <br />
 5211:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5212:     <input type="hidden" name="command" value="scantron_warning" />
 5213:     '.$default_form_data.'
 5214:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5215:        '.&Apache::loncommon::start_data_table_header_row().'
 5216:             <th colspan="2">
 5217:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5218:             </th>
 5219:        '.&Apache::loncommon::end_data_table_header_row().'
 5220:        '.&Apache::loncommon::start_data_table_row().'
 5221:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5222:        '.&Apache::loncommon::end_data_table_row().'
 5223:        '.&Apache::loncommon::start_data_table_row().'
 5224:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5225:        '.&Apache::loncommon::end_data_table_row().'
 5226:        '.&Apache::loncommon::start_data_table_row().'
 5227:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5228:        '.&Apache::loncommon::end_data_table_row().'
 5229:        '.&Apache::loncommon::start_data_table_row().'
 5230:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5231:        '.&Apache::loncommon::end_data_table_row().'
 5232:        '.&Apache::loncommon::start_data_table_row().'
 5233:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5234:        '.&Apache::loncommon::end_data_table_row().'
 5235:        '.&Apache::loncommon::start_data_table_row().'
 5236: 	    <td> '.&mt('Options:').' </td>
 5237:             <td>
 5238: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5239:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5240:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5241: 	    </td>
 5242:        '.&Apache::loncommon::end_data_table_row().'
 5243:        '.&Apache::loncommon::start_data_table_row().'
 5244:             <td colspan="2">
 5245:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5246:             </td>
 5247:        '.&Apache::loncommon::end_data_table_row().'
 5248:     '.&Apache::loncommon::end_data_table().'
 5249:     </form>
 5250: ';
 5251:    
 5252:     $r->print($result);
 5253: 
 5254:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5255:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5256: 
 5257: 	# Chunk of form to prompt for a scantron file upload.
 5258: 
 5259:         $r->print('
 5260:     <br />
 5261:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5262:        '.&Apache::loncommon::start_data_table_header_row().'
 5263:             <th>
 5264:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5265:             </th>
 5266:        '.&Apache::loncommon::end_data_table_header_row().'
 5267:        '.&Apache::loncommon::start_data_table_row().'
 5268:             <td>
 5269: ');
 5270:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5271:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5272:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5273:     $r->print('
 5274:               <script type="text/javascript" language="javascript">
 5275:     function checkUpload(formname) {
 5276: 	if (formname.upfile.value == "") {
 5277: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5278: 	    return false;
 5279: 	}
 5280: 	formname.submit();
 5281:     }
 5282:               </script>
 5283: 
 5284:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5285:                 '.$default_form_data.'
 5286:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5287:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5288:                 <input name="command" value="scantronupload_save" type="hidden" />
 5289:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5290:                 <br />
 5291:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5292:               </form>
 5293: ');
 5294: 
 5295:         $r->print('
 5296:             </td>
 5297:        '.&Apache::loncommon::end_data_table_row().'
 5298:        '.&Apache::loncommon::end_data_table().'
 5299: ');
 5300:     }
 5301: 
 5302:     # Chunk of the form that prompts to view a scoring office file,
 5303:     # corrected file, skipped records in a file.
 5304: 
 5305:     $r->print('
 5306:    <br />
 5307:    <form action="/adm/grades" name="scantron_download">
 5308:      '.$default_form_data.'
 5309:      <input type="hidden" name="command" value="scantron_download" />
 5310:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5311:        '.&Apache::loncommon::start_data_table_header_row().'
 5312:               <th>
 5313:                 &nbsp;'.&mt('Download a scoring office file').'
 5314:               </th>
 5315:        '.&Apache::loncommon::end_data_table_header_row().'
 5316:        '.&Apache::loncommon::start_data_table_row().'
 5317:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5318:                 <br />
 5319:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5320:        '.&Apache::loncommon::end_data_table_row().'
 5321:      '.&Apache::loncommon::end_data_table().'
 5322:    </form>
 5323:    <br />
 5324: ');
 5325: 
 5326:     &Apache::lonpickcode::code_list($r,2);
 5327: 
 5328:     $r->print('<br /><form method="post" name="checkscantron">'.
 5329:              $default_form_data."\n".
 5330:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5331:              &Apache::loncommon::start_data_table_header_row()."\n".
 5332:              '<th colspan="2">
 5333:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5334:              '</th>'."\n".
 5335:               &Apache::loncommon::end_data_table_header_row()."\n".
 5336:               &Apache::loncommon::start_data_table_row()."\n".
 5337:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5338:               '<td> '.$sequence_selector.' </td>'.
 5339:               &Apache::loncommon::end_data_table_row()."\n".
 5340:               &Apache::loncommon::start_data_table_row()."\n".
 5341:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5342:               '<td> '.$file_selector.' </td>'."\n".
 5343:               &Apache::loncommon::end_data_table_row()."\n".
 5344:               &Apache::loncommon::start_data_table_row()."\n".
 5345:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5346:               '<td> '.$format_selector.' </td>'."\n".
 5347:               &Apache::loncommon::end_data_table_row()."\n".
 5348:               &Apache::loncommon::start_data_table_row()."\n".
 5349:               '<td> '.&mt('Options').' </td>'."\n".
 5350:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5351:               &Apache::loncommon::end_data_table_row()."\n".
 5352:               &Apache::loncommon::start_data_table_row()."\n".
 5353:               '<td colspan="2">'."\n".
 5354:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5355:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5356:               '</td>'."\n".
 5357:               &Apache::loncommon::end_data_table_row()."\n".
 5358:               &Apache::loncommon::end_data_table()."\n".
 5359:               '</form><br />');
 5360:     $r->print($grading_menu_button);
 5361:     return;
 5362: }
 5363: 
 5364: =pod
 5365: 
 5366: =item get_scantron_config
 5367: 
 5368:    Parse and return the scantron configuration line selected as a
 5369:    hash of configuration file fields.
 5370: 
 5371:  Arguments:
 5372:     which - the name of the configuration to parse from the file.
 5373: 
 5374: 
 5375:  Returns:
 5376:             If the named configuration is not in the file, an empty
 5377:             hash is returned.
 5378:     a hash with the fields
 5379:       name         - internal name for the this configuration setup
 5380:       description  - text to display to operator that describes this config
 5381:       CODElocation - if 0 or the string 'none'
 5382:                           - no CODE exists for this config
 5383:                      if -1 || the string 'letter'
 5384:                           - a CODE exists for this config and is
 5385:                             a string of letters
 5386:                      Unsupported value (but planned for future support)
 5387:                           if a positive integer
 5388:                                - The CODE exists as the first n items from
 5389:                                  the question section of the form
 5390:                           if the string 'number'
 5391:                                - The CODE exists for this config and is
 5392:                                  a string of numbers
 5393:       CODEstart   - (only matter if a CODE exists) column in the line where
 5394:                      the CODE starts
 5395:       CODElength  - length of the CODE
 5396:       IDstart     - column where the student/employee ID starts
 5397:       IDlength    - length of the student/employee ID info
 5398:       Qstart      - column where the information from the bubbled
 5399:                     'questions' start
 5400:       Qlength     - number of columns comprising a single bubble line from
 5401:                     the sheet. (usually either 1 or 10)
 5402:       Qon         - either a single character representing the character used
 5403:                     to signal a bubble was chosen in the positional setup, or
 5404:                     the string 'letter' if the letter of the chosen bubble is
 5405:                     in the final, or 'number' if a number representing the
 5406:                     chosen bubble is in the file (1->A 0->J)
 5407:       Qoff        - the character used to represent that a bubble was
 5408:                     left blank
 5409:       PaperID     - if the scanning process generates a unique number for each
 5410:                     sheet scanned the column that this ID number starts in
 5411:       PaperIDlength - number of columns that comprise the unique ID number
 5412:                       for the sheet of paper
 5413:       FirstName   - column that the first name starts in
 5414:       FirstNameLength - number of columns that the first name spans
 5415:  
 5416:       LastName    - column that the last name starts in
 5417:       LastNameLength - number of columns that the last name spans
 5418: 
 5419: =cut
 5420: 
 5421: sub get_scantron_config {
 5422:     my ($which) = @_;
 5423:     my @lines = &get_scantronformat_file();
 5424:     my %config;
 5425:     #FIXME probably should move to XML it has already gotten a bit much now
 5426:     foreach my $line (@lines) {
 5427: 	my ($name,$descrip)=split(/:/,$line);
 5428: 	if ($name ne $which ) { next; }
 5429: 	chomp($line);
 5430: 	my @config=split(/:/,$line);
 5431: 	$config{'name'}=$config[0];
 5432: 	$config{'description'}=$config[1];
 5433: 	$config{'CODElocation'}=$config[2];
 5434: 	$config{'CODEstart'}=$config[3];
 5435: 	$config{'CODElength'}=$config[4];
 5436: 	$config{'IDstart'}=$config[5];
 5437: 	$config{'IDlength'}=$config[6];
 5438: 	$config{'Qstart'}=$config[7];
 5439:  	$config{'Qlength'}=$config[8];
 5440: 	$config{'Qoff'}=$config[9];
 5441: 	$config{'Qon'}=$config[10];
 5442: 	$config{'PaperID'}=$config[11];
 5443: 	$config{'PaperIDlength'}=$config[12];
 5444: 	$config{'FirstName'}=$config[13];
 5445: 	$config{'FirstNamelength'}=$config[14];
 5446: 	$config{'LastName'}=$config[15];
 5447: 	$config{'LastNamelength'}=$config[16];
 5448: 	last;
 5449:     }
 5450:     return %config;
 5451: }
 5452: 
 5453: =pod 
 5454: 
 5455: =item username_to_idmap
 5456: 
 5457:     creates a hash keyed by student/employee ID with values of the corresponding
 5458:     student username:domain.
 5459: 
 5460:   Arguments:
 5461: 
 5462:     $classlist - reference to the class list hash. This is a hash
 5463:                  keyed by student name:domain  whose elements are references
 5464:                  to arrays containing various chunks of information
 5465:                  about the student. (See loncoursedata for more info).
 5466: 
 5467:   Returns
 5468:     %idmap - the constructed hash
 5469: 
 5470: =cut
 5471: 
 5472: sub username_to_idmap {
 5473:     my ($classlist)= @_;
 5474:     my %idmap;
 5475:     foreach my $student (keys(%$classlist)) {
 5476: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5477: 	    $student;
 5478:     }
 5479:     return %idmap;
 5480: }
 5481: 
 5482: =pod
 5483: 
 5484: =item scantron_fixup_scanline
 5485: 
 5486:    Process a requested correction to a scanline.
 5487: 
 5488:   Arguments:
 5489:     $scantron_config   - hash from &get_scantron_config()
 5490:     $scan_data         - hash of correction information 
 5491:                           (see &scantron_getfile())
 5492:     $line              - existing scanline
 5493:     $whichline         - line number of the passed in scanline
 5494:     $field             - type of change to process 
 5495:                          (either 
 5496:                           'ID'     -> correct the student/employee ID
 5497:                           'CODE'   -> correct the CODE
 5498:                           'answer' -> fixup the submitted answers)
 5499:     
 5500:    $args               - hash of additional info,
 5501:                           - 'ID' 
 5502:                                'newid' -> studentID to use in replacement
 5503:                                           of existing one
 5504:                           - 'CODE' 
 5505:                                'CODE_ignore_dup' - set to true if duplicates
 5506:                                                    should be ignored.
 5507: 	                       'CODE' - is new code or 'use_unfound'
 5508:                                         if the existing unfound code should
 5509:                                         be used as is
 5510:                           - 'answer'
 5511:                                'response' - new answer or 'none' if blank
 5512:                                'question' - the bubble line to change
 5513:                                'questionnum' - the question identifier,
 5514:                                                may include subquestion. 
 5515: 
 5516:   Returns:
 5517:     $line - the modified scanline
 5518: 
 5519:   Side effects: 
 5520:     $scan_data - may be updated
 5521: 
 5522: =cut
 5523: 
 5524: 
 5525: sub scantron_fixup_scanline {
 5526:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5527:     if ($field eq 'ID') {
 5528: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5529: 	    return ($line,1,'New value too large');
 5530: 	}
 5531: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5532: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5533: 				     $args->{'newid'});
 5534: 	}
 5535: 	substr($line,$$scantron_config{'IDstart'}-1,
 5536: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5537: 	if ($args->{'newid'}=~/^\s*$/) {
 5538: 	    &scan_data($scan_data,"$whichline.user",
 5539: 		       $args->{'username'}.':'.$args->{'domain'});
 5540: 	}
 5541:     } elsif ($field eq 'CODE') {
 5542: 	if ($args->{'CODE_ignore_dup'}) {
 5543: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5544: 	}
 5545: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5546: 	if ($args->{'CODE'} ne 'use_unfound') {
 5547: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5548: 		return ($line,1,'New CODE value too large');
 5549: 	    }
 5550: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5551: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5552: 	    }
 5553: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5554: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5555: 	}
 5556:     } elsif ($field eq 'answer') {
 5557: 	my $length=$scantron_config->{'Qlength'};
 5558: 	my $off=$scantron_config->{'Qoff'};
 5559: 	my $on=$scantron_config->{'Qon'};
 5560: 	my $answer=${off}x$length;
 5561: 	if ($args->{'response'} eq 'none') {
 5562: 	    &scan_data($scan_data,
 5563: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5564: 	} else {
 5565: 	    if ($on eq 'letter') {
 5566: 		my @alphabet=('A'..'Z');
 5567: 		$answer=$alphabet[$args->{'response'}];
 5568: 	    } elsif ($on eq 'number') {
 5569: 		$answer=$args->{'response'}+1;
 5570: 		if ($answer == 10) { $answer = '0'; }
 5571: 	    } else {
 5572: 		substr($answer,$args->{'response'},1)=$on;
 5573: 	    }
 5574: 	    &scan_data($scan_data,
 5575: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5576: 	}
 5577: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5578: 	substr($line,$where-1,$length)=$answer;
 5579:     }
 5580:     return $line;
 5581: }
 5582: 
 5583: =pod
 5584: 
 5585: =item scan_data
 5586: 
 5587:     Edit or look up  an item in the scan_data hash.
 5588: 
 5589:   Arguments:
 5590:     $scan_data  - The hash (see scantron_getfile)
 5591:     $key        - shorthand of the key to edit (actual key is
 5592:                   scantronfilename_key).
 5593:     $data        - New value of the hash entry.
 5594:     $delete      - If true, the entry is removed from the hash.
 5595: 
 5596:   Returns:
 5597:     The new value of the hash table field (undefined if deleted).
 5598: 
 5599: =cut
 5600: 
 5601: 
 5602: sub scan_data {
 5603:     my ($scan_data,$key,$value,$delete)=@_;
 5604:     my $filename=$env{'form.scantron_selectfile'};
 5605:     if (defined($value)) {
 5606: 	$scan_data->{$filename.'_'.$key} = $value;
 5607:     }
 5608:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5609:     return $scan_data->{$filename.'_'.$key};
 5610: }
 5611: 
 5612: # ----- These first few routines are general use routines.----
 5613: 
 5614: # Return the number of occurences of a pattern in a string.
 5615: 
 5616: sub occurence_count {
 5617:     my ($string, $pattern) = @_;
 5618: 
 5619:     my @matches = ($string =~ /$pattern/g);
 5620: 
 5621:     return scalar(@matches);
 5622: }
 5623: 
 5624: 
 5625: # Take a string known to have digits and convert all the
 5626: # digits into letters in the range J,A..I.
 5627: 
 5628: sub digits_to_letters {
 5629:     my ($input) = @_;
 5630: 
 5631:     my @alphabet = ('J', 'A'..'I');
 5632: 
 5633:     my @input    = split(//, $input);
 5634:     my $output ='';
 5635:     for (my $i = 0; $i < scalar(@input); $i++) {
 5636: 	if ($input[$i] =~ /\d/) {
 5637: 	    $output .= $alphabet[$input[$i]];
 5638: 	} else {
 5639: 	    $output .= $input[$i];
 5640: 	}
 5641:     }
 5642:     return $output;
 5643: }
 5644: 
 5645: =pod 
 5646: 
 5647: =item scantron_parse_scanline
 5648: 
 5649:   Decodes a scanline from the selected scantron file
 5650: 
 5651:  Arguments:
 5652:     line             - The text of the scantron file line to process
 5653:     whichline        - Line number
 5654:     scantron_config  - Hash describing the format of the scantron lines.
 5655:     scan_data        - Hash of extra information about the scanline
 5656:                        (see scantron_getfile for more information)
 5657:     just_header      - True if should not process question answers but only
 5658:                        the stuff to the left of the answers.
 5659:  Returns:
 5660:    Hash containing the result of parsing the scanline
 5661: 
 5662:    Keys are all proceeded by the string 'scantron.'
 5663: 
 5664:        CODE    - the CODE in use for this scanline
 5665:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5666:                  by the operator
 5667:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5668:                             CODEs were selected, but the usage has been
 5669:                             forced by the operator
 5670:        ID  - student/employee ID
 5671:        PaperID - if used, the ID number printed on the sheet when the 
 5672:                  paper was scanned
 5673:        FirstName - first name from the sheet
 5674:        LastName  - last name from the sheet
 5675: 
 5676:      if just_header was not true these key may also exist
 5677: 
 5678:        missingerror - a list of bubble ranges that are considered to be answers
 5679:                       to a single question that don't have any bubbles filled in.
 5680:                       Of the form questionnumber:firstbubblenumber:count.
 5681:        doubleerror  - a list of bubble ranges that are considered to be answers
 5682:                       to a single question that have more than one bubble filled in.
 5683:                       Of the form questionnumber::firstbubblenumber:count
 5684:    
 5685:                 In the above, count is the number of bubble responses in the
 5686:                 input line needed to represent the possible answers to the question.
 5687:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5688:                 per line would have count = 2.
 5689: 
 5690:        maxquest     - the number of the last bubble line that was parsed
 5691: 
 5692:        (<number> starts at 1)
 5693:        <number>.answer - zero or more letters representing the selected
 5694:                          letters from the scanline for the bubble line 
 5695:                          <number>.
 5696:                          if blank there was either no bubble or there where
 5697:                          multiple bubbles, (consult the keys missingerror and
 5698:                          doubleerror if this is an error condition)
 5699: 
 5700: =cut
 5701: 
 5702: sub scantron_parse_scanline {
 5703:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5704: 
 5705:     my %record;
 5706:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5707:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5708:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5709:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5710: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5711: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5712: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5713: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5714: 	    $record{'scantron.CODE'}=substr($data,
 5715: 					    $$scantron_config{'CODEstart'}-1,
 5716: 					    $$scantron_config{'CODElength'});
 5717: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5718: 		$record{'scantron.useCODE'}=1;
 5719: 	    }
 5720: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5721: 		$record{'scantron.CODE_ignore_dup'}=1;
 5722: 	    }
 5723: 	} else {
 5724: 	    #FIXME interpret first N questions
 5725: 	}
 5726:     }
 5727:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5728: 				  $$scantron_config{'IDlength'});
 5729:     $record{'scantron.PaperID'}=
 5730: 	substr($data,$$scantron_config{'PaperID'}-1,
 5731: 	       $$scantron_config{'PaperIDlength'});
 5732:     $record{'scantron.FirstName'}=
 5733: 	substr($data,$$scantron_config{'FirstName'}-1,
 5734: 	       $$scantron_config{'FirstNamelength'});
 5735:     $record{'scantron.LastName'}=
 5736: 	substr($data,$$scantron_config{'LastName'}-1,
 5737: 	       $$scantron_config{'LastNamelength'});
 5738:     if ($just_header) { return \%record; }
 5739: 
 5740:     my @alphabet=('A'..'Z');
 5741:     my $questnum=0;
 5742:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5743: 
 5744:     chomp($questions);		# Get rid of any trailing \n.
 5745:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5746:     while (length($questions)) {
 5747: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5748:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5749:                              || 1;
 5750:         $questnum++;
 5751:         my $quest_id = $questnum;
 5752:         my $currentquest = substr($questions,0,$answer_length);
 5753:         $questions       = substr($questions,$answer_length);
 5754:         if (length($currentquest) < $answer_length) { next; }
 5755: 
 5756:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5757:             my $subquestnum = 1;
 5758:             my $subquestions = $currentquest;
 5759:             my @subanswers_needed = 
 5760:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5761:             foreach my $subans (@subanswers_needed) {
 5762:                 my $subans_length =
 5763:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5764:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5765:                 $subquestions   = substr($subquestions,$subans_length);
 5766:                 $quest_id = "$questnum.$subquestnum";
 5767:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5768:                     ($$scantron_config{'Qon'} eq 'number')) {
 5769:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5770:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5771:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5772:                 } else {
 5773:                     $ansnum = &scantron_validator_positional($ansnum,
 5774:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5775:                 }
 5776:                 $subquestnum ++;
 5777:             }
 5778:         } else {
 5779:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5780:                 ($$scantron_config{'Qon'} eq 'number')) {
 5781:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5782:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5783:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5784:             } else {
 5785:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5786:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5787:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5788:             }
 5789:         }
 5790:     }
 5791:     $record{'scantron.maxquest'}=$questnum;
 5792:     return \%record;
 5793: }
 5794: 
 5795: sub scantron_validator_lettnum {
 5796:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5797:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5798: 
 5799:     # Qon 'letter' implies for each slot in currquest we have:
 5800:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5801:     #    about anything else (esp. a value of Qoff) for missing
 5802:     #    bubbles.
 5803:     #
 5804:     # Qon 'number' implies each slot gives a digit that indexes the
 5805:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5806:     #    and * or ? for double bubbles on a single line.
 5807:     #
 5808: 
 5809:     my $matchon;
 5810:     if ($$scantron_config{'Qon'} eq 'letter') {
 5811:         $matchon = '[A-Z]';
 5812:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5813:         $matchon = '\d';
 5814:     }
 5815:     my $occurrences = 0;
 5816:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5817:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5818:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5819:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5820:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5821:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5822:         my @singlelines = split('',$currquest);
 5823:         foreach my $entry (@singlelines) {
 5824:             $occurrences = &occurence_count($entry,$matchon);
 5825:             if ($occurrences > 1) {
 5826:                 last;
 5827:             }
 5828:         } 
 5829:     } else {
 5830:         $occurrences = &occurence_count($currquest,$matchon); 
 5831:     }
 5832:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5833:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5834:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5835:             my $bubble = substr($currquest,$ans,1);
 5836:             if ($bubble =~ /$matchon/ ) {
 5837:                 if ($$scantron_config{'Qon'} eq 'number') {
 5838:                     if ($bubble == 0) {
 5839:                         $bubble = 10; 
 5840:                     }
 5841:                     $record->{"scantron.$ansnum.answer"} = 
 5842:                         $alphabet->[$bubble-1];
 5843:                 } else {
 5844:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5845:                 }
 5846:             } else {
 5847:                 $record->{"scantron.$ansnum.answer"}='';
 5848:             }
 5849:             $ansnum++;
 5850:         }
 5851:     } elsif (!defined($currquest)
 5852:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5853:             || (&occurence_count($currquest,$matchon) == 0)) {
 5854:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5855:             $record->{"scantron.$ansnum.answer"}='';
 5856:             $ansnum++;
 5857:         }
 5858:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5859:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5860:         }
 5861:     } else {
 5862:         if ($$scantron_config{'Qon'} eq 'number') {
 5863:             $currquest = &digits_to_letters($currquest);            
 5864:         }
 5865:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5866:             my $bubble = substr($currquest,$ans,1);
 5867:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5868:             $ansnum++;
 5869:         }
 5870:     }
 5871:     return $ansnum;
 5872: }
 5873: 
 5874: sub scantron_validator_positional {
 5875:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5876:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5877: 
 5878:     # Otherwise there's a positional notation;
 5879:     # each bubble line requires Qlength items, and there are filled in
 5880:     # bubbles for each case where there 'Qon' characters.
 5881:     #
 5882: 
 5883:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5884: 
 5885:     # If the split only gives us one element.. the full length of the
 5886:     # answer string, no bubbles are filled in:
 5887: 
 5888:     if ($answers_needed eq '') {
 5889:         return;
 5890:     }
 5891: 
 5892:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5893:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5894:             $record->{"scantron.$ansnum.answer"}='';
 5895:             $ansnum++;
 5896:         }
 5897:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5898:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5899:         }
 5900:     } elsif (scalar(@array) == 2) {
 5901:         my $location = length($array[0]);
 5902:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5903:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5904:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5905:             if ($ans eq $line_num) {
 5906:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5907:             } else {
 5908:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5909:             }
 5910:             $ansnum++;
 5911:          }
 5912:     } else {
 5913:         #  If there's more than one instance of a bubble character
 5914:         #  That's a double bubble; with positional notation we can
 5915:         #  record all the bubbles filled in as well as the
 5916:         #  fact this response consists of multiple bubbles.
 5917:         #
 5918:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5919:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5920:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5921:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5922:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5923:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5924:             my $doubleerror = 0;
 5925:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5926:                    (!$doubleerror)) {
 5927:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5928:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5929:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5930:                if (length(@currarray) > 2) {
 5931:                    $doubleerror = 1;
 5932:                } 
 5933:             }
 5934:             if ($doubleerror) {
 5935:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5936:             }
 5937:         } else {
 5938:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5939:         }
 5940:         my $item = $ansnum;
 5941:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5942:             $record->{"scantron.$item.answer"} = '';
 5943:             $item ++;
 5944:         }
 5945: 
 5946:         my @ans=@array;
 5947:         my $i=0;
 5948:         my $increment = 0;
 5949:         while ($#ans) {
 5950:             $i+=length($ans[0]) + $increment;
 5951:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5952:             my $bubble = $i%$$scantron_config{'Qlength'};
 5953:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5954:             shift(@ans);
 5955:             $increment = 1;
 5956:         }
 5957:         $ansnum += $answers_needed;
 5958:     }
 5959:     return $ansnum;
 5960: }
 5961: 
 5962: =pod
 5963: 
 5964: =item scantron_add_delay
 5965: 
 5966:    Adds an error message that occurred during the grading phase to a
 5967:    queue of messages to be shown after grading pass is complete
 5968: 
 5969:  Arguments:
 5970:    $delayqueue  - arrary ref of hash ref of error messages
 5971:    $scanline    - the scanline that caused the error
 5972:    $errormesage - the error message
 5973:    $errorcode   - a numeric code for the error
 5974: 
 5975:  Side Effects:
 5976:    updates the $delayqueue to have a new hash ref of the error
 5977: 
 5978: =cut
 5979: 
 5980: sub scantron_add_delay {
 5981:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5982:     push(@$delayqueue,
 5983: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5984: 	  'ecode' => $errorcode }
 5985: 	 );
 5986: }
 5987: 
 5988: =pod
 5989: 
 5990: =item scantron_find_student
 5991: 
 5992:    Finds the username for the current scanline
 5993: 
 5994:   Arguments:
 5995:    $scantron_record - hash result from scantron_parse_scanline
 5996:    $scan_data       - hash of correction information 
 5997:                       (see &scantron_getfile() form more information)
 5998:    $idmap           - hash from &username_to_idmap()
 5999:    $line            - number of current scanline
 6000:  
 6001:   Returns:
 6002:    Either 'username:domain' or undef if unknown
 6003: 
 6004: =cut
 6005: 
 6006: sub scantron_find_student {
 6007:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6008:     my $scanID=$$scantron_record{'scantron.ID'};
 6009:     if ($scanID =~ /^\s*$/) {
 6010:  	return &scan_data($scan_data,"$line.user");
 6011:     }
 6012:     foreach my $id (keys(%$idmap)) {
 6013:  	if (lc($id) eq lc($scanID)) {
 6014:  	    return $$idmap{$id};
 6015:  	}
 6016:     }
 6017:     return undef;
 6018: }
 6019: 
 6020: =pod
 6021: 
 6022: =item scantron_filter
 6023: 
 6024:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6025:    hidden resources was selected
 6026: 
 6027: =cut
 6028: 
 6029: sub scantron_filter {
 6030:     my ($curres)=@_;
 6031: 
 6032:     if (ref($curres) && $curres->is_problem()) {
 6033: 	# if the user has asked to not have either hidden
 6034: 	# or 'randomout' controlled resources to be graded
 6035: 	# don't include them
 6036: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6037: 	    && $curres->randomout) {
 6038: 	    return 0;
 6039: 	}
 6040: 	return 1;
 6041:     }
 6042:     return 0;
 6043: }
 6044: 
 6045: =pod
 6046: 
 6047: =item scantron_process_corrections
 6048: 
 6049:    Gets correction information out of submitted form data and corrects
 6050:    the scanline
 6051: 
 6052: =cut
 6053: 
 6054: sub scantron_process_corrections {
 6055:     my ($r) = @_;
 6056:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6057:     my ($scanlines,$scan_data)=&scantron_getfile();
 6058:     my $classlist=&Apache::loncoursedata::get_classlist();
 6059:     my $which=$env{'form.scantron_line'};
 6060:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6061:     my ($skip,$err,$errmsg);
 6062:     if ($env{'form.scantron_skip_record'}) {
 6063: 	$skip=1;
 6064:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6065: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6066: 	    $env{'form.scantron_domain'};
 6067: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6068: 	($line,$err,$errmsg)=
 6069: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6070: 				     'ID',{'newid'=>$newid,
 6071: 				    'username'=>$env{'form.scantron_username'},
 6072: 				    'domain'=>$env{'form.scantron_domain'}});
 6073:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6074: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6075: 	my $newCODE;
 6076: 	my %args;
 6077: 	if      ($resolution eq 'use_unfound') {
 6078: 	    $newCODE='use_unfound';
 6079: 	} elsif ($resolution eq 'use_found') {
 6080: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6081: 	} elsif ($resolution eq 'use_typed') {
 6082: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6083: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6084: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6085: 	}
 6086: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6087: 	    $args{'CODE_ignore_dup'}=1;
 6088: 	}
 6089: 	$args{'CODE'}=$newCODE;
 6090: 	($line,$err,$errmsg)=
 6091: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6092: 				     'CODE',\%args);
 6093:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6094: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6095: 	    ($line,$err,$errmsg)=
 6096: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6097: 					 $which,'answer',
 6098: 					 { 'question'=>$question,
 6099: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6100:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6101: 	    if ($err) { last; }
 6102: 	}
 6103:     }
 6104:     if ($err) {
 6105: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6106:     } else {
 6107: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6108: 	&scantron_putfile($scanlines,$scan_data);
 6109:     }
 6110: }
 6111: 
 6112: =pod
 6113: 
 6114: =item reset_skipping_status
 6115: 
 6116:    Forgets the current set of remember skipped scanlines (and thus
 6117:    reverts back to considering all lines in the
 6118:    scantron_skipped_<filename> file)
 6119: 
 6120: =cut
 6121: 
 6122: sub reset_skipping_status {
 6123:     my ($scanlines,$scan_data)=&scantron_getfile();
 6124:     &scan_data($scan_data,'remember_skipping',undef,1);
 6125:     &scantron_putfile(undef,$scan_data);
 6126: }
 6127: 
 6128: =pod
 6129: 
 6130: =item start_skipping
 6131: 
 6132:    Marks a scanline to be skipped. 
 6133: 
 6134: =cut
 6135: 
 6136: sub start_skipping {
 6137:     my ($scan_data,$i)=@_;
 6138:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6139:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6140: 	$remembered{$i}=2;
 6141:     } else {
 6142: 	$remembered{$i}=1;
 6143:     }
 6144:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6145: }
 6146: 
 6147: =pod
 6148: 
 6149: =item should_be_skipped
 6150: 
 6151:    Checks whether a scanline should be skipped.
 6152: 
 6153: =cut
 6154: 
 6155: sub should_be_skipped {
 6156:     my ($scanlines,$scan_data,$i)=@_;
 6157:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6158: 	# not redoing old skips
 6159: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6160: 	return 0;
 6161:     }
 6162:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6163: 
 6164:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6165: 	return 0;
 6166:     }
 6167:     return 1;
 6168: }
 6169: 
 6170: =pod
 6171: 
 6172: =item remember_current_skipped
 6173: 
 6174:    Discovers what scanlines are in the scantron_skipped_<filename>
 6175:    file and remembers them into scan_data for later use.
 6176: 
 6177: =cut
 6178: 
 6179: sub remember_current_skipped {
 6180:     my ($scanlines,$scan_data)=&scantron_getfile();
 6181:     my %to_remember;
 6182:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6183: 	if ($scanlines->{'skipped'}[$i]) {
 6184: 	    $to_remember{$i}=1;
 6185: 	}
 6186:     }
 6187: 
 6188:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6189:     &scantron_putfile(undef,$scan_data);
 6190: }
 6191: 
 6192: =pod
 6193: 
 6194: =item check_for_error
 6195: 
 6196:     Checks if there was an error when attempting to remove a specific
 6197:     scantron_.. bubble sheet data file. Prints out an error if
 6198:     something went wrong.
 6199: 
 6200: =cut
 6201: 
 6202: sub check_for_error {
 6203:     my ($r,$result)=@_;
 6204:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6205: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6206:     }
 6207: }
 6208: 
 6209: =pod
 6210: 
 6211: =item scantron_warning_screen
 6212: 
 6213:    Interstitial screen to make sure the operator has selected the
 6214:    correct options before we start the validation phase.
 6215: 
 6216: =cut
 6217: 
 6218: sub scantron_warning_screen {
 6219:     my ($button_text)=@_;
 6220:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6221:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6222:     my $CODElist;
 6223:     if ($scantron_config{'CODElocation'} &&
 6224: 	$scantron_config{'CODEstart'} &&
 6225: 	$scantron_config{'CODElength'}) {
 6226: 	$CODElist=$env{'form.scantron_CODElist'};
 6227: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6228: 	$CODElist=
 6229: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6230: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6231:     }
 6232:     return ('
 6233: <p>
 6234: <span class="LC_warning">
 6235: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6236: </p>
 6237: <table>
 6238: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6239: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6240: '.$CODElist.'
 6241: </table>
 6242: <br />
 6243: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6244: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6245: 
 6246: <br />
 6247: ');
 6248: }
 6249: 
 6250: =pod
 6251: 
 6252: =item scantron_do_warning
 6253: 
 6254:    Check if the operator has picked something for all required
 6255:    fields. Error out if something is missing.
 6256: 
 6257: =cut
 6258: 
 6259: sub scantron_do_warning {
 6260:     my ($r)=@_;
 6261:     my ($symb)=&get_symb($r);
 6262:     if (!$symb) {return '';}
 6263:     my $default_form_data=&defaultFormData($symb);
 6264:     $r->print(&scantron_form_start().$default_form_data);
 6265:     if ( $env{'form.selectpage'} eq '' ||
 6266: 	 $env{'form.scantron_selectfile'} eq '' ||
 6267: 	 $env{'form.scantron_format'} eq '' ) {
 6268: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6269: 	if ( $env{'form.selectpage'} eq '') {
 6270: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6271: 	} 
 6272: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6273: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6274: 	} 
 6275: 	if ( $env{'form.scantron_format'} eq '') {
 6276: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6277: 	} 
 6278:     } else {
 6279: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6280: 	$r->print('
 6281: '.$warning.'
 6282: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6283: <input type="hidden" name="command" value="scantron_validate" />
 6284: ');
 6285:     }
 6286:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6287:     return '';
 6288: }
 6289: 
 6290: =pod
 6291: 
 6292: =item scantron_form_start
 6293: 
 6294:     html hidden input for remembering all selected grading options
 6295: 
 6296: =cut
 6297: 
 6298: sub scantron_form_start {
 6299:     my ($max_bubble)=@_;
 6300:     my $result= <<SCANTRONFORM;
 6301: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6302:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6303:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6304:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6305:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6306:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6307:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6308:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6309:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6310:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6311: SCANTRONFORM
 6312: 
 6313:   my $line = 0;
 6314:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6315:        my $chunk =
 6316: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6317:        $chunk .=
 6318: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6319:        $chunk .= 
 6320:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6321:        $chunk .=
 6322:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6323:        $result .= $chunk;
 6324:        $line++;
 6325:    }
 6326:     return $result;
 6327: }
 6328: 
 6329: =pod
 6330: 
 6331: =item scantron_validate_file
 6332: 
 6333:     Dispatch routine for doing validation of a bubble sheet data file.
 6334: 
 6335:     Also processes any necessary information resets that need to
 6336:     occur before validation begins (ignore previous corrections,
 6337:     restarting the skipped records processing)
 6338: 
 6339: =cut
 6340: 
 6341: sub scantron_validate_file {
 6342:     my ($r) = @_;
 6343:     my ($symb)=&get_symb($r);
 6344:     if (!$symb) {return '';}
 6345:     my $default_form_data=&defaultFormData($symb);
 6346:     
 6347:     # do the detection of only doing skipped records first befroe we delete
 6348:     # them when doing the corrections reset
 6349:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6350: 	&reset_skipping_status();
 6351:     }
 6352:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6353: 	&remember_current_skipped();
 6354: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6355:     }
 6356: 
 6357:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6358: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6359: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6360: 	&check_for_error($r,&scantron_remove_scan_data());
 6361: 	$env{'form.scantron_options_ignore'}='done';
 6362:     }
 6363: 
 6364:     if ($env{'form.scantron_corrections'}) {
 6365: 	&scantron_process_corrections($r);
 6366:     }
 6367:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6368:     #get the student pick code ready
 6369:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6370:     my $nav_error;
 6371:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6372:     if ($nav_error) {
 6373:         $r->print(&navmap_errormsg());
 6374:         return '';
 6375:     }
 6376:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6377:     $r->print($result);
 6378:     
 6379:     my @validate_phases=( 'sequence',
 6380: 			  'ID',
 6381: 			  'CODE',
 6382: 			  'doublebubble',
 6383: 			  'missingbubbles');
 6384:     if (!$env{'form.validatepass'}) {
 6385: 	$env{'form.validatepass'} = 0;
 6386:     }
 6387:     my $currentphase=$env{'form.validatepass'};
 6388: 
 6389: 
 6390:     my $stop=0;
 6391:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6392: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6393: 	$r->rflush();
 6394: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6395: 	{
 6396: 	    no strict 'refs';
 6397: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6398: 	}
 6399:     }
 6400:     if (!$stop) {
 6401: 	my $warning=&scantron_warning_screen('Start Grading');
 6402: 	$r->print(&mt('Validation process complete.').'<br />'.
 6403:                   $warning.
 6404:                   &mt('Perform verification for each student after storage of submissions?').
 6405:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6406:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6407:                   ('&nbsp;'x3).'<label>'.
 6408:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6409:                   '</label></span><br />'.
 6410:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6411:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6412:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6413:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6414:     } else {
 6415: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6416: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6417:     }
 6418:     if ($stop) {
 6419: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6420: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6421: 	    $r->print(' '.&mt('this error').' <br />');
 6422: 
 6423: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6424: 	} else {
 6425:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6426: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6427:             } else {
 6428:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6429:             }
 6430: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6431: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6432: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6433: 	}
 6434:     }
 6435:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6436:     return '';
 6437: }
 6438: 
 6439: 
 6440: =pod
 6441: 
 6442: =item scantron_remove_file
 6443: 
 6444:    Removes the requested bubble sheet data file, makes sure that
 6445:    scantron_original_<filename> is never removed
 6446: 
 6447: 
 6448: =cut
 6449: 
 6450: sub scantron_remove_file {
 6451:     my ($which)=@_;
 6452:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6453:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6454:     my $file='scantron_';
 6455:     if ($which eq 'corrected' || $which eq 'skipped') {
 6456: 	$file.=$which.'_';
 6457:     } else {
 6458: 	return 'refused';
 6459:     }
 6460:     $file.=$env{'form.scantron_selectfile'};
 6461:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6462: }
 6463: 
 6464: 
 6465: =pod
 6466: 
 6467: =item scantron_remove_scan_data
 6468: 
 6469:    Removes all scan_data correction for the requested bubble sheet
 6470:    data file.  (In the case that both the are doing skipped records we need
 6471:    to remember the old skipped lines for the time being so that element
 6472:    persists for a while.)
 6473: 
 6474: =cut
 6475: 
 6476: sub scantron_remove_scan_data {
 6477:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6478:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6479:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6480:     my @todelete;
 6481:     my $filename=$env{'form.scantron_selectfile'};
 6482:     foreach my $key (@keys) {
 6483: 	if ($key=~/^\Q$filename\E_/) {
 6484: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6485: 		$key=~/remember_skipping/) {
 6486: 		next;
 6487: 	    }
 6488: 	    push(@todelete,$key);
 6489: 	}
 6490:     }
 6491:     my $result;
 6492:     if (@todelete) {
 6493: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6494: 				       \@todelete,$cdom,$cname);
 6495:     } else {
 6496: 	$result = 'ok';
 6497:     }
 6498:     return $result;
 6499: }
 6500: 
 6501: 
 6502: =pod
 6503: 
 6504: =item scantron_getfile
 6505: 
 6506:     Fetches the requested bubble sheet data file (all 3 versions), and
 6507:     the scan_data hash
 6508:   
 6509:   Arguments:
 6510:     None
 6511: 
 6512:   Returns:
 6513:     2 hash references
 6514: 
 6515:      - first one has 
 6516:          orig      -
 6517:          corrected -
 6518:          skipped   -  each of which points to an array ref of the specified
 6519:                       file broken up into individual lines
 6520:          count     - number of scanlines
 6521:  
 6522:      - second is the scan_data hash possible keys are
 6523:        ($number refers to scanline numbered $number and thus the key affects
 6524:         only that scanline
 6525:         $bubline refers to the specific bubble line element and the aspects
 6526:         refers to that specific bubble line element)
 6527: 
 6528:        $number.user - username:domain to use
 6529:        $number.CODE_ignore_dup 
 6530:                     - ignore the duplicate CODE error 
 6531:        $number.useCODE
 6532:                     - use the CODE in the scanline as is
 6533:        $number.no_bubble.$bubline
 6534:                     - it is valid that there is no bubbled in bubble
 6535:                       at $number $bubline
 6536:        remember_skipping
 6537:                     - a frozen hash containing keys of $number and values
 6538:                       of either 
 6539:                         1 - we are on a 'do skipped records pass' and plan
 6540:                             on processing this line
 6541:                         2 - we are on a 'do skipped records pass' and this
 6542:                             scanline has been marked to skip yet again
 6543: 
 6544: =cut
 6545: 
 6546: sub scantron_getfile {
 6547:     #FIXME really would prefer a scantron directory
 6548:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6549:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6550:     my $lines;
 6551:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6552: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6553:     my %scanlines;
 6554:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6555:     my $temp=$scanlines{'orig'};
 6556:     $scanlines{'count'}=$#$temp;
 6557: 
 6558:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6559: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6560:     if ($lines eq '-1') {
 6561: 	$scanlines{'corrected'}=[];
 6562:     } else {
 6563: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6564:     }
 6565:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6566: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6567:     if ($lines eq '-1') {
 6568: 	$scanlines{'skipped'}=[];
 6569:     } else {
 6570: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6571:     }
 6572:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6573:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6574:     my %scan_data = @tmp;
 6575:     return (\%scanlines,\%scan_data);
 6576: }
 6577: 
 6578: =pod
 6579: 
 6580: =item lonnet_putfile
 6581: 
 6582:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6583: 
 6584:  Arguments:
 6585:    $contents - data to store
 6586:    $filename - filename to store $contents into
 6587: 
 6588:  Returns:
 6589:    result value from &Apache::lonnet::finishuserfileupload
 6590: 
 6591: =cut
 6592: 
 6593: sub lonnet_putfile {
 6594:     my ($contents,$filename)=@_;
 6595:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6596:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6597:     $env{'form.sillywaytopassafilearound'}=$contents;
 6598:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6599: 
 6600: }
 6601: 
 6602: =pod
 6603: 
 6604: =item scantron_putfile
 6605: 
 6606:     Stores the current version of the bubble sheet data files, and the
 6607:     scan_data hash. (Does not modify the original version only the
 6608:     corrected and skipped versions.
 6609: 
 6610:  Arguments:
 6611:     $scanlines - hash ref that looks like the first return value from
 6612:                  &scantron_getfile()
 6613:     $scan_data - hash ref that looks like the second return value from
 6614:                  &scantron_getfile()
 6615: 
 6616: =cut
 6617: 
 6618: sub scantron_putfile {
 6619:     my ($scanlines,$scan_data) = @_;
 6620:     #FIXME really would prefer a scantron directory
 6621:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6622:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6623:     if ($scanlines) {
 6624: 	my $prefix='scantron_';
 6625: # no need to update orig, shouldn't change
 6626: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6627: #		    $env{'form.scantron_selectfile'});
 6628: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6629: 			$prefix.'corrected_'.
 6630: 			$env{'form.scantron_selectfile'});
 6631: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6632: 			$prefix.'skipped_'.
 6633: 			$env{'form.scantron_selectfile'});
 6634:     }
 6635:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6636: }
 6637: 
 6638: =pod
 6639: 
 6640: =item scantron_get_line
 6641: 
 6642:    Returns the correct version of the scanline
 6643: 
 6644:  Arguments:
 6645:     $scanlines - hash ref that looks like the first return value from
 6646:                  &scantron_getfile()
 6647:     $scan_data - hash ref that looks like the second return value from
 6648:                  &scantron_getfile()
 6649:     $i         - number of the requested line (starts at 0)
 6650: 
 6651:  Returns:
 6652:    A scanline, (either the original or the corrected one if it
 6653:    exists), or undef if the requested scanline should be
 6654:    skipped. (Either because it's an skipped scanline, or it's an
 6655:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6656:    pass.
 6657: 
 6658: =cut
 6659: 
 6660: sub scantron_get_line {
 6661:     my ($scanlines,$scan_data,$i)=@_;
 6662:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6663:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6664:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6665:     return $scanlines->{'orig'}[$i]; 
 6666: }
 6667: 
 6668: =pod
 6669: 
 6670: =item scantron_todo_count
 6671: 
 6672:     Counts the number of scanlines that need processing.
 6673: 
 6674:  Arguments:
 6675:     $scanlines - hash ref that looks like the first return value from
 6676:                  &scantron_getfile()
 6677:     $scan_data - hash ref that looks like the second return value from
 6678:                  &scantron_getfile()
 6679: 
 6680:  Returns:
 6681:     $count - number of scanlines to process
 6682: 
 6683: =cut
 6684: 
 6685: sub get_todo_count {
 6686:     my ($scanlines,$scan_data)=@_;
 6687:     my $count=0;
 6688:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6689: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6690: 	if ($line=~/^[\s\cz]*$/) { next; }
 6691: 	$count++;
 6692:     }
 6693:     return $count;
 6694: }
 6695: 
 6696: =pod
 6697: 
 6698: =item scantron_put_line
 6699: 
 6700:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6701:     data file.
 6702: 
 6703:  Arguments:
 6704:     $scanlines - hash ref that looks like the first return value from
 6705:                  &scantron_getfile()
 6706:     $scan_data - hash ref that looks like the second return value from
 6707:                  &scantron_getfile()
 6708:     $i         - line number to update
 6709:     $newline   - contents of the updated scanline
 6710:     $skip      - if true make the line for skipping and update the
 6711:                  'skipped' file
 6712: 
 6713: =cut
 6714: 
 6715: sub scantron_put_line {
 6716:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6717:     if ($skip) {
 6718: 	$scanlines->{'skipped'}[$i]=$newline;
 6719: 	&start_skipping($scan_data,$i);
 6720: 	return;
 6721:     }
 6722:     $scanlines->{'corrected'}[$i]=$newline;
 6723: }
 6724: 
 6725: =pod
 6726: 
 6727: =item scantron_clear_skip
 6728: 
 6729:    Remove a line from the 'skipped' file
 6730: 
 6731:  Arguments:
 6732:     $scanlines - hash ref that looks like the first return value from
 6733:                  &scantron_getfile()
 6734:     $scan_data - hash ref that looks like the second return value from
 6735:                  &scantron_getfile()
 6736:     $i         - line number to update
 6737: 
 6738: =cut
 6739: 
 6740: sub scantron_clear_skip {
 6741:     my ($scanlines,$scan_data,$i)=@_;
 6742:     if (exists($scanlines->{'skipped'}[$i])) {
 6743: 	undef($scanlines->{'skipped'}[$i]);
 6744: 	return 1;
 6745:     }
 6746:     return 0;
 6747: }
 6748: 
 6749: =pod
 6750: 
 6751: =item scantron_filter_not_exam
 6752: 
 6753:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6754:    filter out resources that are not marked as 'exam' mode
 6755: 
 6756: =cut
 6757: 
 6758: sub scantron_filter_not_exam {
 6759:     my ($curres)=@_;
 6760:     
 6761:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6762: 	# if the user has asked to not have either hidden
 6763: 	# or 'randomout' controlled resources to be graded
 6764: 	# don't include them
 6765: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6766: 	    && $curres->randomout) {
 6767: 	    return 0;
 6768: 	}
 6769: 	return 1;
 6770:     }
 6771:     return 0;
 6772: }
 6773: 
 6774: =pod
 6775: 
 6776: =item scantron_validate_sequence
 6777: 
 6778:     Validates the selected sequence, checking for resource that are
 6779:     not set to exam mode.
 6780: 
 6781: =cut
 6782: 
 6783: sub scantron_validate_sequence {
 6784:     my ($r,$currentphase) = @_;
 6785: 
 6786:     my $navmap=Apache::lonnavmaps::navmap->new();
 6787:     unless (ref($navmap)) {
 6788:         $r->print(&navmap_errormsg());
 6789:         return (1,$currentphase);
 6790:     }
 6791:     my (undef,undef,$sequence)=
 6792: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6793: 
 6794:     my $map=$navmap->getResourceByUrl($sequence);
 6795: 
 6796:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6797:                                     value="ignore" />');
 6798:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6799: 	my @resources=
 6800: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6801: 	if (@resources) {
 6802: 	    $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>");
 6803: 	    return (1,$currentphase);
 6804: 	}
 6805:     }
 6806: 
 6807:     return (0,$currentphase+1);
 6808: }
 6809: 
 6810: 
 6811: 
 6812: sub scantron_validate_ID {
 6813:     my ($r,$currentphase) = @_;
 6814:     
 6815:     #get student info
 6816:     my $classlist=&Apache::loncoursedata::get_classlist();
 6817:     my %idmap=&username_to_idmap($classlist);
 6818: 
 6819:     #get scantron line setup
 6820:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6821:     my ($scanlines,$scan_data)=&scantron_getfile();
 6822: 
 6823:     my $nav_error;
 6824:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6825:     if ($nav_error) {
 6826:         $r->print(&navmap_errormsg());
 6827:         return(1,$currentphase);
 6828:     }
 6829: 
 6830:     my %found=('ids'=>{},'usernames'=>{});
 6831:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6832: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6833: 	if ($line=~/^[\s\cz]*$/) { next; }
 6834: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6835: 						 $scan_data);
 6836: 	my $id=$$scan_record{'scantron.ID'};
 6837: 	my $found;
 6838: 	foreach my $checkid (keys(%idmap)) {
 6839: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6840: 	}
 6841: 	if ($found) {
 6842: 	    my $username=$idmap{$found};
 6843: 	    if ($found{'ids'}{$found}) {
 6844: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6845: 					 $line,'duplicateID',$found);
 6846: 		return(1,$currentphase);
 6847: 	    } elsif ($found{'usernames'}{$username}) {
 6848: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6849: 					 $line,'duplicateID',$username);
 6850: 		return(1,$currentphase);
 6851: 	    }
 6852: 	    #FIXME store away line we previously saw the ID on to use above
 6853: 	    $found{'ids'}{$found}++;
 6854: 	    $found{'usernames'}{$username}++;
 6855: 	} else {
 6856: 	    if ($id =~ /^\s*$/) {
 6857: 		my $username=&scan_data($scan_data,"$i.user");
 6858: 		if (defined($username) && $found{'usernames'}{$username}) {
 6859: 		    &scantron_get_correction($r,$i,$scan_record,
 6860: 					     \%scantron_config,
 6861: 					     $line,'duplicateID',$username);
 6862: 		    return(1,$currentphase);
 6863: 		} elsif (!defined($username)) {
 6864: 		    &scantron_get_correction($r,$i,$scan_record,
 6865: 					     \%scantron_config,
 6866: 					     $line,'incorrectID');
 6867: 		    return(1,$currentphase);
 6868: 		}
 6869: 		$found{'usernames'}{$username}++;
 6870: 	    } else {
 6871: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6872: 					 $line,'incorrectID');
 6873: 		return(1,$currentphase);
 6874: 	    }
 6875: 	}
 6876:     }
 6877: 
 6878:     return (0,$currentphase+1);
 6879: }
 6880: 
 6881: 
 6882: sub scantron_get_correction {
 6883:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6884: #FIXME in the case of a duplicated ID the previous line, probably need
 6885: #to show both the current line and the previous one and allow skipping
 6886: #the previous one or the current one
 6887: 
 6888:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6889: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6890: 			    " for PaperID <tt>[_1]</tt>",
 6891: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6892:     } else {
 6893: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6894: 			    " in scanline [_1] <pre>[_2]</pre>",
 6895: 			    $i,$line)."</p> \n");
 6896:     }
 6897:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6898: 			  "The name on the paper is [_2],[_3]",
 6899: 			  $$scan_record{'scantron.ID'},
 6900: 			  $$scan_record{'scantron.LastName'},
 6901: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6902: 
 6903:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6904:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6905:                            # Array populated for doublebubble or
 6906:     my @lines_to_correct;  # missingbubble errors to build javascript
 6907:                            # to validate radio button checking   
 6908: 
 6909:     if ($error =~ /ID$/) {
 6910: 	if ($error eq 'incorrectID') {
 6911: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6912: 		      "</p>\n");
 6913: 	} elsif ($error eq 'duplicateID') {
 6914: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6915: 	}
 6916: 	$r->print($message);
 6917: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6918: 	$r->print("\n<ul><li> ");
 6919: 	#FIXME it would be nice if this sent back the user ID and
 6920: 	#could do partial userID matches
 6921: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6922: 				       'scantron_username','scantron_domain'));
 6923: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6924: 	$r->print("\n@".
 6925: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6926: 
 6927: 	$r->print('</li>');
 6928:     } elsif ($error =~ /CODE$/) {
 6929: 	if ($error eq 'incorrectCODE') {
 6930: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6931: 	} elsif ($error eq 'duplicateCODE') {
 6932: 	    $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");
 6933: 	}
 6934: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6935: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6936: 	$r->print($message);
 6937: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6938: 	$r->print("\n<br /> ");
 6939: 	my $i=0;
 6940: 	if ($error eq 'incorrectCODE' 
 6941: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6942: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6943: 	    if ($closest > 0) {
 6944: 		foreach my $testcode (@{$closest}) {
 6945: 		    my $checked='';
 6946: 		    if (!$i) { $checked=' checked="checked"'; }
 6947: 		    $r->print("
 6948:    <label>
 6949:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6950:        ".&mt("Use the similar CODE [_1] instead.",
 6951: 	    "<b><tt>".$testcode."</tt></b>")."
 6952:     </label>
 6953:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6954: 		    $r->print("\n<br />");
 6955: 		    $i++;
 6956: 		}
 6957: 	    }
 6958: 	}
 6959: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6960: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6961: 	    $r->print("
 6962:     <label>
 6963:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6964:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6965: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6966:     </label>");
 6967: 	    $r->print("\n<br />");
 6968: 	}
 6969: 
 6970: 	$r->print(<<ENDSCRIPT);
 6971: <script type="text/javascript">
 6972: function change_radio(field) {
 6973:     var slct=document.scantronupload.scantron_CODE_resolution;
 6974:     var i;
 6975:     for (i=0;i<slct.length;i++) {
 6976:         if (slct[i].value==field) { slct[i].checked=true; }
 6977:     }
 6978: }
 6979: </script>
 6980: ENDSCRIPT
 6981: 	my $href="/adm/pickcode?".
 6982: 	   "form=".&escape("scantronupload").
 6983: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6984: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6985: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6986: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6987: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6988: 	    $r->print("
 6989:     <label>
 6990:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6991:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6992: 	     "<a target='_blank' href='$href'>","</a>")."
 6993:     </label> 
 6994:     ".&mt("Selected CODE is [_1]",'<input readonly="readonly" type="text" size="8" name="scantron_CODE_selectedvalue" onfocus="javascript:change_radio(\'use_found\')" onchange="javascript:change_radio(\'use_found\')" />'));
 6995: 	    $r->print("\n<br />");
 6996: 	}
 6997: 	$r->print("
 6998:     <label>
 6999:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7000:        ".&mt("Use [_1] as the CODE.",
 7001: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7002: 	$r->print("\n<br /><br />");
 7003:     } elsif ($error eq 'doublebubble') {
 7004: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7005: 
 7006: 	# The form field scantron_questions is acutally a list of line numbers.
 7007: 	# represented by this form so:
 7008: 
 7009: 	my $line_list = &questions_to_line_list($arg);
 7010: 
 7011: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7012: 		  $line_list.'" />');
 7013: 	$r->print($message);
 7014: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7015: 	foreach my $question (@{$arg}) {
 7016: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7017:                                                    $scan_record, $error);
 7018:             push(@lines_to_correct,@linenums);
 7019: 	}
 7020:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7021:     } elsif ($error eq 'missingbubble') {
 7022: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 7023: 	$r->print($message);
 7024: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7025: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7026: 
 7027: 	# The form field scantron_questions is actually a list of line numbers not
 7028: 	# a list of question numbers. Therefore:
 7029: 	#
 7030: 	
 7031: 	my $line_list = &questions_to_line_list($arg);
 7032: 
 7033: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7034: 		  $line_list.'" />');
 7035: 	foreach my $question (@{$arg}) {
 7036: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7037:                                                    $scan_record, $error);
 7038:             push(@lines_to_correct,@linenums);
 7039: 	}
 7040:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7041:     } else {
 7042: 	$r->print("\n<ul>");
 7043:     }
 7044:     $r->print("\n</li></ul>");
 7045: }
 7046: 
 7047: sub verify_bubbles_checked {
 7048:     my (@ansnums) = @_;
 7049:     my $ansnumstr = join('","',@ansnums);
 7050:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7051:     my $output = (<<ENDSCRIPT);
 7052: <script type="text/javascript">
 7053: function verify_bubble_radio(form) {
 7054:     var ansnumArray = new Array ("$ansnumstr");
 7055:     var need_bubble_count = 0;
 7056:     for (var i=0; i<ansnumArray.length; i++) {
 7057:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7058:             var bubble_picked = 0; 
 7059:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7060:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7061:                     bubble_picked = 1;
 7062:                 }
 7063:             }
 7064:             if (bubble_picked == 0) {
 7065:                 need_bubble_count ++;
 7066:             }
 7067:         }
 7068:     }
 7069:     if (need_bubble_count) {
 7070:         alert("$warning");
 7071:         return;
 7072:     }
 7073:     form.submit(); 
 7074: }
 7075: </script>
 7076: ENDSCRIPT
 7077:     return $output;
 7078: }
 7079: 
 7080: =pod
 7081: 
 7082: =item  questions_to_line_list
 7083: 
 7084: Converts a list of questions into a string of comma separated
 7085: line numbers in the answer sheet used by the questions.  This is
 7086: used to fill in the scantron_questions form field.
 7087: 
 7088:   Arguments:
 7089:      questions    - Reference to an array of questions.
 7090: 
 7091: =cut
 7092: 
 7093: 
 7094: sub questions_to_line_list {
 7095:     my ($questions) = @_;
 7096:     my @lines;
 7097: 
 7098:     foreach my $item (@{$questions}) {
 7099:         my $question = $item;
 7100:         my ($first,$count,$last);
 7101:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7102:             $question = $1;
 7103:             my $subquestion = $2;
 7104:             $first = $first_bubble_line{$question-1} + 1;
 7105:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7106:             my $subcount = 1;
 7107:             while ($subcount<$subquestion) {
 7108:                 $first += $subans[$subcount-1];
 7109:                 $subcount ++;
 7110:             }
 7111:             $count = $subans[$subquestion-1];
 7112:         } else {
 7113: 	    $first   = $first_bubble_line{$question-1} + 1;
 7114: 	    $count   = $bubble_lines_per_response{$question-1};
 7115:         }
 7116:         $last = $first+$count-1;
 7117:         push(@lines, ($first..$last));
 7118:     }
 7119:     return join(',', @lines);
 7120: }
 7121: 
 7122: =pod 
 7123: 
 7124: =item prompt_for_corrections
 7125: 
 7126: Prompts for a potentially multiline correction to the
 7127: user's bubbling (factors out common code from scantron_get_correction
 7128: for multi and missing bubble cases).
 7129: 
 7130:  Arguments:
 7131:    $r           - Apache request object.
 7132:    $question    - The question number to prompt for.
 7133:    $scan_config - The scantron file configuration hash.
 7134:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7135:    $error       - Type of error
 7136: 
 7137:  Implicit inputs:
 7138:    %bubble_lines_per_response   - Starting line numbers for each question.
 7139:                                   Numbered from 0 (but question numbers are from
 7140:                                   1.
 7141:    %first_bubble_line           - Starting bubble line for each question.
 7142:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7143:                                   type problems render as separate sub-questions, 
 7144:                                   in exam mode. This hash contains a 
 7145:                                   comma-separated list of the lines per 
 7146:                                   sub-question.
 7147:    %responsetype_per_response   - essayresponse, formularesponse,
 7148:                                   stringresponse, imageresponse, reactionresponse,
 7149:                                   and organicresponse type problem parts can have
 7150:                                   multiple lines per response if the weight
 7151:                                   assigned exceeds 10.  In this case, only
 7152:                                   one bubble per line is permitted, but more 
 7153:                                   than one line might contain bubbles, e.g.
 7154:                                   bubbling of: line 1 - J, line 2 - J, 
 7155:                                   line 3 - B would assign 22 points.  
 7156: 
 7157: =cut
 7158: 
 7159: sub prompt_for_corrections {
 7160:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7161:     my ($current_line,$lines);
 7162:     my @linenums;
 7163:     my $questionnum = $question;
 7164:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7165:         $question = $1;
 7166:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7167:         my $subquestion = $2;
 7168:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7169:         my $subcount = 1;
 7170:         while ($subcount<$subquestion) {
 7171:             $current_line += $subans[$subcount-1];
 7172:             $subcount ++;
 7173:         }
 7174:         $lines = $subans[$subquestion-1];
 7175:     } else {
 7176:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7177:         $lines        = $bubble_lines_per_response{$question-1};
 7178:     }
 7179:     if ($lines > 1) {
 7180:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7181:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7182:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7183:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7184:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7185:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7186:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7187:             $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 bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet 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 />');
 7188:         } else {
 7189:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7190:         }
 7191:     }
 7192:     for (my $i =0; $i < $lines; $i++) {
 7193:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7194: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7195: 	        		  $questionnum,$error,split('', $selected));
 7196:         push(@linenums,$current_line);
 7197: 	$current_line++;
 7198:     }
 7199:     if ($lines > 1) {
 7200: 	$r->print("<hr /><br />");
 7201:     }
 7202:     return @linenums;
 7203: }
 7204: 
 7205: =pod
 7206: 
 7207: =item scantron_bubble_selector
 7208:   
 7209:    Generates the html radiobuttons to correct a single bubble line
 7210:    possibly showing the existing the selected bubbles if known
 7211: 
 7212:  Arguments:
 7213:     $r           - Apache request object
 7214:     $scan_config - hash from &get_scantron_config()
 7215:     $line        - Number of the line being displayed.
 7216:     $questionnum - Question number (may include subquestion)
 7217:     $error       - Type of error.
 7218:     @selected    - Array of bubbles picked on this line.
 7219: 
 7220: =cut
 7221: 
 7222: sub scantron_bubble_selector {
 7223:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7224:     my $max=$$scan_config{'Qlength'};
 7225: 
 7226:     my $scmode=$$scan_config{'Qon'};
 7227:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7228: 
 7229:     my @alphabet=('A'..'Z');
 7230:     $r->print(&Apache::loncommon::start_data_table().
 7231:               &Apache::loncommon::start_data_table_row());
 7232:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7233:     for (my $i=0;$i<$max+1;$i++) {
 7234: 	$r->print("\n".'<td align="center">');
 7235: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7236: 	else { $r->print('&nbsp;'); }
 7237: 	$r->print('</td>');
 7238:     }
 7239:     $r->print(&Apache::loncommon::end_data_table_row().
 7240:               &Apache::loncommon::start_data_table_row());
 7241:     for (my $i=0;$i<$max;$i++) {
 7242: 	$r->print("\n".
 7243: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7244: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7245:     }
 7246:     my $nobub_checked = ' ';
 7247:     if ($error eq 'missingbubble') {
 7248:         $nobub_checked = ' checked = "checked" ';
 7249:     }
 7250:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7251: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7252:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7253:               $line.'" value="'.$questionnum.'" /></td>');
 7254:     $r->print(&Apache::loncommon::end_data_table_row().
 7255:               &Apache::loncommon::end_data_table());
 7256: }
 7257: 
 7258: =pod
 7259: 
 7260: =item num_matches
 7261: 
 7262:    Counts the number of characters that are the same between the two arguments.
 7263: 
 7264:  Arguments:
 7265:    $orig - CODE from the scanline
 7266:    $code - CODE to match against
 7267: 
 7268:  Returns:
 7269:    $count - integer count of the number of same characters between the
 7270:             two arguments
 7271: 
 7272: =cut
 7273: 
 7274: sub num_matches {
 7275:     my ($orig,$code) = @_;
 7276:     my @code=split(//,$code);
 7277:     my @orig=split(//,$orig);
 7278:     my $same=0;
 7279:     for (my $i=0;$i<scalar(@code);$i++) {
 7280: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7281:     }
 7282:     return $same;
 7283: }
 7284: 
 7285: =pod
 7286: 
 7287: =item scantron_get_closely_matching_CODEs
 7288: 
 7289:    Cycles through all CODEs and finds the set that has the greatest
 7290:    number of same characters as the provided CODE
 7291: 
 7292:  Arguments:
 7293:    $allcodes - hash ref returned by &get_codes()
 7294:    $CODE     - CODE from the current scanline
 7295: 
 7296:  Returns:
 7297:    2 element list
 7298:     - first elements is number of how closely matching the best fit is 
 7299:       (5 means best set has 5 matching characters)
 7300:     - second element is an arrary ref containing the set of valid CODEs
 7301:       that best fit the passed in CODE
 7302: 
 7303: =cut
 7304: 
 7305: sub scantron_get_closely_matching_CODEs {
 7306:     my ($allcodes,$CODE)=@_;
 7307:     my @CODEs;
 7308:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7309: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7310:     }
 7311: 
 7312:     return ($#CODEs,$CODEs[-1]);
 7313: }
 7314: 
 7315: =pod
 7316: 
 7317: =item get_codes
 7318: 
 7319:    Builds a hash which has keys of all of the valid CODEs from the selected
 7320:    set of remembered CODEs.
 7321: 
 7322:  Arguments:
 7323:   $old_name - name of the set of remembered CODEs
 7324:   $cdom     - domain of the course
 7325:   $cnum     - internal course name
 7326: 
 7327:  Returns:
 7328:   %allcodes - keys are the valid CODEs, values are all 1
 7329: 
 7330: =cut
 7331: 
 7332: sub get_codes {
 7333:     my ($old_name, $cdom, $cnum) = @_;
 7334:     if (!$old_name) {
 7335: 	$old_name=$env{'form.scantron_CODElist'};
 7336:     }
 7337:     if (!$cdom) {
 7338: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7339:     }
 7340:     if (!$cnum) {
 7341: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7342:     }
 7343:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7344: 				    $cdom,$cnum);
 7345:     my %allcodes;
 7346:     if ($result{"type\0$old_name"} eq 'number') {
 7347: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7348:     } else {
 7349: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7350:     }
 7351:     return %allcodes;
 7352: }
 7353: 
 7354: =pod
 7355: 
 7356: =item scantron_validate_CODE
 7357: 
 7358:    Validates all scanlines in the selected file to not have any
 7359:    invalid or underspecified CODEs and that none of the codes are
 7360:    duplicated if this was requested.
 7361: 
 7362: =cut
 7363: 
 7364: sub scantron_validate_CODE {
 7365:     my ($r,$currentphase) = @_;
 7366:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7367:     if ($scantron_config{'CODElocation'} &&
 7368: 	$scantron_config{'CODEstart'} &&
 7369: 	$scantron_config{'CODElength'}) {
 7370: 	if (!defined($env{'form.scantron_CODElist'})) {
 7371: 	    &FIXME_blow_up()
 7372: 	}
 7373:     } else {
 7374: 	return (0,$currentphase+1);
 7375:     }
 7376:     
 7377:     my %usedCODEs;
 7378: 
 7379:     my %allcodes=&get_codes();
 7380: 
 7381:     my $nav_error;
 7382:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7383:     if ($nav_error) {
 7384:         $r->print(&navmap_errormsg());
 7385:         return(1,$currentphase);
 7386:     }
 7387: 
 7388:     my ($scanlines,$scan_data)=&scantron_getfile();
 7389:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7390: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7391: 	if ($line=~/^[\s\cz]*$/) { next; }
 7392: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7393: 						 $scan_data);
 7394: 	my $CODE=$$scan_record{'scantron.CODE'};
 7395: 	my $error=0;
 7396: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7397: 	    &scantron_get_correction($r,$i,$scan_record,
 7398: 				     \%scantron_config,
 7399: 				     $line,'incorrectCODE',\%allcodes);
 7400: 	    return(1,$currentphase);
 7401: 	}
 7402: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7403: 	    && !$$scan_record{'scantron.useCODE'}) {
 7404: 	    &scantron_get_correction($r,$i,$scan_record,
 7405: 				     \%scantron_config,
 7406: 				     $line,'incorrectCODE',\%allcodes);
 7407: 	    return(1,$currentphase);
 7408: 	}
 7409: 	if (exists($usedCODEs{$CODE}) 
 7410: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7411: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7412: 	    &scantron_get_correction($r,$i,$scan_record,
 7413: 				     \%scantron_config,
 7414: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7415: 	    return(1,$currentphase);
 7416: 	}
 7417: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7418:     }
 7419:     return (0,$currentphase+1);
 7420: }
 7421: 
 7422: =pod
 7423: 
 7424: =item scantron_validate_doublebubble
 7425: 
 7426:    Validates all scanlines in the selected file to not have any
 7427:    bubble lines with multiple bubbles marked.
 7428: 
 7429: =cut
 7430: 
 7431: sub scantron_validate_doublebubble {
 7432:     my ($r,$currentphase) = @_;
 7433:     #get student info
 7434:     my $classlist=&Apache::loncoursedata::get_classlist();
 7435:     my %idmap=&username_to_idmap($classlist);
 7436: 
 7437:     #get scantron line setup
 7438:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7439:     my ($scanlines,$scan_data)=&scantron_getfile();
 7440:     my $nav_error;
 7441:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7442:     if ($nav_error) {
 7443:         $r->print(&navmap_errormsg());
 7444:         return(1,$currentphase);
 7445:     }
 7446: 
 7447:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7448: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7449: 	if ($line=~/^[\s\cz]*$/) { next; }
 7450: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7451: 						 $scan_data);
 7452: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7453: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7454: 				 'doublebubble',
 7455: 				 $$scan_record{'scantron.doubleerror'});
 7456:     	return (1,$currentphase);
 7457:     }
 7458:     return (0,$currentphase+1);
 7459: }
 7460: 
 7461: 
 7462: sub scantron_get_maxbubble {
 7463:     my ($nav_error) = @_;
 7464:     if (defined($env{'form.scantron_maxbubble'}) &&
 7465: 	$env{'form.scantron_maxbubble'}) {
 7466: 	&restore_bubble_lines();
 7467: 	return $env{'form.scantron_maxbubble'};
 7468:     }
 7469: 
 7470:     my (undef, undef, $sequence) =
 7471: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7472: 
 7473:     my $navmap=Apache::lonnavmaps::navmap->new();
 7474:     unless (ref($navmap)) {
 7475:         if (ref($nav_error)) {
 7476:             $$nav_error = 1;
 7477:         }
 7478:         return;
 7479:     }
 7480:     my $map=$navmap->getResourceByUrl($sequence);
 7481:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7482: 
 7483:     &Apache::lonxml::clear_problem_counter();
 7484: 
 7485:     my $uname       = $env{'user.name'};
 7486:     my $udom        = $env{'user.domain'};
 7487:     my $cid         = $env{'request.course.id'};
 7488:     my $total_lines = 0;
 7489:     %bubble_lines_per_response = ();
 7490:     %first_bubble_line         = ();
 7491:     %subdivided_bubble_lines   = ();
 7492:     %responsetype_per_response = ();
 7493: 
 7494:     my $response_number = 0;
 7495:     my $bubble_line     = 0;
 7496:     foreach my $resource (@resources) {
 7497:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7498:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7499: 	    foreach my $part_id (@{$parts}) {
 7500:                 my $lines;
 7501: 
 7502: 	        # TODO - make this a persistent hash not an array.
 7503: 
 7504:                 # optionresponse, matchresponse and rankresponse type items 
 7505:                 # render as separate sub-questions in exam mode.
 7506:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7507:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7508:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7509:                     my ($numbub,$numshown);
 7510:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7511:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7512:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7513:                         }
 7514:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7515:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7516:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7517:                         }
 7518:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7519:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7520:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7521:                         }
 7522:                     }
 7523:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7524:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7525:                     }
 7526:                     my $bubbles_per_line = 10;
 7527:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7528:                     if (($numbub % $bubbles_per_line) != 0) {
 7529:                         $inner_bubble_lines++;
 7530:                     }
 7531:                     for (my $i=0; $i<$numshown; $i++) {
 7532:                         $subdivided_bubble_lines{$response_number} .= 
 7533:                             $inner_bubble_lines.',';
 7534:                     }
 7535:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7536:                     $lines = $numshown * $inner_bubble_lines;
 7537:                 } else {
 7538:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7539:                 } 
 7540: 
 7541:                 $first_bubble_line{$response_number} = $bubble_line;
 7542: 	        $bubble_lines_per_response{$response_number} = $lines;
 7543:                 $responsetype_per_response{$response_number} = 
 7544:                     $analysis->{$part_id.'.type'};
 7545: 	        $response_number++;
 7546: 
 7547: 	        $bubble_line +=  $lines;
 7548: 	        $total_lines +=  $lines;
 7549: 	    }
 7550:         }
 7551:     }
 7552:     &Apache::lonnet::delenv('scantron.');
 7553: 
 7554:     &save_bubble_lines();
 7555:     $env{'form.scantron_maxbubble'} =
 7556: 	$total_lines;
 7557:     return $env{'form.scantron_maxbubble'};
 7558: }
 7559: 
 7560: sub scantron_validate_missingbubbles {
 7561:     my ($r,$currentphase) = @_;
 7562:     #get student info
 7563:     my $classlist=&Apache::loncoursedata::get_classlist();
 7564:     my %idmap=&username_to_idmap($classlist);
 7565: 
 7566:     #get scantron line setup
 7567:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7568:     my ($scanlines,$scan_data)=&scantron_getfile();
 7569:     my $nav_error;
 7570:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7571:     if ($nav_error) {
 7572:         return(1,$currentphase);
 7573:     }
 7574:     if (!$max_bubble) { $max_bubble=2**31; }
 7575:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7576: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7577: 	if ($line=~/^[\s\cz]*$/) { next; }
 7578: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7579: 						 $scan_data);
 7580: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7581: 	my @to_correct;
 7582: 	
 7583: 	# Probably here's where the error is...
 7584: 
 7585: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7586:             my $lastbubble;
 7587:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7588:                my $question = $1;
 7589:                my $subquestion = $2;
 7590:                if (!defined($first_bubble_line{$question -1})) { next; }
 7591:                my $first = $first_bubble_line{$question-1};
 7592:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7593:                my $subcount = 1;
 7594:                while ($subcount<$subquestion) {
 7595:                    $first += $subans[$subcount-1];
 7596:                    $subcount ++;
 7597:                }
 7598:                my $count = $subans[$subquestion-1];
 7599:                $lastbubble = $first + $count;
 7600:             } else {
 7601:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7602:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7603:             }
 7604:             if ($lastbubble > $max_bubble) { next; }
 7605: 	    push(@to_correct,$missing);
 7606: 	}
 7607: 	if (@to_correct) {
 7608: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7609: 				     $line,'missingbubble',\@to_correct);
 7610: 	    return (1,$currentphase);
 7611: 	}
 7612: 
 7613:     }
 7614:     return (0,$currentphase+1);
 7615: }
 7616: 
 7617: 
 7618: sub scantron_process_students {
 7619:     my ($r) = @_;
 7620: 
 7621:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7622:     my ($symb)=&get_symb($r);
 7623:     if (!$symb) {
 7624: 	return '';
 7625:     }
 7626:     my $default_form_data=&defaultFormData($symb);
 7627: 
 7628:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7629:     my ($scanlines,$scan_data)=&scantron_getfile();
 7630:     my $classlist=&Apache::loncoursedata::get_classlist();
 7631:     my %idmap=&username_to_idmap($classlist);
 7632:     my $navmap=Apache::lonnavmaps::navmap->new();
 7633:     unless (ref($navmap)) {
 7634:         $r->print(&navmap_errormsg());
 7635:         return '';
 7636:     }  
 7637:     my $map=$navmap->getResourceByUrl($sequence);
 7638:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7639:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7640:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7641:                             \%grader_randomlists_by_symb);
 7642:     my $resource_error;
 7643:     foreach my $resource (@resources) {
 7644:         my $ressymb;
 7645:         if (ref($resource)) {
 7646:             $ressymb = $resource->symb();
 7647:         } else {
 7648:             $resource_error = 1;
 7649:             last;
 7650:         }
 7651:         my ($analysis,$parts) =
 7652:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7653:                                       $env{'user.name'},$env{'user.domain'},1);
 7654:         $grader_partids_by_symb{$ressymb} = $parts;
 7655:         if (ref($analysis) eq 'HASH') {
 7656:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7657:                 $grader_randomlists_by_symb{$ressymb} = 
 7658:                     $analysis->{'parts_withrandomlist'};
 7659:             }
 7660:         }
 7661:     }
 7662:     if ($resource_error) {
 7663:         $r->print(&navmap_errormsg());
 7664:         return '';
 7665:     }
 7666: 
 7667:     my ($uname,$udom);
 7668:     my $result= <<SCANTRONFORM;
 7669: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7670:   <input type="hidden" name="command" value="scantron_configphase" />
 7671:   $default_form_data
 7672: SCANTRONFORM
 7673:     $r->print($result);
 7674: 
 7675:     my @delayqueue;
 7676:     my (%completedstudents,%scandata);
 7677:     
 7678:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7679:     my $count=&get_todo_count($scanlines,$scan_data);
 7680:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7681:  				    'Bubblesheet Progress',$count,
 7682: 				    'inline',undef,'scantronupload');
 7683:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7684: 					  'Processing first student');
 7685:     $r->print('<br />');
 7686:     my $start=&Time::HiRes::time();
 7687:     my $i=-1;
 7688:     my $started;
 7689: 
 7690:     my $nav_error;
 7691:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7692:     if ($nav_error) {
 7693:         $r->print(&navmap_errormsg());
 7694:         return '';
 7695:     }
 7696: 
 7697:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7698:     # the user and return.
 7699: 
 7700:     if ($ssi_error) {
 7701: 	$r->print("</form>");
 7702: 	&ssi_print_error($r);
 7703: 	$r->print(&show_grading_menu_form($symb));
 7704:         &Apache::lonnet::remove_lock($lock);
 7705: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7706:     }
 7707: 
 7708:     my %lettdig = &letter_to_digits();
 7709:     my $numletts = scalar(keys(%lettdig));
 7710: 
 7711:     while ($i<$scanlines->{'count'}) {
 7712:  	($uname,$udom)=('','');
 7713:  	$i++;
 7714:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7715:  	if ($line=~/^[\s\cz]*$/) { next; }
 7716: 	if ($started) {
 7717: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7718: 						     'last student');
 7719: 	}
 7720: 	$started=1;
 7721:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7722:  						 $scan_data);
 7723:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7724:  					      \%idmap,$i)) {
 7725:   	    &scantron_add_delay(\@delayqueue,$line,
 7726:  				'Unable to find a student that matches',1);
 7727:  	    next;
 7728:   	}
 7729:  	if (exists $completedstudents{$uname}) {
 7730:  	    &scantron_add_delay(\@delayqueue,$line,
 7731:  				'Student '.$uname.' has multiple sheets',2);
 7732:  	    next;
 7733:  	}
 7734:   	($uname,$udom)=split(/:/,$uname);
 7735: 
 7736:         my (%partids_by_symb,$res_error);
 7737:         foreach my $resource (@resources) {
 7738:             my $ressymb;
 7739:             if (ref($resource)) {
 7740:                 $ressymb = $resource->symb();
 7741:             } else {
 7742:                 $res_error = 1;
 7743:                 last;
 7744:             }
 7745:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7746:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7747:                 my ($analysis,$parts) =
 7748:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7749:                 $partids_by_symb{$ressymb} = $parts;
 7750:             } else {
 7751:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7752:             }
 7753:         }
 7754: 
 7755:         if ($res_error) {
 7756:             &scantron_add_delay(\@delayqueue,$line,
 7757:                                 'An error occurred while grading student '.$uname,2);
 7758:             next;
 7759:         }
 7760: 
 7761: 	&Apache::lonxml::clear_problem_counter();
 7762:   	&Apache::lonnet::appenv($scan_record);
 7763: 
 7764: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7765: 	    &scantron_putfile($scanlines,$scan_data);
 7766: 	}
 7767: 	
 7768:         my $scancode;
 7769:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7770:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7771:             $scancode = $scan_record->{'scantron.CODE'};
 7772:         } else {
 7773:             $scancode = '';
 7774:         }
 7775: 
 7776:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7777:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7778:             $ssi_error = 0; # So end of handler error message does not trigger.
 7779:             $r->print("</form>");
 7780:             &ssi_print_error($r);
 7781:             $r->print(&show_grading_menu_form($symb));
 7782:             &Apache::lonnet::remove_lock($lock);
 7783:             return '';      # Why return ''?  Beats me.
 7784:         }
 7785: 
 7786: 	$completedstudents{$uname}={'line'=>$line};
 7787:         if ($env{'form.verifyrecord'}) {
 7788:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7789:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7790:             chomp($studentdata);
 7791:             $studentdata =~ s/\r$//;
 7792:             my $studentrecord = '';
 7793:             my $counter = -1;
 7794:             foreach my $resource (@resources) {
 7795:                 my $ressymb = $resource->symb();
 7796:                 ($counter,my $recording) =
 7797:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7798:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7799:                                              \%scantron_config,\%lettdig,$numletts);
 7800:                 $studentrecord .= $recording;
 7801:             }
 7802:             if ($studentrecord ne $studentdata) {
 7803:                 &Apache::lonxml::clear_problem_counter();
 7804:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7805:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7806:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7807:                     $r->print("</form>");
 7808:                     &ssi_print_error($r);
 7809:                     $r->print(&show_grading_menu_form($symb));
 7810:                     &Apache::lonnet::remove_lock($lock);
 7811:                     delete($completedstudents{$uname});
 7812:                     return '';
 7813:                 }
 7814:                 $counter = -1;
 7815:                 $studentrecord = '';
 7816:                 foreach my $resource (@resources) {
 7817:                     my $ressymb = $resource->symb();
 7818:                     ($counter,my $recording) =
 7819:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7820:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7821:                                                  \%scantron_config,\%lettdig,$numletts);
 7822:                     $studentrecord .= $recording;
 7823:                 }
 7824:                 if ($studentrecord ne $studentdata) {
 7825:                     $r->print('<p><span class="LC_error">');
 7826:                     if ($scancode eq '') {
 7827:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7828:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7829:                     } else {
 7830:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7831:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7832:                     }
 7833:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7834:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7835:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7836:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7837:                               &Apache::loncommon::start_data_table_row().
 7838:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7839:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7840:                               &Apache::loncommon::end_data_table_row().
 7841:                               &Apache::loncommon::start_data_table_row().
 7842:                               '<td>Stored submissions</td>'.
 7843:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7844:                               &Apache::loncommon::end_data_table_row().
 7845:                               &Apache::loncommon::end_data_table().'</p>');
 7846:                 } else {
 7847:                     $r->print('<br /><span class="LC_warning">'.
 7848:                              &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 />'.
 7849:                              &mt("As a consequence, this user's submission history records two tries.").
 7850:                                  '</span><br />');
 7851:                 }
 7852:             }
 7853:         }
 7854:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7855:     } continue {
 7856: 	&Apache::lonxml::clear_problem_counter();
 7857: 	&Apache::lonnet::delenv('scantron.');
 7858:     }
 7859:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7860:     &Apache::lonnet::remove_lock($lock);
 7861: #    my $lasttime = &Time::HiRes::time()-$start;
 7862: #    $r->print("<p>took $lasttime</p>");
 7863: 
 7864:     $r->print("</form>");
 7865:     $r->print(&show_grading_menu_form($symb));
 7866:     return '';
 7867: }
 7868: 
 7869: sub graders_resources_pass {
 7870:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7871:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7872:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7873:         foreach my $resource (@{$resources}) {
 7874:             my $ressymb = $resource->symb();
 7875:             my ($analysis,$parts) =
 7876:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7877:                                           $env{'user.name'},$env{'user.domain'},1);
 7878:             $grader_partids_by_symb->{$ressymb} = $parts;
 7879:             if (ref($analysis) eq 'HASH') {
 7880:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7881:                     $grader_randomlists_by_symb->{$ressymb} =
 7882:                         $analysis->{'parts_withrandomlist'};
 7883:                 }
 7884:             }
 7885:         }
 7886:     }
 7887:     return;
 7888: }
 7889: 
 7890: sub grade_student_bubbles {
 7891:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7892:     if (ref($resources) eq 'ARRAY') {
 7893:         my $count = 0;
 7894:         foreach my $resource (@{$resources}) {
 7895:             my $ressymb = $resource->symb();
 7896:             my %form = ('submitted'      => 'scantron',
 7897:                         'grade_target'   => 'grade',
 7898:                         'grade_username' => $uname,
 7899:                         'grade_domain'   => $udom,
 7900:                         'grade_courseid' => $env{'request.course.id'},
 7901:                         'grade_symb'     => $ressymb,
 7902:                         'CODE'           => $scancode
 7903:                        );
 7904:             if (ref($parts) eq 'HASH') {
 7905:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7906:                     foreach my $part (@{$parts->{$ressymb}}) {
 7907:                         $form{'scantron_questnum_start.'.$part} =
 7908:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7909:                         $count++;
 7910:                     }
 7911:                 }
 7912:             }
 7913:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7914:             return 'ssi_error' if ($ssi_error);
 7915:             last if (&Apache::loncommon::connection_aborted($r));
 7916:         }
 7917:     }
 7918:     return;
 7919: }
 7920: 
 7921: sub scantron_upload_scantron_data {
 7922:     my ($r)=@_;
 7923:     my $dom = $env{'request.role.domain'};
 7924:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7925:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7926:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7927: 							  'domainid',
 7928: 							  'coursename',$dom);
 7929:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7930:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7931:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7932:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7933:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
 7934:     $r->print('
 7935: <script type="text/javascript" language="javascript">
 7936:     function checkUpload(formname) {
 7937: 	if (formname.upfile.value == "") {
 7938: 	    alert("'.$nofile_alert.'");
 7939: 	    return false;
 7940: 	}
 7941:         if (formname.courseid.value == "") {
 7942:             alert("'.$nocourseid_alert.'");
 7943:             return false;
 7944:         }
 7945: 	formname.submit();
 7946:     }
 7947: 
 7948:     function ToSyllabus() {
 7949:         var cdom = '."'$dom'".';
 7950:         var cnum = document.rules.courseid.value;
 7951:         if (cdom == "" || cdom == null) {
 7952:             return;
 7953:         }
 7954:         if (cnum == "" || cnum == null) {
 7955:            return;
 7956:         }
 7957:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7958:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7959:         return;
 7960:     }
 7961: 
 7962: </script>
 7963: 
 7964: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7965: 
 7966: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7967: '.$default_form_data.
 7968:   &Apache::lonhtmlcommon::start_pick_box().
 7969:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7970:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7971:   &Apache::lonhtmlcommon::row_closure().
 7972:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7973:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7974:   &Apache::lonhtmlcommon::row_closure().
 7975:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7976:   '<input name="domainid" type="hidden" />'.$domdesc.
 7977:   &Apache::lonhtmlcommon::row_closure().
 7978:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7979:   '<input type="file" name="upfile" size="50" />'.
 7980:   &Apache::lonhtmlcommon::row_closure(1).
 7981:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7982: 
 7983: <input name="command" value="scantronupload_save" type="hidden" />
 7984: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7985: </form>
 7986: ');
 7987:     return '';
 7988: }
 7989: 
 7990: 
 7991: sub scantron_upload_scantron_data_save {
 7992:     my($r)=@_;
 7993:     my ($symb)=&get_symb($r,1);
 7994:     my $doanotherupload=
 7995: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7996: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7997: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7998: 	'</form>'."\n";
 7999:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8000: 	!&Apache::lonnet::allowed('usc',
 8001: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8002: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8003: 	if ($symb) {
 8004: 	    $r->print(&show_grading_menu_form($symb));
 8005: 	} else {
 8006: 	    $r->print($doanotherupload);
 8007: 	}
 8008: 	return '';
 8009:     }
 8010:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8011:     my $uploadedfile;
 8012:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8013:     if (length($env{'form.upfile'}) < 2) {
 8014:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8015:     } else {
 8016:         my $result = 
 8017:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8018:                                             $env{'form.courseid'},$env{'form.domainid'});
 8019: 	if ($result =~ m{^/uploaded/}) {
 8020: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8021:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8022: 			  '<span class="LC_filename">'.$result.'</span>'));
 8023:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8024:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8025:                                                        $env{'form.courseid'},$uploadedfile));
 8026: 	} else {
 8027: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8028:                           '<span class="LC_error">','</span>',$result,
 8029: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8030: 	}
 8031:     }
 8032:     if ($symb) {
 8033: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8034:     } else {
 8035: 	$r->print($doanotherupload);
 8036:     }
 8037:     return '';
 8038: }
 8039: 
 8040: sub validate_uploaded_scantron_file {
 8041:     my ($cdom,$cname,$fname) = @_;
 8042:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8043:     my @lines;
 8044:     if ($scanlines ne '-1') {
 8045:         @lines=split("\n",$scanlines,-1);
 8046:     }
 8047:     my $output;
 8048:     if (@lines) {
 8049:         my (%counts,$max_match_format);
 8050:         my ($max_match_count,$max_match_pct) = (0,0);
 8051:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8052:         my %idmap = &username_to_idmap($classlist);
 8053:         foreach my $key (keys(%idmap)) {
 8054:             my $lckey = lc($key);
 8055:             $idmap{$lckey} = $idmap{$key};
 8056:         }
 8057:         my %unique_formats;
 8058:         my @formatlines = &get_scantronformat_file();
 8059:         foreach my $line (@formatlines) {
 8060:             chomp($line);
 8061:             my @config = split(/:/,$line);
 8062:             my $idstart = $config[5];
 8063:             my $idlength = $config[6];
 8064:             if (($idstart ne '') && ($idlength > 0)) {
 8065:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8066:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8067:                 } else {
 8068:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8069:                 }
 8070:             }
 8071:         }
 8072:         foreach my $key (keys(%unique_formats)) {
 8073:             my ($idstart,$idlength) = split(':',$key);
 8074:             %{$counts{$key}} = (
 8075:                                'found'   => 0,
 8076:                                'total'   => 0,
 8077:                               );
 8078:             foreach my $line (@lines) {
 8079:                 next if ($line =~ /^#/);
 8080:                 next if ($line =~ /^[\s\cz]*$/);
 8081:                 my $id = substr($line,$idstart-1,$idlength);
 8082:                 $id = lc($id);
 8083:                 if (exists($idmap{$id})) {
 8084:                     $counts{$key}{'found'} ++;
 8085:                 }
 8086:                 $counts{$key}{'total'} ++;
 8087:             }
 8088:             if ($counts{$key}{'total'}) {
 8089:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8090:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8091:                     $max_match_pct = $percent_match;
 8092:                     $max_match_format = $key;
 8093:                     $max_match_count = $counts{$key}{'total'};
 8094:                 }
 8095:             }
 8096:         }
 8097:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8098:             my $format_descs;
 8099:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8100:             for (my $i=0; $i<$numwithformat; $i++) {
 8101:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8102:                 if ($i<$numwithformat-2) {
 8103:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8104:                 } elsif ($i==$numwithformat-2) {
 8105:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8106:                 } elsif ($i==$numwithformat-1) {
 8107:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8108:                 }
 8109:             }
 8110:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8111:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8112:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8113:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8114:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8115:                                   '<i>'.$cdom.'</i>').'</li>'.
 8116:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8117:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8118:                        '</ul>';
 8119:         }
 8120:     } else {
 8121:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8122:     }
 8123:     return $output;
 8124: }
 8125: 
 8126: sub valid_file {
 8127:     my ($requested_file)=@_;
 8128:     foreach my $filename (sort(&scantron_filenames())) {
 8129: 	if ($requested_file eq $filename) { return 1; }
 8130:     }
 8131:     return 0;
 8132: }
 8133: 
 8134: sub scantron_download_scantron_data {
 8135:     my ($r)=@_;
 8136:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8137:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8138:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8139:     my $file=$env{'form.scantron_selectfile'};
 8140:     if (! &valid_file($file)) {
 8141: 	$r->print('
 8142: 	<p>
 8143: 	    '.&mt('The requested file name was invalid.').'
 8144:         </p>
 8145: ');
 8146: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8147: 	return;
 8148:     }
 8149:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8150:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8151:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8152:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8153:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8154:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8155:     $r->print('
 8156:     <p>
 8157: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8158: 	      '<a href="'.$orig.'">','</a>').'
 8159:     </p>
 8160:     <p>
 8161: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8162: 	      '<a href="'.$corrected.'">','</a>').'
 8163:     </p>
 8164:     <p>
 8165: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8166: 	      '<a href="'.$skipped.'">','</a>').'
 8167:     </p>
 8168: ');
 8169:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8170:     return '';
 8171: }
 8172: 
 8173: sub checkscantron_results {
 8174:     my ($r) = @_;
 8175:     my ($symb)=&get_symb($r);
 8176:     if (!$symb) {return '';}
 8177:     my $grading_menu_button=&show_grading_menu_form($symb);
 8178:     my $cid = $env{'request.course.id'};
 8179:     my %lettdig = &letter_to_digits();
 8180:     my $numletts = scalar(keys(%lettdig));
 8181:     my $cnum = $env{'course.'.$cid.'.num'};
 8182:     my $cdom = $env{'course.'.$cid.'.domain'};
 8183:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8184:     my %record;
 8185:     my %scantron_config =
 8186:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8187:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8188:     my $classlist=&Apache::loncoursedata::get_classlist();
 8189:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8190:     my $navmap=Apache::lonnavmaps::navmap->new();
 8191:     unless (ref($navmap)) {
 8192:         $r->print(&navmap_errormsg());
 8193:         return '';
 8194:     }
 8195:     my $map=$navmap->getResourceByUrl($sequence);
 8196:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8197:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8198:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8199: 
 8200:     my ($uname,$udom);
 8201:     my (%scandata,%lastname,%bylast);
 8202:     $r->print('
 8203: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8204: 
 8205:     my @delayqueue;
 8206:     my %completedstudents;
 8207: 
 8208:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8209:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8210:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8211:                                     'inline',undef,'checkscantron');
 8212:     my ($username,$domain,$started);
 8213:     my $nav_error;
 8214:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8215:     if ($nav_error) {
 8216:         $r->print(&navmap_errormsg());
 8217:         return '';
 8218:     }
 8219: 
 8220:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8221:                                           'Processing first student');
 8222:     my $start=&Time::HiRes::time();
 8223:     my $i=-1;
 8224: 
 8225:     while ($i<$scanlines->{'count'}) {
 8226:         ($username,$domain,$uname)=('','','');
 8227:         $i++;
 8228:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8229:         if ($line=~/^[\s\cz]*$/) { next; }
 8230:         if ($started) {
 8231:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8232:                                                      'last student');
 8233:         }
 8234:         $started=1;
 8235:         my $scan_record=
 8236:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8237:                                                      $scan_data);
 8238:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8239:                                                               \%idmap,$i)) {
 8240:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8241:                                 'Unable to find a student that matches',1);
 8242:             next;
 8243:         }
 8244:         if (exists $completedstudents{$uname}) {
 8245:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8246:                                 'Student '.$uname.' has multiple sheets',2);
 8247:             next;
 8248:         }
 8249:         my $pid = $scan_record->{'scantron.ID'};
 8250:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8251:         push(@{$bylast{$lastname{$pid}}},$pid);
 8252:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8253:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8254:         chomp($scandata{$pid});
 8255:         $scandata{$pid} =~ s/\r$//;
 8256:         ($username,$domain)=split(/:/,$uname);
 8257:         my $counter = -1;
 8258:         foreach my $resource (@resources) {
 8259:             my $parts;
 8260:             my $ressymb = $resource->symb();
 8261:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8262:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8263:                 (my $analysis,$parts) =
 8264:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8265:             } else {
 8266:                 $parts = $grader_partids_by_symb{$ressymb};
 8267:             }
 8268:             ($counter,my $recording) =
 8269:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8270:                                          $scandata{$pid},$parts,
 8271:                                          \%scantron_config,\%lettdig,$numletts);
 8272:             $record{$pid} .= $recording;
 8273:         }
 8274:     }
 8275:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8276:     $r->print('<br />');
 8277:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8278:     $passed = 0;
 8279:     $failed = 0;
 8280:     $numstudents = 0;
 8281:     foreach my $last (sort(keys(%bylast))) {
 8282:         if (ref($bylast{$last}) eq 'ARRAY') {
 8283:             foreach my $pid (sort(@{$bylast{$last}})) {
 8284:                 my $showscandata = $scandata{$pid};
 8285:                 my $showrecord = $record{$pid};
 8286:                 $showscandata =~ s/\s/&nbsp;/g;
 8287:                 $showrecord =~ s/\s/&nbsp;/g;
 8288:                 if ($scandata{$pid} eq $record{$pid}) {
 8289:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8290:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8291: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8292: '</tr>'."\n".
 8293: '<tr class="'.$css_class.'">'."\n".
 8294: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8295:                     $passed ++;
 8296:                 } else {
 8297:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8298:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Bubblesheet').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8299: '</tr>'."\n".
 8300: '<tr class="'.$css_class.'">'."\n".
 8301: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8302: '</tr>'."\n";
 8303:                     $failed ++;
 8304:                 }
 8305:                 $numstudents ++;
 8306:             }
 8307:         }
 8308:     }
 8309:     $r->print('<p>'.&mt('Comparison of bubblesheet 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>');
 8310:     $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>');
 8311:     if ($passed) {
 8312:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8313:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8314:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8315:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8316:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8317:                  $okstudents."\n".
 8318:                  &Apache::loncommon::end_data_table().'<br />');
 8319:     }
 8320:     if ($failed) {
 8321:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8322:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8323:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8324:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8325:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8326:                  $badstudents."\n".
 8327:                  &Apache::loncommon::end_data_table()).'<br />'.
 8328:                  &mt('Differences can occur if submissions were modified using manual grading after a bubblesheet grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original bubblesheets.');  
 8329:     }
 8330:     $r->print('</form><br />'.$grading_menu_button);
 8331:     return;
 8332: }
 8333: 
 8334: sub verify_scantron_grading {
 8335:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8336:         $scantron_config,$lettdig,$numletts) = @_;
 8337:     my ($record,%expected,%startpos);
 8338:     return ($counter,$record) if (!ref($resource));
 8339:     return ($counter,$record) if (!$resource->is_problem());
 8340:     my $symb = $resource->symb();
 8341:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8342:     foreach my $part_id (@{$partids}) {
 8343:         $counter ++;
 8344:         $expected{$part_id} = 0;
 8345:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8346:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8347:             foreach my $item (@sub_lines) {
 8348:                 $expected{$part_id} += $item;
 8349:             }
 8350:         } else {
 8351:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8352:         }
 8353:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8354:     }
 8355:     if ($symb) {
 8356:         my %recorded;
 8357:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8358:         if ($returnhash{'version'}) {
 8359:             my %lasthash=();
 8360:             my $version;
 8361:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8362:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8363:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8364:                 }
 8365:             }
 8366:             foreach my $key (keys(%lasthash)) {
 8367:                 if ($key =~ /\.scantron$/) {
 8368:                     my $value = &unescape($lasthash{$key});
 8369:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8370:                     if ($value eq '') {
 8371:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8372:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8373:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8374:                             }
 8375:                         }
 8376:                     } else {
 8377:                         my @tocheck;
 8378:                         my @items = split(//,$value);
 8379:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8380:                             ($scantron_config->{'Qon'} eq 'number')) {
 8381:                             if (@items < $expected{$part_id}) {
 8382:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8383:                                 my @singles = split(//,$fragment);
 8384:                                 foreach my $pos (@singles) {
 8385:                                     if ($pos eq ' ') {
 8386:                                         push(@tocheck,$pos);
 8387:                                     } else {
 8388:                                         my $next = shift(@items);
 8389:                                         push(@tocheck,$next);
 8390:                                     }
 8391:                                 }
 8392:                             } else {
 8393:                                 @tocheck = @items;
 8394:                             }
 8395:                             foreach my $letter (@tocheck) {
 8396:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8397:                                     if ($letter !~ /^[A-J]$/) {
 8398:                                         $letter = $scantron_config->{'Qoff'};
 8399:                                     }
 8400:                                     $recorded{$part_id} .= $letter;
 8401:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8402:                                     my $digit;
 8403:                                     if ($letter !~ /^[A-J]$/) {
 8404:                                         $digit = $scantron_config->{'Qoff'};
 8405:                                     } else {
 8406:                                         $digit = $lettdig->{$letter};
 8407:                                     }
 8408:                                     $recorded{$part_id} .= $digit;
 8409:                                 }
 8410:                             }
 8411:                         } else {
 8412:                             @tocheck = @items;
 8413:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8414:                                 my $curr_sub = shift(@tocheck);
 8415:                                 my $digit;
 8416:                                 if ($curr_sub =~ /^[A-J]$/) {
 8417:                                     $digit = $lettdig->{$curr_sub}-1;
 8418:                                 }
 8419:                                 if ($curr_sub eq 'J') {
 8420:                                     $digit += scalar($numletts);
 8421:                                 }
 8422:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8423:                                     if ($j == $digit) {
 8424:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8425:                                     } else {
 8426:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8427:                                     }
 8428:                                 }
 8429:                             }
 8430:                         }
 8431:                     }
 8432:                 }
 8433:             }
 8434:         }
 8435:         foreach my $part_id (@{$partids}) {
 8436:             if ($recorded{$part_id} eq '') {
 8437:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8438:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8439:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8440:                     }
 8441:                 }
 8442:             }
 8443:             $record .= $recorded{$part_id};
 8444:         }
 8445:     }
 8446:     return ($counter,$record);
 8447: }
 8448: 
 8449: sub letter_to_digits { 
 8450:     my %lettdig = (
 8451:                     A => 1,
 8452:                     B => 2,
 8453:                     C => 3,
 8454:                     D => 4,
 8455:                     E => 5,
 8456:                     F => 6,
 8457:                     G => 7,
 8458:                     H => 8,
 8459:                     I => 9,
 8460:                     J => 0,
 8461:                   );
 8462:     return %lettdig;
 8463: }
 8464: 
 8465: 
 8466: #-------- end of section for handling grading scantron forms -------
 8467: #
 8468: #-------------------------------------------------------------------
 8469: 
 8470: #-------------------------- Menu interface -------------------------
 8471: #
 8472: #--- Show a Grading Menu button - Calls the next routine ---
 8473: sub show_grading_menu_form {
 8474:     my ($symb)=@_;
 8475:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8476: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8477: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8478: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8479: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8480: 	'</form>'."\n";
 8481:     return $result;
 8482: }
 8483: 
 8484: # -- Retrieve choices for grading form
 8485: sub savedState {
 8486:     my %savedState = ();
 8487:     if ($env{'form.saveState'}) {
 8488: 	foreach (split(/:/,$env{'form.saveState'})) {
 8489: 	    my ($key,$value) = split(/=/,$_,2);
 8490: 	    $savedState{$key} = $value;
 8491: 	}
 8492:     }
 8493:     return \%savedState;
 8494: }
 8495: 
 8496: sub grading_menu {
 8497:     my ($request) = @_;
 8498:     my ($symb)=&get_symb($request);
 8499:     if (!$symb) {return '';}
 8500:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8501:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8502: 
 8503:     $request->print($table);
 8504:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8505:                   'handgrade'=>$hdgrade,
 8506:                   'probTitle'=>$probTitle,
 8507:                   'command'=>'submit_options',
 8508:                   'saveState'=>"",
 8509:                   'gradingMenu'=>1,
 8510:                   'showgrading'=>"yes");
 8511:     
 8512:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8513:     
 8514:     $fields{'command'} = 'csvform';
 8515:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8516:     
 8517:     $fields{'command'} = 'processclicker';
 8518:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8519:     
 8520:     $fields{'command'} = 'scantron_selectphase';
 8521:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8522:     
 8523:     my @menu = ({	categorytitle=>'Course Grading',
 8524:             items =>[
 8525:                         {	linktext => 'Manual Grading/View Submissions',
 8526:                     		url => $url1,
 8527:                     		permission => 'F',
 8528:                     		icon => 'edit-find-replace.png',
 8529:                     		linktitle => 'Start the process of hand grading submissions.'
 8530:                         },
 8531:                 	    {	linktext => 'Upload Scores',
 8532:                     		url => $url2,
 8533:                     		permission => 'F',
 8534:                     		icon => 'uploadscores.png',
 8535:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8536:                 	    },
 8537:                 	    {	linktext => 'Process Clicker',
 8538:                     		url => $url3,
 8539:                     		permission => 'F',
 8540:                     		icon => 'addClickerInfoFile.png',
 8541:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8542:                 	    },
 8543:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8544:                     		url => $url4,
 8545:                     		permission => 'F',
 8546:                     		icon => 'stat.png',
 8547:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8548:                 	    }
 8549:                     ]
 8550:             });
 8551: 
 8552:     #$fields{'command'} = 'verify';
 8553:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8554:     #
 8555:     # Create the menu
 8556:     my $Str;
 8557:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8558:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8559:     $Str .= '<input type="hidden" name="command" value="" />'.
 8560:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8561: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8562: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8563: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8564: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8565: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8566: 
 8567:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8568:     #$menudata->{'jscript'}
 8569:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 8570:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8571:         ' /> '.
 8572:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8573:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8574: 
 8575:     $Str .="</form>\n";
 8576:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8577:     $request->print(<<GRADINGMENUJS);
 8578: <script type="text/javascript" language="javascript">
 8579:     function checkChoice(formname,val,cmdx) {
 8580: 	if (val <= 2) {
 8581: 	    var cmd = radioSelection(formname.radioChoice);
 8582: 	    var cmdsave = cmd;
 8583: 	} else {
 8584: 	    cmd = cmdx;
 8585: 	    cmdsave = 'submission';
 8586: 	}
 8587: 	formname.command.value = cmd;
 8588: 	if (val < 5) formname.submit();
 8589: 	if (val == 5) {
 8590: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8591: 	        return false;
 8592: 	    } else {
 8593: 	        formname.submit();
 8594: 	    }
 8595: 	}
 8596:     }
 8597: 
 8598:     function checkReceiptNo(formname,nospace) {
 8599: 	var receiptNo = formname.receipt.value;
 8600: 	var checkOpt = false;
 8601: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8602: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8603: 	if (checkOpt) {
 8604: 	    alert("$receiptalert");
 8605: 	    formname.receipt.value = "";
 8606: 	    formname.receipt.focus();
 8607: 	    return false;
 8608: 	}
 8609: 	return true;
 8610:     }
 8611: </script>
 8612: GRADINGMENUJS
 8613:     &commonJSfunctions($request);
 8614:     return $Str;    
 8615: }
 8616: 
 8617: 
 8618: #--- Displays the submissions first page -------
 8619: sub submit_options {
 8620:     my ($request) = @_;
 8621:     my ($symb)=&get_symb($request);
 8622:     if (!$symb) {return '';}
 8623:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8624: 
 8625:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8626:     $request->print(<<GRADINGMENUJS);
 8627: <script type="text/javascript" language="javascript">
 8628:     function checkChoice(formname,val,cmdx) {
 8629: 	if (val <= 2) {
 8630: 	    var cmd = radioSelection(formname.radioChoice);
 8631: 	    var cmdsave = cmd;
 8632: 	} else {
 8633: 	    cmd = cmdx;
 8634: 	    cmdsave = 'submission';
 8635: 	}
 8636: 	formname.command.value = cmd;
 8637: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8638: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8639: 	if (val < 5) formname.submit();
 8640: 	if (val == 5) {
 8641: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8642: 	    formname.submit();
 8643: 	}
 8644: 	if (val < 7) formname.submit();
 8645:     }
 8646: 
 8647:     function checkReceiptNo(formname,nospace) {
 8648: 	var receiptNo = formname.receipt.value;
 8649: 	var checkOpt = false;
 8650: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8651: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8652: 	if (checkOpt) {
 8653: 	    alert("$receiptalert");
 8654: 	    formname.receipt.value = "";
 8655: 	    formname.receipt.focus();
 8656: 	    return false;
 8657: 	}
 8658: 	return true;
 8659:     }
 8660: </script>
 8661: GRADINGMENUJS
 8662:     &commonJSfunctions($request);
 8663:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8664:     my $result;
 8665:     my (undef,$sections) = &getclasslist('all','0');
 8666:     my $savedState = &savedState();
 8667:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8668:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8669:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8670:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8671: 
 8672:     # Preselect sections
 8673:     my $selsec="";
 8674:     if (ref($sections)) {
 8675:         foreach my $section (sort(@$sections)) {
 8676:             $selsec.='<option value="'.$section.'" '.
 8677:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8678:         }
 8679:     }
 8680: 
 8681:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8682: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8683: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8684: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8685: 	'<input type="hidden" name="command"     value="" />'."\n".
 8686: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8687: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8688: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8689: 
 8690:     $result.='
 8691: <h2>
 8692:   '.&mt('Grade Current Resource').'
 8693: </h2>
 8694: <div>
 8695:   '.$table.'
 8696: </div>
 8697: 
 8698: <div class="LC_columnSection">
 8699:   
 8700:     <fieldset>
 8701:       <legend>
 8702:        '.&mt('Sections').'
 8703:       </legend>
 8704:       <select name="section" multiple="multiple" size="5">'."\n";
 8705:     $result.= $selsec;
 8706:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8707:     $result.='
 8708:     </fieldset>
 8709:   
 8710:     <fieldset>
 8711:       <legend>
 8712:         '.&mt('Groups').'
 8713:       </legend>
 8714:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8715:     </fieldset>
 8716:   
 8717:     <fieldset>
 8718:       <legend>
 8719:         '.&mt('Access Status').'
 8720:       </legend>
 8721:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8722:     </fieldset>
 8723:   
 8724:     <fieldset>
 8725:       <legend>
 8726:         '.&mt('Submission Status').'
 8727:       </legend>
 8728:       <select name="submitonly" size="5">
 8729: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8730: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8731: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8732: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8733:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8734:       </select>
 8735:     </fieldset>
 8736:   
 8737: </div>
 8738: 
 8739: <br />
 8740:           <div>
 8741:             <div>
 8742:               <label>
 8743:                 <input type="radio" name="radioChoice" value="submission" '.
 8744:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8745:              &mt('Select individual students to grade and view submissions.').'
 8746: 	      </label> 
 8747:             </div>
 8748:             <div>
 8749: 	      <label>
 8750:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8751:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8752:                     &mt('Grade all selected students in a grading table.').'
 8753:               </label>
 8754:             </div>
 8755:             <div>
 8756: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8757:             </div>
 8758:           </div>
 8759: 
 8760: 
 8761:         <h2>
 8762:          '.&mt('Grade Complete Folder for One Student').'
 8763:         </h2>
 8764:         <div>
 8765:             <div>
 8766:               <label>
 8767:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8768: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8769:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8770:               </label>
 8771:             </div>
 8772:             <div>
 8773: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8774:             </div>
 8775:         </div>
 8776:   </form>';
 8777:     $result .= &show_grading_menu_form($symb);
 8778:     return $result;
 8779: }
 8780: 
 8781: sub reset_perm {
 8782:     undef(%perm);
 8783: }
 8784: 
 8785: sub init_perm {
 8786:     &reset_perm();
 8787:     foreach my $test_perm ('vgr','mgr','opa') {
 8788: 
 8789: 	my $scope = $env{'request.course.id'};
 8790: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8791: 
 8792: 	    $scope .= '/'.$env{'request.course.sec'};
 8793: 	    if ( $perm{$test_perm}=
 8794: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8795: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8796: 	    } else {
 8797: 		delete($perm{$test_perm});
 8798: 	    }
 8799: 	}
 8800:     }
 8801: }
 8802: 
 8803: sub gather_clicker_ids {
 8804:     my %clicker_ids;
 8805: 
 8806:     my $classlist = &Apache::loncoursedata::get_classlist();
 8807: 
 8808:     # Set up a couple variables.
 8809:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8810:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8811:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8812: 
 8813:     foreach my $student (keys(%$classlist)) {
 8814:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8815:         my $username = $classlist->{$student}->[$username_idx];
 8816:         my $domain   = $classlist->{$student}->[$domain_idx];
 8817:         my $clickers =
 8818: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8819:         foreach my $id (split(/\,/,$clickers)) {
 8820:             $id=~s/^[\#0]+//;
 8821:             $id=~s/[\-\:]//g;
 8822:             if (exists($clicker_ids{$id})) {
 8823: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8824:             } else {
 8825: 		$clicker_ids{$id}=$username.':'.$domain;
 8826:             }
 8827:         }
 8828:     }
 8829:     return %clicker_ids;
 8830: }
 8831: 
 8832: sub gather_adv_clicker_ids {
 8833:     my %clicker_ids;
 8834:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8835:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8836:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8837:     foreach my $element (sort(keys(%coursepersonnel))) {
 8838:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8839:             my ($puname,$pudom)=split(/\:/,$person);
 8840:             my $clickers =
 8841: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8842:             foreach my $id (split(/\,/,$clickers)) {
 8843: 		$id=~s/^[\#0]+//;
 8844:                 $id=~s/[\-\:]//g;
 8845: 		if (exists($clicker_ids{$id})) {
 8846: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8847: 		} else {
 8848: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8849: 		}
 8850:             }
 8851:         }
 8852:     }
 8853:     return %clicker_ids;
 8854: }
 8855: 
 8856: sub clicker_grading_parameters {
 8857:     return ('gradingmechanism' => 'scalar',
 8858:             'upfiletype' => 'scalar',
 8859:             'specificid' => 'scalar',
 8860:             'pcorrect' => 'scalar',
 8861:             'pincorrect' => 'scalar');
 8862: }
 8863: 
 8864: sub process_clicker {
 8865:     my ($r)=@_;
 8866:     my ($symb)=&get_symb($r);
 8867:     if (!$symb) {return '';}
 8868:     my $result=&checkforfile_js();
 8869:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8870:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8871:     $result.=$table;
 8872:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8873:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8874:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8875:         '</b></td></tr>'."\n";
 8876:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8877: # Attempt to restore parameters from last session, set defaults if not present
 8878:     my %Saveable_Parameters=&clicker_grading_parameters();
 8879:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8880:                                                  \%Saveable_Parameters);
 8881:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8882:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8883:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8884:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8885: 
 8886:     my %checked;
 8887:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8888:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8889:           $checked{$gradingmechanism}=' checked="checked"';
 8890:        }
 8891:     }
 8892: 
 8893:     my $upload=&mt("Upload File");
 8894:     my $type=&mt("Type");
 8895:     my $attendance=&mt("Award points just for participation");
 8896:     my $personnel=&mt("Correctness determined from response by course personnel");
 8897:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8898:     my $given=&mt("Correctness determined from given list of answers").' '.
 8899:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8900:     my $pcorrect=&mt("Percentage points for correct solution");
 8901:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8902:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8903: 						   ('iclicker' => 'i>clicker',
 8904:                                                     'interwrite' => 'interwrite PRS'));
 8905:     $symb = &Apache::lonenc::check_encrypt($symb);
 8906:     $result.=<<ENDUPFORM;
 8907: <script type="text/javascript">
 8908: function sanitycheck() {
 8909: // Accept only integer percentages
 8910:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8911:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8912: // Find out grading choice
 8913:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8914:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8915:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8916:       }
 8917:    }
 8918: // By default, new choice equals user selection
 8919:    newgradingchoice=gradingchoice;
 8920: // Not good to give more points for false answers than correct ones
 8921:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8922:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8923:    }
 8924: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8925:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8926:       document.forms.gradesupload.pcorrect.value=100;
 8927:       document.forms.gradesupload.pincorrect.value=100;
 8928:    }
 8929: // If the values are different, cannot be attendance only
 8930:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8931:        (gradingchoice=='attendance')) {
 8932:        newgradingchoice='personnel';
 8933:    }
 8934: // Change grading choice to new one
 8935:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8936:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8937:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8938:       } else {
 8939:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8940:       }
 8941:    }
 8942: // Remember the old state
 8943:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8944: }
 8945: </script>
 8946: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8947: <input type="hidden" name="symb" value="$symb" />
 8948: <input type="hidden" name="command" value="processclickerfile" />
 8949: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8950: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8951: <input type="file" name="upfile" size="50" />
 8952: <br /><label>$type: $selectform</label>
 8953: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8954: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8955: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8956: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8957: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8958: <br />&nbsp;&nbsp;&nbsp;
 8959: <input type="text" name="givenanswer" size="50" />
 8960: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8961: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8962: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8963: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8964: </form>
 8965: ENDUPFORM
 8966:     $result.='</td></tr></table>'."\n".
 8967:              '</td></tr></table><br /><br />'."\n";
 8968:     $result.=&show_grading_menu_form($symb);
 8969:     return $result;
 8970: }
 8971: 
 8972: sub process_clicker_file {
 8973:     my ($r)=@_;
 8974:     my ($symb)=&get_symb($r);
 8975:     if (!$symb) {return '';}
 8976: 
 8977:     my %Saveable_Parameters=&clicker_grading_parameters();
 8978:     &Apache::loncommon::store_course_settings('grades_clicker',
 8979:                                               \%Saveable_Parameters);
 8980: 
 8981:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8982:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8983: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8984: 	return $result.&show_grading_menu_form($symb);
 8985:     }
 8986:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8987:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8988:         return $result.&show_grading_menu_form($symb);
 8989:     }
 8990:     my $foundgiven=0;
 8991:     if ($env{'form.gradingmechanism'} eq 'given') {
 8992:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8993:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8994:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8995:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8996:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8997:         $foundgiven=$#answers+1;
 8998:     }
 8999:     my %clicker_ids=&gather_clicker_ids();
 9000:     my %correct_ids;
 9001:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9002: 	%correct_ids=&gather_adv_clicker_ids();
 9003:     }
 9004:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9005: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9006: 	   $correct_id=~tr/a-z/A-Z/;
 9007: 	   $correct_id=~s/\s//gs;
 9008: 	   $correct_id=~s/^[\#0]+//;
 9009:            $correct_id=~s/[\-\:]//g;
 9010:            if ($correct_id) {
 9011: 	      $correct_ids{$correct_id}='specified';
 9012:            }
 9013:         }
 9014:     }
 9015:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9016: 	$result.=&mt('Score based on attendance only');
 9017:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9018:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9019:     } else {
 9020: 	my $number=0;
 9021: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9022: 	foreach my $id (sort(keys(%correct_ids))) {
 9023: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9024: 	    if ($correct_ids{$id} eq 'specified') {
 9025: 		$result.=&mt('specified');
 9026: 	    } else {
 9027: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9028: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9029: 	    }
 9030: 	    $number++;
 9031: 	}
 9032:         $result.="</p>\n";
 9033: 	if ($number==0) {
 9034: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9035: 	    return $result.&show_grading_menu_form($symb);
 9036: 	}
 9037:     }
 9038:     if (length($env{'form.upfile'}) < 2) {
 9039:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9040: 		     '<span class="LC_error">',
 9041: 		     '</span>',
 9042: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9043:         return $result.&show_grading_menu_form($symb);
 9044:     }
 9045: 
 9046: # Were able to get all the info needed, now analyze the file
 9047: 
 9048:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9049:     $symb = &Apache::lonenc::check_encrypt($symb);
 9050:     my $heading=&mt('Scanning clicker file');
 9051:     $result.=(<<ENDHEADER);
 9052: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9053: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9054: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9055: <form method="post" action="/adm/grades" name="clickeranalysis">
 9056: <input type="hidden" name="symb" value="$symb" />
 9057: <input type="hidden" name="command" value="assignclickergrades" />
 9058: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9059: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9060: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9061: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9062: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9063: ENDHEADER
 9064:     if ($env{'form.gradingmechanism'} eq 'given') {
 9065:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9066:     } 
 9067:     my %responses;
 9068:     my @questiontitles;
 9069:     my $errormsg='';
 9070:     my $number=0;
 9071:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9072: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9073:     }
 9074:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9075:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9076:     }
 9077:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9078:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9079:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9080:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9081:              '<br />';
 9082:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9083:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9084:        return $result.&show_grading_menu_form($symb);
 9085:     } 
 9086: # Remember Question Titles
 9087: # FIXME: Possibly need delimiter other than ":"
 9088:     for (my $i=0;$i<$number;$i++) {
 9089:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9090:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9091:     }
 9092:     my $correct_count=0;
 9093:     my $student_count=0;
 9094:     my $unknown_count=0;
 9095: # Match answers with usernames
 9096: # FIXME: Possibly need delimiter other than ":"
 9097:     foreach my $id (keys(%responses)) {
 9098:        if ($correct_ids{$id}) {
 9099:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9100:           $correct_count++;
 9101:        } elsif ($clicker_ids{$id}) {
 9102:           if ($clicker_ids{$id}=~/\,/) {
 9103: # More than one user with the same clicker!
 9104:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9105:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9106:                            "<select name='multi".$id."'>";
 9107:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9108:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9109:              }
 9110:              $result.='</select>';
 9111:              $unknown_count++;
 9112:           } else {
 9113: # Good: found one and only one user with the right clicker
 9114:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9115:              $student_count++;
 9116:           }
 9117:        } else {
 9118:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9119:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9120:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9121:                    "\n".&mt("Domain").": ".
 9122:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9123:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9124:           $unknown_count++;
 9125:        }
 9126:     }
 9127:     $result.='<hr />'.
 9128:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9129:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9130:        if ($correct_count==0) {
 9131:           $errormsg.="Found no correct answers answers for grading!";
 9132:        } elsif ($correct_count>1) {
 9133:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9134:        }
 9135:     }
 9136:     if ($number<1) {
 9137:        $errormsg.="Found no questions.";
 9138:     }
 9139:     if ($errormsg) {
 9140:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9141:     } else {
 9142:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9143:     }
 9144:     $result.='</form></td></tr></table>'."\n".
 9145:              '</td></tr></table><br /><br />'."\n";
 9146:     return $result.&show_grading_menu_form($symb);
 9147: }
 9148: 
 9149: sub iclicker_eval {
 9150:     my ($questiontitles,$responses)=@_;
 9151:     my $number=0;
 9152:     my $errormsg='';
 9153:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9154:         my %components=&Apache::loncommon::record_sep($line);
 9155:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9156: 	if ($entries[0] eq 'Question') {
 9157: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9158: 		$$questiontitles[$number]=$entries[$i];
 9159: 		$number++;
 9160: 	    }
 9161: 	}
 9162: 	if ($entries[0]=~/^\#/) {
 9163: 	    my $id=$entries[0];
 9164: 	    my @idresponses;
 9165: 	    $id=~s/^[\#0]+//;
 9166: 	    for (my $i=0;$i<$number;$i++) {
 9167: 		my $idx=3+$i*6;
 9168: 		push(@idresponses,$entries[$idx]);
 9169: 	    }
 9170: 	    $$responses{$id}=join(',',@idresponses);
 9171: 	}
 9172:     }
 9173:     return ($errormsg,$number);
 9174: }
 9175: 
 9176: sub interwrite_eval {
 9177:     my ($questiontitles,$responses)=@_;
 9178:     my $number=0;
 9179:     my $errormsg='';
 9180:     my $skipline=1;
 9181:     my $questionnumber=0;
 9182:     my %idresponses=();
 9183:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9184:         my %components=&Apache::loncommon::record_sep($line);
 9185:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9186:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9187:         if ($entries[1] eq 'Response') { $skipline=1; }
 9188:         next if $skipline;
 9189:         if ($entries[0]!=$questionnumber) {
 9190:            $questionnumber=$entries[0];
 9191:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9192:            $number++;
 9193:         }
 9194:         my $id=$entries[4];
 9195:         $id=~s/^[\#0]+//;
 9196:         $id=~s/^v\d*\://i;
 9197:         $id=~s/[\-\:]//g;
 9198:         $idresponses{$id}[$number]=$entries[6];
 9199:     }
 9200:     foreach my $id (keys(%idresponses)) {
 9201:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9202:        $$responses{$id}=~s/^\s*\,//;
 9203:     }
 9204:     return ($errormsg,$number);
 9205: }
 9206: 
 9207: sub assign_clicker_grades {
 9208:     my ($r)=@_;
 9209:     my ($symb)=&get_symb($r);
 9210:     if (!$symb) {return '';}
 9211: # See which part we are saving to
 9212:     my $res_error;
 9213:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9214:     if ($res_error) {
 9215:         return &navmap_errormsg();
 9216:     }
 9217: # FIXME: This should probably look for the first handgradeable part
 9218:     my $part=$$partlist[0];
 9219: # Start screen output
 9220:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9221: 
 9222:     my $heading=&mt('Assigning grades based on clicker file');
 9223:     $result.=(<<ENDHEADER);
 9224: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9225: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9226: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9227: ENDHEADER
 9228: # Get correct result
 9229: # FIXME: Possibly need delimiter other than ":"
 9230:     my @correct=();
 9231:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9232:     my $number=$env{'form.number'};
 9233:     if ($gradingmechanism ne 'attendance') {
 9234:        foreach my $key (keys(%env)) {
 9235:           if ($key=~/^form\.correct\:/) {
 9236:              my @input=split(/\,/,$env{$key});
 9237:              for (my $i=0;$i<=$#input;$i++) {
 9238:                  if (($correct[$i]) && ($input[$i]) &&
 9239:                      ($correct[$i] ne $input[$i])) {
 9240:                     $result.='<br /><span class="LC_warning">'.
 9241:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9242:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9243:                  } elsif ($input[$i]) {
 9244:                     $correct[$i]=$input[$i];
 9245:                  }
 9246:              }
 9247:           }
 9248:        }
 9249:        for (my $i=0;$i<$number;$i++) {
 9250:           if (!$correct[$i]) {
 9251:              $result.='<br /><span class="LC_error">'.
 9252:                       &mt('No correct result given for question "[_1]"!',
 9253:                           $env{'form.question:'.$i}).'</span>';
 9254:           }
 9255:        }
 9256:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9257:     }
 9258: # Start grading
 9259:     my $pcorrect=$env{'form.pcorrect'};
 9260:     my $pincorrect=$env{'form.pincorrect'};
 9261:     my $storecount=0;
 9262:     foreach my $key (keys(%env)) {
 9263:        my $user='';
 9264:        if ($key=~/^form\.student\:(.*)$/) {
 9265:           $user=$1;
 9266:        }
 9267:        if ($key=~/^form\.unknown\:(.*)$/) {
 9268:           my $id=$1;
 9269:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9270:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9271:           } elsif ($env{'form.multi'.$id}) {
 9272:              $user=$env{'form.multi'.$id};
 9273:           }
 9274:        }
 9275:        if ($user) { 
 9276:           my @answer=split(/\,/,$env{$key});
 9277:           my $sum=0;
 9278:           my $realnumber=$number;
 9279:           for (my $i=0;$i<$number;$i++) {
 9280:              if  ($correct[$i] eq '-') {
 9281:                 $realnumber--;
 9282:              } elsif ($answer[$i]) {
 9283:                 if ($gradingmechanism eq 'attendance') {
 9284:                    $sum+=$pcorrect;
 9285:                 } elsif ($correct[$i] eq '*') {
 9286:                    $sum+=$pcorrect;
 9287:                 } else {
 9288:                    if ($answer[$i] eq $correct[$i]) {
 9289:                       $sum+=$pcorrect;
 9290:                    } else {
 9291:                       $sum+=$pincorrect;
 9292:                    }
 9293:                 }
 9294:              }
 9295:           }
 9296:           my $ave=$sum/(100*$realnumber);
 9297: # Store
 9298:           my ($username,$domain)=split(/\:/,$user);
 9299:           my %grades=();
 9300:           $grades{"resource.$part.solved"}='correct_by_override';
 9301:           $grades{"resource.$part.awarded"}=$ave;
 9302:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9303:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9304:                                                  $env{'request.course.id'},
 9305:                                                  $domain,$username);
 9306:           if ($returncode ne 'ok') {
 9307:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9308:           } else {
 9309:              $storecount++;
 9310:           }
 9311:        }
 9312:     }
 9313: # We are done
 9314:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9315:              '</td></tr></table>'."\n".
 9316:              '</td></tr></table><br /><br />'."\n";
 9317:     return $result.&show_grading_menu_form($symb);
 9318: }
 9319: 
 9320: sub navmap_errormsg {
 9321:     return '<div class="LC_error">'.
 9322:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9323:            &mt('It is recommended that you [_1]re-initialize the course[_2] and then return to this grading page..','<a href="/adm/roles?selectrole=1&newrole='.$env{'request.role'}.'">','</a>').
 9324:            '</div>';
 9325: }
 9326: 
 9327: sub handler {
 9328:     my $request=$_[0];
 9329:     &reset_caches();
 9330:     if ($env{'browser.mathml'}) {
 9331: 	&Apache::loncommon::content_type($request,'text/xml');
 9332:     } else {
 9333: 	&Apache::loncommon::content_type($request,'text/html');
 9334:     }
 9335:     $request->send_http_header;
 9336:     return '' if $request->header_only;
 9337:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9338:     my $symb=&get_symb($request,1);
 9339:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9340:     my $command=$commands[0];
 9341: 
 9342:     if ($#commands > 0) {
 9343: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9344:     }
 9345: 
 9346:     $ssi_error = 0;
 9347:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9348:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9349:                                           {'bread_crumbs' => $brcrum}));
 9350:     if ($symb eq '' && $command eq '') {
 9351: 	if ($env{'user.adv'}) {
 9352: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9353: 		($env{'form.codethree'})) {
 9354: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9355: 		    $env{'form.codethree'};
 9356: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9357: 		    &Apache::lonnet::checkin($token);
 9358: 		if ($tsymb) {
 9359: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9360: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9361: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9362: 					  ('grade_username' => $tuname,
 9363: 					   'grade_domain' => $tudom,
 9364: 					   'grade_courseid' => $tcrsid,
 9365: 					   'grade_symb' => $tsymb)));
 9366: 		    } else {
 9367: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9368: 		    }
 9369: 		} else {
 9370: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9371: 		}
 9372: 	    } else {
 9373: 		$request->print(&Apache::lonxml::tokeninputfield());
 9374: 	    }
 9375: 	}
 9376:     } else {
 9377: 	&init_perm();
 9378: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9379: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9380: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9381: 	    &pickStudentPage($request);
 9382: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9383: 	    &displayPage($request);
 9384: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9385: 	    &updateGradeByPage($request);
 9386: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9387: 	    &processGroup($request);
 9388: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9389: 	    $request->print(&grading_menu($request));
 9390: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9391: 	    $request->print(&submit_options($request));
 9392: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9393: 	    $request->print(&viewgrades($request));
 9394: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9395: 	    $request->print(&processHandGrade($request));
 9396: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9397: 	    $request->print(&editgrades($request));
 9398: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9399: 	    $request->print(&verifyreceipt($request));
 9400:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9401:             $request->print(&process_clicker($request));
 9402:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9403:             $request->print(&process_clicker_file($request));
 9404:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9405:             $request->print(&assign_clicker_grades($request));
 9406: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9407: 	    $request->print(&upcsvScores_form($request));
 9408: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9409: 	    $request->print(&csvupload($request));
 9410: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9411: 	    $request->print(&csvuploadmap($request));
 9412: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9413: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9414: 		$request->print(&csvuploadoptions($request));
 9415: 	    } else {
 9416: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9417: 		    $env{'form.upfile_associate'} = 'reverse';
 9418: 		} else {
 9419: 		    $env{'form.upfile_associate'} = 'forward';
 9420: 		}
 9421: 		$request->print(&csvuploadmap($request));
 9422: 	    }
 9423: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9424: 	    $request->print(&csvuploadassign($request));
 9425: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9426: 	    $request->print(&scantron_selectphase($request));
 9427:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9428:  	    $request->print(&scantron_do_warning($request));
 9429: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9430: 	    $request->print(&scantron_validate_file($request));
 9431: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9432: 	    $request->print(&scantron_process_students($request));
 9433:  	} elsif ($command eq 'scantronupload' && 
 9434:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9435: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9436:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9437:  	} elsif ($command eq 'scantronupload_save' &&
 9438:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9439: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9440:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9441:  	} elsif ($command eq 'scantron_download' &&
 9442: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9443:  	    $request->print(&scantron_download_scantron_data($request));
 9444:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9445:             $request->print(&checkscantron_results($request));     
 9446: 	} elsif ($command) {
 9447: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9448: 	}
 9449:     }
 9450:     if ($ssi_error) {
 9451: 	&ssi_print_error($request);
 9452:     }
 9453:     $request->print(&Apache::loncommon::end_page());
 9454:     &reset_caches();
 9455:     return '';
 9456: }
 9457: 
 9458: 1;
 9459: 
 9460: __END__;
 9461: 
 9462: 
 9463: =head1 NAME
 9464: 
 9465: Apache::grades
 9466: 
 9467: =head1 SYNOPSIS
 9468: 
 9469: Handles the viewing of grades.
 9470: 
 9471: This is part of the LearningOnline Network with CAPA project
 9472: described at http://www.lon-capa.org.
 9473: 
 9474: =head1 OVERVIEW
 9475: 
 9476: Do an ssi with retries:
 9477: While I'd love to factor out this with the vesrion in lonprintout,
 9478: 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
 9479: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9480: 
 9481: At least the logic that drives this has been pulled out into loncommon.
 9482: 
 9483: 
 9484: 
 9485: ssi_with_retries - Does the server side include of a resource.
 9486:                      if the ssi call returns an error we'll retry it up to
 9487:                      the number of times requested by the caller.
 9488:                      If we still have a proble, no text is appended to the
 9489:                      output and we set some global variables.
 9490:                      to indicate to the caller an SSI error occurred.  
 9491:                      All of this is supposed to deal with the issues described
 9492:                      in LonCAPA BZ 5631 see:
 9493:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9494:                      by informing the user that this happened.
 9495: 
 9496: Parameters:
 9497:   resource   - The resource to include.  This is passed directly, without
 9498:                interpretation to lonnet::ssi.
 9499:   form       - The form hash parameters that guide the interpretation of the resource
 9500:                
 9501:   retries    - Number of retries allowed before giving up completely.
 9502: Returns:
 9503:   On success, returns the rendered resource identified by the resource parameter.
 9504: Side Effects:
 9505:   The following global variables can be set:
 9506:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9507:                               It is up to the caller to initialize this to false
 9508:                               if desired.
 9509:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9510:                               of the resource that could not be rendered by the ssi
 9511:                               call.
 9512:    ssi_error_message   - The error string fetched from the ssi response
 9513:                               in the event of an error.
 9514: 
 9515: 
 9516: =head1 HANDLER SUBROUTINE
 9517: 
 9518: ssi_with_retries()
 9519: 
 9520: =head1 SUBROUTINES
 9521: 
 9522: =over
 9523: 
 9524: =item scantron_get_correction() : 
 9525: 
 9526:    Builds the interface screen to interact with the operator to fix a
 9527:    specific error condition in a specific scanline
 9528: 
 9529:  Arguments:
 9530:     $r           - Apache request object
 9531:     $i           - number of the current scanline
 9532:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9533:     $scan_config - hash ref as returned from &get_scantron_config()
 9534:     $line        - full contents of the current scanline
 9535:     $error       - error condition, valid values are
 9536:                    'incorrectCODE', 'duplicateCODE',
 9537:                    'doublebubble', 'missingbubble',
 9538:                    'duplicateID', 'incorrectID'
 9539:     $arg         - extra information needed
 9540:        For errors:
 9541:          - duplicateID   - paper number that this studentID was seen before on
 9542:          - duplicateCODE - array ref of the paper numbers this CODE was
 9543:                            seen on before
 9544:          - incorrectCODE - current incorrect CODE 
 9545:          - doublebubble  - array ref of the bubble lines that have double
 9546:                            bubble errors
 9547:          - missingbubble - array ref of the bubble lines that have missing
 9548:                            bubble errors
 9549: 
 9550: =item  scantron_get_maxbubble() : 
 9551: 
 9552:    Arguments:
 9553:        $nav_error  - Reference to scalar which is a flag to indicate a
 9554:                       failure to retrieve a navmap object.
 9555:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9556:        calling routine should trap the error condition and display the warning
 9557:        found in &navmap_errormsg().
 9558: 
 9559:    Returns the maximum number of bubble lines that are expected to
 9560:    occur. Does this by walking the selected sequence rendering the
 9561:    resource and then checking &Apache::lonxml::get_problem_counter()
 9562:    for what the current value of the problem counter is.
 9563: 
 9564:    Caches the results to $env{'form.scantron_maxbubble'},
 9565:    $env{'form.scantron.bubble_lines.n'}, 
 9566:    $env{'form.scantron.first_bubble_line.n'} and
 9567:    $env{"form.scantron.sub_bubblelines.n"}
 9568:    which are the total number of bubble, lines, the number of bubble
 9569:    lines for response n and number of the first bubble line for response n,
 9570:    and a comma separated list of numbers of bubble lines for sub-questions
 9571:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9572: 
 9573: 
 9574: =item  scantron_validate_missingbubbles() : 
 9575: 
 9576:    Validates all scanlines in the selected file to not have any
 9577:     answers that don't have bubbles that have not been verified
 9578:     to be bubble free.
 9579: 
 9580: =item  scantron_process_students() : 
 9581: 
 9582:    Routine that does the actual grading of the bubble sheet information.
 9583: 
 9584:    The parsed scanline hash is added to %env 
 9585: 
 9586:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9587:    foreach resource , with the form data of
 9588: 
 9589: 	'submitted'     =>'scantron' 
 9590: 	'grade_target'  =>'grade',
 9591: 	'grade_username'=> username of student
 9592: 	'grade_domain'  => domain of student
 9593: 	'grade_courseid'=> of course
 9594: 	'grade_symb'    => symb of resource to grade
 9595: 
 9596:     This triggers a grading pass. The problem grading code takes care
 9597:     of converting the bubbled letter information (now in %env) into a
 9598:     valid submission.
 9599: 
 9600: =item  scantron_upload_scantron_data() :
 9601: 
 9602:     Creates the screen for adding a new bubble sheet data file to a course.
 9603: 
 9604: =item  scantron_upload_scantron_data_save() : 
 9605: 
 9606:    Adds a provided bubble information data file to the course if user
 9607:    has the correct privileges to do so. 
 9608: 
 9609: =item  valid_file() :
 9610: 
 9611:    Validates that the requested bubble data file exists in the course.
 9612: 
 9613: =item  scantron_download_scantron_data() : 
 9614: 
 9615:    Shows a list of the three internal files (original, corrected,
 9616:    skipped) for a specific bubble sheet data file that exists in the
 9617:    course.
 9618: 
 9619: =item  scantron_validate_ID() : 
 9620: 
 9621:    Validates all scanlines in the selected file to not have any
 9622:    invalid or underspecified student/employee IDs
 9623: 
 9624: =item navmap_errormsg() :
 9625: 
 9626:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9627:    Should be called whenever the request to instantiate a navmap object fails.  
 9628: 
 9629: =back
 9630: 
 9631: =cut

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