File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.597: download - view: text, annotated - select for diffs
Thu Mar 11 16:29:42 2010 UTC (14 years, 1 month ago) by wenzelju
Branches: MAIN
CVS tags: HEAD
- &scripttag()-call for XHTML-conformity.
- Deleted non-opend but closed <b>Tags.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.597 2010/03/11 16:29:42 wenzelju 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: 	    $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(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  491:     function radioSelection(radioButton) {
  492: 	var selection=null;
  493: 	if (radioButton.length > 1) {
  494: 	    for (var i=0; i<radioButton.length; i++) {
  495: 		if (radioButton[i].checked) {
  496: 		    return radioButton[i].value;
  497: 		}
  498: 	    }
  499: 	} else {
  500: 	    if (radioButton.checked) return radioButton.value;
  501: 	}
  502: 	return selection;
  503:     }
  504: 
  505:     function pullDownSelection(selectOne) {
  506: 	var selection="";
  507: 	if (selectOne.length > 1) {
  508: 	    for (var i=0; i<selectOne.length; i++) {
  509: 		if (selectOne[i].selected) {
  510: 		    return selectOne[i].value;
  511: 		}
  512: 	    }
  513: 	} else {
  514:             // only one value it must be the selected one
  515: 	    return selectOne.value;
  516: 	}
  517:     }
  518: COMMONJSFUNCTIONS
  519: }
  520: 
  521: #--- Dumps the class list with usernames,list of sections,
  522: #--- section, ids and fullnames for each user.
  523: sub getclasslist {
  524:     my ($getsec,$filterlist,$getgroup) = @_;
  525:     my @getsec;
  526:     my @getgroup;
  527:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  528:     if (!ref($getsec)) {
  529: 	if ($getsec ne '' && $getsec ne 'all') {
  530: 	    @getsec=($getsec);
  531: 	}
  532:     } else {
  533: 	@getsec=@{$getsec};
  534:     }
  535:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  536:     if (!ref($getgroup)) {
  537: 	if ($getgroup ne '' && $getgroup ne 'all') {
  538: 	    @getgroup=($getgroup);
  539: 	}
  540:     } else {
  541: 	@getgroup=@{$getgroup};
  542:     }
  543:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  544: 
  545:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  546:     # Bail out if we were unable to get the classlist
  547:     return if (! defined($classlist));
  548:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  549:     #
  550:     my %sections;
  551:     my %fullnames;
  552:     foreach my $student (keys(%$classlist)) {
  553:         my $end      = 
  554:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  555:         my $start    = 
  556:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  557:         my $id       = 
  558:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  559:         my $section  = 
  560:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  561:         my $fullname = 
  562:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  563:         my $status   = 
  564:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  565:         my $group   = 
  566:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  567: 	# filter students according to status selected
  568: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  569: 	    if (!($stu_status =~ $status)) {
  570: 		delete($classlist->{$student});
  571: 		next;
  572: 	    }
  573: 	}
  574: 	# filter students according to groups selected
  575: 	my @stu_groups = split(/,/,$group);
  576: 	if (@getgroup) {
  577: 	    my $exclude = 1;
  578: 	    foreach my $grp (@getgroup) {
  579: 	        foreach my $stu_group (@stu_groups) {
  580: 	            if ($stu_group eq $grp) {
  581: 	                $exclude = 0;
  582:     	            } 
  583: 	        }
  584:     	        if (($grp eq 'none') && !$group) {
  585:         	        $exclude = 0;
  586:         	}
  587: 	    }
  588: 	    if ($exclude) {
  589: 	        delete($classlist->{$student});
  590: 	    }
  591: 	}
  592: 	$section = ($section ne '' ? $section : 'none');
  593: 	if (&canview($section)) {
  594: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  595: 		$sections{$section}++;
  596: 		if ($classlist->{$student}) {
  597: 		    $fullnames{$student}=$fullname;
  598: 		}
  599: 	    } else {
  600: 		delete($classlist->{$student});
  601: 	    }
  602: 	} else {
  603: 	    delete($classlist->{$student});
  604: 	}
  605:     }
  606:     my %seen = ();
  607:     my @sections = sort(keys(%sections));
  608:     return ($classlist,\@sections,\%fullnames);
  609: }
  610: 
  611: sub canmodify {
  612:     my ($sec)=@_;
  613:     if ($perm{'mgr'}) {
  614: 	if (!defined($perm{'mgr_section'})) {
  615: 	    # can modify whole class
  616: 	    return 1;
  617: 	} else {
  618: 	    if ($sec eq $perm{'mgr_section'}) {
  619: 		#can modify the requested section
  620: 		return 1;
  621: 	    } else {
  622: 		# can't modify the request section
  623: 		return 0;
  624: 	    }
  625: 	}
  626:     }
  627:     #can't modify
  628:     return 0;
  629: }
  630: 
  631: sub canview {
  632:     my ($sec)=@_;
  633:     if ($perm{'vgr'}) {
  634: 	if (!defined($perm{'vgr_section'})) {
  635: 	    # can modify whole class
  636: 	    return 1;
  637: 	} else {
  638: 	    if ($sec eq $perm{'vgr_section'}) {
  639: 		#can modify the requested section
  640: 		return 1;
  641: 	    } else {
  642: 		# can't modify the request section
  643: 		return 0;
  644: 	    }
  645: 	}
  646:     }
  647:     #can't modify
  648:     return 0;
  649: }
  650: 
  651: #--- Retrieve the grade status of a student for all the parts
  652: sub student_gradeStatus {
  653:     my ($symb,$udom,$uname,$partlist) = @_;
  654:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  655:     my %partstatus = ();
  656:     foreach (@$partlist) {
  657: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  658: 	$status              = 'nothing' if ($status eq '');
  659: 	$partstatus{$_}      = $status;
  660: 	my $subkey           = "resource.$_.submitted_by";
  661: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  662:     }
  663:     return %partstatus;
  664: }
  665: 
  666: # hidden form and javascript that calls the form
  667: # Use by verifyscript and viewgrades
  668: # Shows a student's view of problem and submission
  669: sub jscriptNform {
  670:     my ($symb) = @_;
  671:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  672:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  673: 	'    function viewOneStudent(user,domain) {'."\n".
  674: 	'	document.onestudent.student.value = user;'."\n".
  675: 	'	document.onestudent.userdom.value = domain;'."\n".
  676: 	'	document.onestudent.submit();'."\n".
  677: 	'    }'."\n".
  678: 	"\n");
  679:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  680: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  681: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  682: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  683: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  684: 	'<input type="hidden" name="command" value="submission" />'."\n".
  685: 	'<input type="hidden" name="student" value="" />'."\n".
  686: 	'<input type="hidden" name="userdom" value="" />'."\n".
  687: 	'</form>'."\n";
  688:     return $jscript;
  689: }
  690: 
  691: 
  692: 
  693: # Given the score (as a number [0-1] and the weight) what is the final
  694: # point value? This function will round to the nearest tenth, third,
  695: # or quarter if one of those is within the tolerance of .00001.
  696: sub compute_points {
  697:     my ($score, $weight) = @_;
  698:     
  699:     my $tolerance = .00001;
  700:     my $points = $score * $weight;
  701: 
  702:     # Check for nearness to 1/x.
  703:     my $check_for_nearness = sub {
  704:         my ($factor) = @_;
  705:         my $num = ($points * $factor) + $tolerance;
  706:         my $floored_num = floor($num);
  707:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  708:             return $floored_num / $factor;
  709:         }
  710:         return $points;
  711:     };
  712: 
  713:     $points = $check_for_nearness->(10);
  714:     $points = $check_for_nearness->(3);
  715:     $points = $check_for_nearness->(4);
  716:     
  717:     return $points;
  718: }
  719: 
  720: #------------------ End of general use routines --------------------
  721: 
  722: #
  723: # Find most similar essay
  724: #
  725: 
  726: sub most_similar {
  727:     my ($uname,$udom,$uessay,$old_essays)=@_;
  728: 
  729: # ignore spaces and punctuation
  730: 
  731:     $uessay=~s/\W+/ /gs;
  732: 
  733: # ignore empty submissions (occuring when only files are sent)
  734: 
  735:     unless ($uessay=~/\w+/) { return ''; }
  736: 
  737: # these will be returned. Do not care if not at least 50 percent similar
  738:     my $limit=0.6;
  739:     my $sname='';
  740:     my $sdom='';
  741:     my $scrsid='';
  742:     my $sessay='';
  743: # go through all essays ...
  744:     foreach my $tkey (keys(%$old_essays)) {
  745: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  746: # ... except the same student
  747:         next if (($tname eq $uname) && ($tdom eq $udom));
  748: 	my $tessay=$old_essays->{$tkey};
  749: 	$tessay=~s/\W+/ /gs;
  750: # String similarity gives up if not even limit
  751: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  752: # Found one
  753: 	if ($tsimilar>$limit) {
  754: 	    $limit=$tsimilar;
  755: 	    $sname=$tname;
  756: 	    $sdom=$tdom;
  757: 	    $scrsid=$tcrsid;
  758: 	    $sessay=$old_essays->{$tkey};
  759: 	}
  760:     }
  761:     if ($limit>0.6) {
  762:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  763:     } else {
  764:        return ('','','','',0);
  765:     }
  766: }
  767: 
  768: #-------------------------------------------------------------------
  769: 
  770: #------------------------------------ Receipt Verification Routines
  771: #
  772: #--- Check whether a receipt number is valid.---
  773: sub verifyreceipt {
  774:     my $request  = shift;
  775: 
  776:     my $courseid = $env{'request.course.id'};
  777:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  778: 	$env{'form.receipt'};
  779:     $receipt     =~ s/[^\-\d]//g;
  780:     my ($symb)   = &get_symb($request);
  781: 
  782:     my $title.=
  783: 	'<h3><span class="LC_info">'.
  784: 	&mt('Verifying Receipt No. [_1]',$receipt).
  785: 	'</span></h3>'."\n".
  786: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  787: 	'</h4>'."\n";
  788: 
  789:     my ($string,$contents,$matches) = ('','',0);
  790:     my (undef,undef,$fullname) = &getclasslist('all','0');
  791:     
  792:     my $receiptparts=0;
  793:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  794: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  795:     my $parts=['0'];
  796:     if ($receiptparts) {
  797:         my $res_error; 
  798:         ($parts)=&response_type($symb,\$res_error);
  799:         if ($res_error) {
  800:             return &navmap_errormsg();
  801:         } 
  802:     }
  803:     
  804:     my $header = 
  805: 	&Apache::loncommon::start_data_table().
  806: 	&Apache::loncommon::start_data_table_header_row().
  807: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  808: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  809: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  810:     if ($receiptparts) {
  811: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  812:     }
  813:     $header.=
  814: 	&Apache::loncommon::end_data_table_header_row();
  815: 
  816:     foreach (sort 
  817: 	     {
  818: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  819: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  820: 		 }
  821: 		 return $a cmp $b;
  822: 	     } (keys(%$fullname))) {
  823: 	my ($uname,$udom)=split(/\:/);
  824: 	foreach my $part (@$parts) {
  825: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  826: 		$contents.=
  827: 		    &Apache::loncommon::start_data_table_row().
  828: 		    '<td>&nbsp;'."\n".
  829: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  830: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  831: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  832: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  833: 		if ($receiptparts) {
  834: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  835: 		}
  836: 		$contents.= 
  837: 		    &Apache::loncommon::end_data_table_row()."\n";
  838: 		
  839: 		$matches++;
  840: 	    }
  841: 	}
  842:     }
  843:     if ($matches == 0) {
  844:         $string = $title
  845:                  .'<p class="LC_warning">'
  846:                  .&mt('No match found for the above receipt number.')
  847:                  .'</p>';
  848:     } else {
  849: 	$string = &jscriptNform($symb).$title.
  850: 	    '<p>'.
  851: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  852: 	    '</p>'.
  853: 	    $header.
  854: 	    $contents.
  855: 	    &Apache::loncommon::end_data_table()."\n";
  856:     }
  857:     return $string.&show_grading_menu_form($symb);
  858: }
  859: 
  860: #--- This is called by a number of programs.
  861: #--- Called from the Grading Menu - View/Grade an individual student
  862: #--- Also called directly when one clicks on the subm button 
  863: #    on the problem page.
  864: sub listStudents {
  865:     my ($request) = shift;
  866: 
  867:     my ($symb) = &get_symb($request);
  868:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  869:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  870:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  871:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  872:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  873:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  874:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  875: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  876: 
  877:     my $result='<h3><span class="LC_info">&nbsp;'
  878: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  879: 	.'</span></h3>';
  880: 
  881:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  882: 
  883:     my %lt = &Apache::lonlocal::texthash (
  884: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  885: 		'single'   => 'Please select the student before clicking on the Next button.',
  886: 	     );
  887:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  888:     function checkSelect(checkBox) {
  889: 	var ctr=0;
  890: 	var sense="";
  891: 	if (checkBox.length > 1) {
  892: 	    for (var i=0; i<checkBox.length; i++) {
  893: 		if (checkBox[i].checked) {
  894: 		    ctr++;
  895: 		}
  896: 	    }
  897: 	    sense = '$lt{'multiple'}';
  898: 	} else {
  899: 	    if (checkBox.checked) {
  900: 		ctr = 1;
  901: 	    }
  902: 	    sense = '$lt{'single'}';
  903: 	}
  904: 	if (ctr == 0) {
  905: 	    alert(sense);
  906: 	    return false;
  907: 	}
  908: 	document.gradesub.submit();
  909:     }
  910: 
  911:     function reLoadList(formname) {
  912: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  913: 	formname.command.value = 'submission';
  914: 	formname.submit();
  915:     }
  916: LISTJAVASCRIPT
  917: 
  918:     &commonJSfunctions($request);
  919:     $request->print($result);
  920: 
  921:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  922:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  923:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  924: 	"\n".$table;
  925: 	
  926:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  927:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  928:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  929:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  930:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  931:                   .&Apache::lonhtmlcommon::row_closure();
  932:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  933:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  934:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  935:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  936:                   .&Apache::lonhtmlcommon::row_closure();
  937: 
  938:     my $submission_options;
  939:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  940: 	$submission_options.=
  941: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  942:     }
  943:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  944:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  945:     $env{'form.Status'} = $saveStatus;
  946:     $submission_options.=
  947:         '<span class="LC_nobreak">'.
  948:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  949:         &mt('last submission only').' </label></span>'."\n".
  950:         '<span class="LC_nobreak">'.
  951:         '<label><input type="radio" name="lastSub" value="last" /> '.
  952:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  953:         '<span class="LC_nobreak">'.
  954:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  955:         &mt('by dates and submissions').'</label></span>'."\n".
  956:         '<span class="LC_nobreak">'.
  957:         '<label><input type="radio" name="lastSub" value="all" /> '.
  958:         &mt('all details').'</label></span>';
  959:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  960:                   .$submission_options
  961:                   .&Apache::lonhtmlcommon::row_closure();
  962: 
  963:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  964:                   .'<select name="increment">'
  965:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  966:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  967:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  968:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  969:                   .'</select>'
  970:                   .&Apache::lonhtmlcommon::row_closure();
  971: 
  972:     $gradeTable .= 
  973:         &build_section_inputs().
  974: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  975: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  976: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  977: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  978: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  979: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  980: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  981: 
  982:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  983: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  984:     } else {
  985:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  986:                       .&Apache::lonhtmlcommon::StatusOptions(
  987:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  988:                       .&Apache::lonhtmlcommon::row_closure();
  989:     }
  990: 
  991:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  992:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  993:                   .&Apache::lonhtmlcommon::row_closure(1)
  994:                   .&Apache::lonhtmlcommon::end_pick_box();
  995: 
  996:     $gradeTable .= '<p>'
  997:                   .&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"
  998:                   .'<input type="hidden" name="command" value="processGroup" />'
  999:                   .'</p>';
 1000: 
 1001: # checkall buttons
 1002:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1003:     $gradeTable.='<input type="button" '."\n".
 1004:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1005:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1006:     $gradeTable.=&check_buttons();
 1007:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1008:     $gradeTable.= &Apache::loncommon::start_data_table().
 1009: 	&Apache::loncommon::start_data_table_header_row();
 1010:     my $loop = 0;
 1011:     while ($loop < 2) {
 1012: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1013: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1014: 	if ($env{'form.showgrading'} eq 'yes' 
 1015: 	    && $submitonly ne 'queued'
 1016: 	    && $submitonly ne 'all') {
 1017: 	    foreach my $part (sort(@$partlist)) {
 1018: 		my $display_part=
 1019: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1020: 		$gradeTable.=
 1021: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1022: 	    }
 1023: 	} elsif ($submitonly eq 'queued') {
 1024: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1025: 	}
 1026: 	$loop++;
 1027: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1028:     }
 1029:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1030: 
 1031:     my $ctr = 0;
 1032:     foreach my $student (sort 
 1033: 			 {
 1034: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1035: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1036: 			     }
 1037: 			     return $a cmp $b;
 1038: 			 }
 1039: 			 (keys(%$fullname))) {
 1040: 	my ($uname,$udom) = split(/:/,$student);
 1041: 
 1042: 	my %status = ();
 1043: 
 1044: 	if ($submitonly eq 'queued') {
 1045: 	    my %queue_status = 
 1046: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1047: 							$udom,$uname);
 1048: 	    next if (!defined($queue_status{'gradingqueue'}));
 1049: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1050: 	}
 1051: 
 1052: 	if ($env{'form.showgrading'} eq 'yes' 
 1053: 	    && $submitonly ne 'queued'
 1054: 	    && $submitonly ne 'all') {
 1055: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1056: 	    my $submitted = 0;
 1057: 	    my $graded = 0;
 1058: 	    my $incorrect = 0;
 1059: 	    foreach (keys(%status)) {
 1060: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1061: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1062: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1063: 		
 1064: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1065: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1066: 		    $submitted = 0;
 1067: 		    my ($part)=split(/\./,$partid);
 1068: 		    $gradeTable.='<input type="hidden" name="'.
 1069: 			$student.':'.$part.':submitted_by" value="'.
 1070: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1071: 		}
 1072: 	    }
 1073: 	    
 1074: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1075: 				     $submitonly eq 'incorrect' ||
 1076: 				     $submitonly eq 'graded'));
 1077: 	    next if (!$graded && ($submitonly eq 'graded'));
 1078: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1079: 	}
 1080: 
 1081: 	$ctr++;
 1082: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1083:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1084: 	if ( $perm{'vgr'} eq 'F' ) {
 1085: 	    if ($ctr%2 ==1) {
 1086: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1087: 	    }
 1088: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1089:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1090:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1091: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1092: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1093: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1094: 
 1095: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1096: 		foreach (sort(keys(%status))) {
 1097: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1098: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1099: 		}
 1100: 	    }
 1101: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1102: 	    if ($ctr%2 ==0) {
 1103: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1104: 	    }
 1105: 	}
 1106:     }
 1107:     if ($ctr%2 ==1) {
 1108: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1109: 	    if ($env{'form.showgrading'} eq 'yes' 
 1110: 		&& $submitonly ne 'queued'
 1111: 		&& $submitonly ne 'all') {
 1112: 		foreach (@$partlist) {
 1113: 		    $gradeTable.='<td>&nbsp;</td>';
 1114: 		}
 1115: 	    } elsif ($submitonly eq 'queued') {
 1116: 		$gradeTable.='<td>&nbsp;</td>';
 1117: 	    }
 1118: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1119:     }
 1120: 
 1121:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1122:         '<input type="button" '.
 1123:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1124:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1125:     if ($ctr == 0) {
 1126: 	my $num_students=(scalar(keys(%$fullname)));
 1127: 	if ($num_students eq 0) {
 1128: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1129: 	} else {
 1130: 	    my $submissions='submissions';
 1131: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1132: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1133: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1134: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1135: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1136: 		    $num_students).
 1137: 		'</span><br />';
 1138: 	}
 1139:     } elsif ($ctr == 1) {
 1140: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1141:     }
 1142:     $gradeTable.=&show_grading_menu_form($symb);
 1143:     $request->print($gradeTable);
 1144:     return '';
 1145: }
 1146: 
 1147: #---- Called from the listStudents routine
 1148: 
 1149: sub check_script {
 1150:     my ($form, $type)=@_;
 1151:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1152:     function checkall() {
 1153:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1154:             ele = document.forms.'.$form.'.elements[i];
 1155:             if (ele.name == "'.$type.'") {
 1156:             document.forms.'.$form.'.elements[i].checked=true;
 1157:                                        }
 1158:         }
 1159:     }
 1160: 
 1161:     function checksec() {
 1162:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1163:             ele = document.forms.'.$form.'.elements[i];
 1164:            string = document.forms.'.$form.'.chksec.value;
 1165:            if
 1166:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1167:               document.forms.'.$form.'.elements[i].checked=true;
 1168:             }
 1169:         }
 1170:     }
 1171: 
 1172: 
 1173:     function uncheckall() {
 1174:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1175:             ele = document.forms.'.$form.'.elements[i];
 1176:             if (ele.name == "'.$type.'") {
 1177:             document.forms.'.$form.'.elements[i].checked=false;
 1178:                                        }
 1179:         }
 1180:     }
 1181: 
 1182: '."\n");
 1183:     return $chkallscript;
 1184: }
 1185: 
 1186: sub check_buttons {
 1187:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1188:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1189:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1190:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1191:     return $buttons;
 1192: }
 1193: 
 1194: #     Displays the submissions for one student or a group of students
 1195: sub processGroup {
 1196:     my ($request)  = shift;
 1197:     my $ctr        = 0;
 1198:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1199:     my $total      = scalar(@stuchecked)-1;
 1200: 
 1201:     foreach my $student (@stuchecked) {
 1202: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1203: 	$env{'form.student'}        = $uname;
 1204: 	$env{'form.userdom'}        = $udom;
 1205: 	$env{'form.fullname'}       = $fullname;
 1206: 	&submission($request,$ctr,$total);
 1207: 	$ctr++;
 1208:     }
 1209:     return '';
 1210: }
 1211: 
 1212: #------------------------------------------------------------------------------------
 1213: #
 1214: #-------------------------- Next few routines handles grading by student, essentially
 1215: #                           handles essay response type problem/part
 1216: #
 1217: #--- Javascript to handle the submission page functionality ---
 1218: sub sub_page_js {
 1219:     my $request = shift;
 1220: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1221:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1222:     function updateRadio(formname,id,weight) {
 1223: 	var gradeBox = formname["GD_BOX"+id];
 1224: 	var radioButton = formname["RADVAL"+id];
 1225: 	var oldpts = formname["oldpts"+id].value;
 1226: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1227: 	gradeBox.value = pts;
 1228: 	var resetbox = false;
 1229: 	if (isNaN(pts) || pts < 0) {
 1230: 	    alert("$alertmsg"+pts);
 1231: 	    for (var i=0; i<radioButton.length; i++) {
 1232: 		if (radioButton[i].checked) {
 1233: 		    gradeBox.value = i;
 1234: 		    resetbox = true;
 1235: 		}
 1236: 	    }
 1237: 	    if (!resetbox) {
 1238: 		formtextbox.value = "";
 1239: 	    }
 1240: 	    return;
 1241: 	}
 1242: 
 1243: 	if (pts > weight) {
 1244: 	    var resp = confirm("You entered a value ("+pts+
 1245: 			       ") greater than the weight for the part. Accept?");
 1246: 	    if (resp == false) {
 1247: 		gradeBox.value = oldpts;
 1248: 		return;
 1249: 	    }
 1250: 	}
 1251: 
 1252: 	for (var i=0; i<radioButton.length; i++) {
 1253: 	    radioButton[i].checked=false;
 1254: 	    if (pts == i && pts != "") {
 1255: 		radioButton[i].checked=true;
 1256: 	    }
 1257: 	}
 1258: 	updateSelect(formname,id);
 1259: 	formname["stores"+id].value = "0";
 1260:     }
 1261: 
 1262:     function writeBox(formname,id,pts) {
 1263: 	var gradeBox = formname["GD_BOX"+id];
 1264: 	if (checkSolved(formname,id) == 'update') {
 1265: 	    gradeBox.value = pts;
 1266: 	} else {
 1267: 	    var oldpts = formname["oldpts"+id].value;
 1268: 	    gradeBox.value = oldpts;
 1269: 	    var radioButton = formname["RADVAL"+id];
 1270: 	    for (var i=0; i<radioButton.length; i++) {
 1271: 		radioButton[i].checked=false;
 1272: 		if (i == oldpts) {
 1273: 		    radioButton[i].checked=true;
 1274: 		}
 1275: 	    }
 1276: 	}
 1277: 	formname["stores"+id].value = "0";
 1278: 	updateSelect(formname,id);
 1279: 	return;
 1280:     }
 1281: 
 1282:     function clearRadBox(formname,id) {
 1283: 	if (checkSolved(formname,id) == 'noupdate') {
 1284: 	    updateSelect(formname,id);
 1285: 	    return;
 1286: 	}
 1287: 	gradeSelect = formname["GD_SEL"+id];
 1288: 	for (var i=0; i<gradeSelect.length; i++) {
 1289: 	    if (gradeSelect[i].selected) {
 1290: 		var selectx=i;
 1291: 	    }
 1292: 	}
 1293: 	var stores = formname["stores"+id];
 1294: 	if (selectx == stores.value) { return };
 1295: 	var gradeBox = formname["GD_BOX"+id];
 1296: 	gradeBox.value = "";
 1297: 	var radioButton = formname["RADVAL"+id];
 1298: 	for (var i=0; i<radioButton.length; i++) {
 1299: 	    radioButton[i].checked=false;
 1300: 	}
 1301: 	stores.value = selectx;
 1302:     }
 1303: 
 1304:     function checkSolved(formname,id) {
 1305: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1306: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1307: 	    if (!reply) {return "noupdate";}
 1308: 	    formname.overRideScore.value = 'yes';
 1309: 	}
 1310: 	return "update";
 1311:     }
 1312: 
 1313:     function updateSelect(formname,id) {
 1314: 	formname["GD_SEL"+id][0].selected = true;
 1315: 	return;
 1316:     }
 1317: 
 1318: //=========== Check that a point is assigned for all the parts  ============
 1319:     function checksubmit(formname,val,total,parttot) {
 1320: 	formname.gradeOpt.value = val;
 1321: 	if (val == "Save & Next") {
 1322: 	    for (i=0;i<=total;i++) {
 1323: 		for (j=0;j<parttot;j++) {
 1324: 		    var partid = formname["partid"+i+"_"+j].value;
 1325: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1326: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1327: 			if (points == "") {
 1328: 			    var name = formname["name"+i].value;
 1329: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1330: 			    var resp = confirm("You did not assign a score for "+studentID+
 1331: 					       ", part "+partid+". Continue?");
 1332: 			    if (resp == false) {
 1333: 				formname["GD_BOX"+i+"_"+partid].focus();
 1334: 				return false;
 1335: 			    }
 1336: 			}
 1337: 		    }
 1338: 		    
 1339: 		}
 1340: 	    }
 1341: 	    
 1342: 	}
 1343: 	if (val == "Grade Student") {
 1344: 	    formname.showgrading.value = "yes";
 1345: 	    if (formname.Status.value == "") {
 1346: 		formname.Status.value = "Active";
 1347: 	    }
 1348: 	    formname.studentNo.value = total;
 1349: 	}
 1350: 	formname.submit();
 1351:     }
 1352: 
 1353: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1354:     function checkSubmitPage(formname,total) {
 1355: 	noscore = new Array(100);
 1356: 	var ptr = 0;
 1357: 	for (i=1;i<total;i++) {
 1358: 	    var partid = formname["q_"+i].value;
 1359: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1360: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1361: 		var status = formname["solved"+i+"_"+partid].value;
 1362: 		if (points == "" && status != "correct_by_student") {
 1363: 		    noscore[ptr] = i;
 1364: 		    ptr++;
 1365: 		}
 1366: 	    }
 1367: 	}
 1368: 	if (ptr != 0) {
 1369: 	    var sense = ptr == 1 ? ": " : "s: ";
 1370: 	    var prolist = "";
 1371: 	    if (ptr == 1) {
 1372: 		prolist = noscore[0];
 1373: 	    } else {
 1374: 		var i = 0;
 1375: 		while (i < ptr-1) {
 1376: 		    prolist += noscore[i]+", ";
 1377: 		    i++;
 1378: 		}
 1379: 		prolist += "and "+noscore[i];
 1380: 	    }
 1381: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1382: 	    if (resp == false) {
 1383: 		return false;
 1384: 	    }
 1385: 	}
 1386: 
 1387: 	formname.submit();
 1388:     }
 1389: SUBJAVASCRIPT
 1390: }
 1391: 
 1392: #--- javascript for essay type problem --
 1393: sub sub_page_kw_js {
 1394:     my $request = shift;
 1395:     my $iconpath = $request->dir_config('lonIconsURL');
 1396:     &commonJSfunctions($request);
 1397: 
 1398:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1399:     function checkInput() {
 1400:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1401:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1402:       var usrctr = document.msgcenter.usrctr.value;
 1403:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1404:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1405: 
 1406:       var msgchk = "";
 1407:       if (document.msgcenter.subchk.checked) {
 1408:          msgchk = "msgsub,";
 1409:       }
 1410:       var includemsg = 0;
 1411:       for (var i=1; i<=nmsg; i++) {
 1412:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1413:           var frmmsg = document.msgcenter["msg"+i];
 1414:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1415:           var showflg = opener.document.SCORE["shownOnce"+i];
 1416:           showflg.value = "1";
 1417:           var chkbox = document.msgcenter["msgn"+i];
 1418:           if (chkbox.checked) {
 1419:              msgchk += "savemsg"+i+",";
 1420:              includemsg = 1;
 1421:           }
 1422:       }
 1423:       if (document.msgcenter.newmsgchk.checked) {
 1424:          msgchk += "newmsg"+usrctr;
 1425:          includemsg = 1;
 1426:       }
 1427:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1428:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1429:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1430:       includemsg.value = msgchk;
 1431: 
 1432:       self.close()
 1433: 
 1434:     }
 1435: INNERJS
 1436: 
 1437:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1438:     function updateChoice(flag) {
 1439:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1440:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1441:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1442:       opener.document.SCORE.refresh.value = "on";
 1443:       if (opener.document.SCORE.keywords.value!=""){
 1444:          opener.document.SCORE.submit();
 1445:       }
 1446:       self.close()
 1447:     }
 1448: INNERJS
 1449: 
 1450:     my $start_page_msg_central = 
 1451:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1452: 				       {'js_ready'  => 1,
 1453: 					'only_body' => 1,
 1454: 					'bgcolor'   =>'#FFFFFF',});
 1455:     my $end_page_msg_central = 
 1456: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1457: 
 1458: 
 1459:     my $start_page_highlight_central = 
 1460:         &Apache::loncommon::start_page('Highlight Central',
 1461: 				       $inner_js_highlight_central,
 1462: 				       {'js_ready'  => 1,
 1463: 					'only_body' => 1,
 1464: 					'bgcolor'   =>'#FFFFFF',});
 1465:     my $end_page_highlight_central = 
 1466: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1467: 
 1468:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1469:     $docopen=~s/^document\.//;
 1470:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1471:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1472: 
 1473: //===================== Show list of keywords ====================
 1474:   function keywords(formname) {
 1475:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1476:     if (nret==null) return;
 1477:     formname.keywords.value = nret;
 1478: 
 1479:     if (formname.keywords.value != "") {
 1480: 	formname.refresh.value = "on";
 1481: 	formname.submit();
 1482:     }
 1483:     return;
 1484:   }
 1485: 
 1486: //===================== Script to view submitted by ==================
 1487:   function viewSubmitter(submitter) {
 1488:     document.SCORE.refresh.value = "on";
 1489:     document.SCORE.NCT.value = "1";
 1490:     document.SCORE.unamedom0.value = submitter;
 1491:     document.SCORE.submit();
 1492:     return;
 1493:   }
 1494: 
 1495: //===================== Script to add keyword(s) ==================
 1496:   function getSel() {
 1497:     if (document.getSelection) txt = document.getSelection();
 1498:     else if (document.selection) txt = document.selection.createRange().text;
 1499:     else return;
 1500:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1501:     if (cleantxt=="") {
 1502: 	alert("$alertmsg");
 1503: 	return;
 1504:     }
 1505:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1506:     if (nret==null) return;
 1507:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1508:     if (document.SCORE.keywords.value != "") {
 1509: 	document.SCORE.refresh.value = "on";
 1510: 	document.SCORE.submit();
 1511:     }
 1512:     return;
 1513:   }
 1514: 
 1515: //====================== Script for composing message ==============
 1516:    // preload images
 1517:    img1 = new Image();
 1518:    img1.src = "$iconpath/mailbkgrd.gif";
 1519:    img2 = new Image();
 1520:    img2.src = "$iconpath/mailto.gif";
 1521: 
 1522:   function msgCenter(msgform,usrctr,fullname) {
 1523:     var Nmsg  = msgform.savemsgN.value;
 1524:     savedMsgHeader(Nmsg,usrctr,fullname);
 1525:     var subject = msgform.msgsub.value;
 1526:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1527:     re = /msgsub/;
 1528:     var shwsel = "";
 1529:     if (re.test(msgchk)) { shwsel = "checked" }
 1530:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1531:     displaySubject(checkEntities(subject),shwsel);
 1532:     for (var i=1; i<=Nmsg; i++) {
 1533: 	var testmsg = "savemsg"+i+",";
 1534: 	re = new RegExp(testmsg,"g");
 1535: 	shwsel = "";
 1536: 	if (re.test(msgchk)) { shwsel = "checked" }
 1537: 	var message = document.SCORE["savemsg"+i].value;
 1538: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1539: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1540: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1541:     }
 1542:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1543:     shwsel = "";
 1544:     re = /newmsg/;
 1545:     if (re.test(msgchk)) { shwsel = "checked" }
 1546:     newMsg(newmsg,shwsel);
 1547:     msgTail(); 
 1548:     return;
 1549:   }
 1550: 
 1551:   function checkEntities(strx) {
 1552:     if (strx.length == 0) return strx;
 1553:     var orgStr = ["&", "<", ">", '"']; 
 1554:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1555:     var counter = 0;
 1556:     while (counter < 4) {
 1557: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1558: 	counter++;
 1559:     }
 1560:     return strx;
 1561:   }
 1562: 
 1563:   function strReplace(strx, orgStr, newStr) {
 1564:     return strx.split(orgStr).join(newStr);
 1565:   }
 1566: 
 1567:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1568:     var height = 70*Nmsg+250;
 1569:     var scrollbar = "no";
 1570:     if (height > 600) {
 1571: 	height = 600;
 1572: 	scrollbar = "yes";
 1573:     }
 1574:     var xpos = (screen.width-600)/2;
 1575:     xpos = (xpos < 0) ? '0' : xpos;
 1576:     var ypos = (screen.height-height)/2-30;
 1577:     ypos = (ypos < 0) ? '0' : ypos;
 1578: 
 1579:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1580:     pWin.focus();
 1581:     pDoc = pWin.document;
 1582:     pDoc.$docopen;
 1583:     pDoc.write('$start_page_msg_central');
 1584: 
 1585:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1586:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1587:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1588: 
 1589:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1590:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1591:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1592: }
 1593:     function displaySubject(msg,shwsel) {
 1594:     pDoc = pWin.document;
 1595:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1596:     pDoc.write("<td>Subject<\\/td>");
 1597:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1598:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1599: }
 1600: 
 1601:   function displaySavedMsg(ctr,msg,shwsel) {
 1602:     pDoc = pWin.document;
 1603:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1604:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1605:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1606:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1607: }
 1608: 
 1609:   function newMsg(newmsg,shwsel) {
 1610:     pDoc = pWin.document;
 1611:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1612:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1613:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1614:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1615: }
 1616: 
 1617:   function msgTail() {
 1618:     pDoc = pWin.document;
 1619:     pDoc.write("<\\/table>");
 1620:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1621:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1622:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1623:     pDoc.write("<\\/form>");
 1624:     pDoc.write('$end_page_msg_central');
 1625:     pDoc.close();
 1626: }
 1627: 
 1628: //====================== Script for keyword highlight options ==============
 1629:   function kwhighlight() {
 1630:     var kwclr    = document.SCORE.kwclr.value;
 1631:     var kwsize   = document.SCORE.kwsize.value;
 1632:     var kwstyle  = document.SCORE.kwstyle.value;
 1633:     var redsel = "";
 1634:     var grnsel = "";
 1635:     var blusel = "";
 1636:     if (kwclr=="red")   {var redsel="checked"};
 1637:     if (kwclr=="green") {var grnsel="checked"};
 1638:     if (kwclr=="blue")  {var blusel="checked"};
 1639:     var sznsel = "";
 1640:     var sz1sel = "";
 1641:     var sz2sel = "";
 1642:     if (kwsize=="0")  {var sznsel="checked"};
 1643:     if (kwsize=="+1") {var sz1sel="checked"};
 1644:     if (kwsize=="+2") {var sz2sel="checked"};
 1645:     var synsel = "";
 1646:     var syisel = "";
 1647:     var sybsel = "";
 1648:     if (kwstyle=="")    {var synsel="checked"};
 1649:     if (kwstyle=="<i>") {var syisel="checked"};
 1650:     if (kwstyle=="<b>") {var sybsel="checked"};
 1651:     highlightCentral();
 1652:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1653:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1654:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1655:     highlightend();
 1656:     return;
 1657:   }
 1658: 
 1659:   function highlightCentral() {
 1660: //    if (window.hwdWin) window.hwdWin.close();
 1661:     var xpos = (screen.width-400)/2;
 1662:     xpos = (xpos < 0) ? '0' : xpos;
 1663:     var ypos = (screen.height-330)/2-30;
 1664:     ypos = (ypos < 0) ? '0' : ypos;
 1665: 
 1666:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1667:     hwdWin.focus();
 1668:     var hDoc = hwdWin.document;
 1669:     hDoc.$docopen;
 1670:     hDoc.write('$start_page_highlight_central');
 1671:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1672:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1673: 
 1674:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1675:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1676:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1677:   }
 1678: 
 1679:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1680:     var hDoc = hwdWin.document;
 1681:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1682:     hDoc.write("<td align=\\"left\\">");
 1683:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1684:     hDoc.write("<td align=\\"left\\">");
 1685:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1686:     hDoc.write("<td align=\\"left\\">");
 1687:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1688:     hDoc.write("<\\/tr>");
 1689:   }
 1690: 
 1691:   function highlightend() { 
 1692:     var hDoc = hwdWin.document;
 1693:     hDoc.write("<\\/table>");
 1694:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1695:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1696:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1697:     hDoc.write("<\\/form>");
 1698:     hDoc.write('$end_page_highlight_central');
 1699:     hDoc.close();
 1700:   }
 1701: 
 1702: SUBJAVASCRIPT
 1703: }
 1704: 
 1705: sub get_increment {
 1706:     my $increment = $env{'form.increment'};
 1707:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1708:         $increment != .1) {
 1709:         $increment = 1;
 1710:     }
 1711:     return $increment;
 1712: }
 1713: 
 1714: sub gradeBox_start {
 1715:     return (
 1716:         &Apache::loncommon::start_data_table()
 1717:        .&Apache::loncommon::start_data_table_header_row()
 1718:        .'<th>'.&mt('Part').'</th>'
 1719:        .'<th>'.&mt('Points').'</th>'
 1720:        .'<th>&nbsp;</th>'
 1721:        .'<th>'.&mt('Assign Grade').'</th>'
 1722:        .'<th>'.&mt('Weight').'</th>'
 1723:        .'<th>'.&mt('Grade Status').'</th>'
 1724:        .&Apache::loncommon::end_data_table_header_row()
 1725:     );
 1726: }
 1727: 
 1728: sub gradeBox_end {
 1729:     return (
 1730:         &Apache::loncommon::end_data_table()
 1731:     );
 1732: }
 1733: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1734: sub gradeBox {
 1735:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1736:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1737: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1738:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1739:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1740:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1741:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1742:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1743: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1744:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1745:     my $display_part= &get_display_part($partid,$symb);
 1746:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1747: 				       [$partid]);
 1748:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1749:     if ($last_resets{$partid}) {
 1750:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1751:     }
 1752:     $result.=&Apache::loncommon::start_data_table_row();
 1753:     my $ctr = 0;
 1754:     my $thisweight = 0;
 1755:     my $increment = &get_increment();
 1756: 
 1757:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1758:     while ($thisweight<=$wgt) {
 1759: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1760:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1761: 	    $thisweight.')" value="'.$thisweight.'" '.
 1762: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1763: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1764:         $thisweight += $increment;
 1765: 	$ctr++;
 1766:     }
 1767:     $radio.='</tr></table>';
 1768: 
 1769:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1770: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1771: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1772: 	$wgt.')" /></td>'."\n";
 1773:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1774: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1775: 	' </td>'."\n";
 1776:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1777: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1778:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1779: 	$line.='<option></option>'.
 1780: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1781:     } else {
 1782: 	$line.='<option selected="selected"></option>'.
 1783: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1784:     }
 1785:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1786: 
 1787: 
 1788: 	#&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);
 1789:     $result .= 
 1790: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1791:     $result.=&Apache::loncommon::end_data_table_row();
 1792:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1793: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1794: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1795: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1796:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1797:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1798:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1799:         $aggtries.'" />'."\n";
 1800:     my $res_error;
 1801:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1802:     if ($res_error) {
 1803:         return &navmap_errormsg();
 1804:     }
 1805:     return $result;
 1806: }
 1807: 
 1808: sub handback_box {
 1809:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1810:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1811:     my (@respids);
 1812:      my @part_response_id = &flatten_responseType($responseType);
 1813:     foreach my $part_response_id (@part_response_id) {
 1814:     	my ($part,$resp) = @{ $part_response_id };
 1815:         if ($part eq $partid) {
 1816:             push(@respids,$resp);
 1817:         }
 1818:     }
 1819:     my $result;
 1820:     foreach my $respid (@respids) {
 1821: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1822: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1823: 	next if (!@$files);
 1824: 	my $file_counter = 1;
 1825: 	foreach my $file (@$files) {
 1826: 	    if ($file =~ /\/portfolio\//) {
 1827:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1828:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1829:     	        $file_disp = "$name.$ext";
 1830:     	        $file = $file_path.$file_disp;
 1831:     	        $result.=&mt('Return commented version of [_1] to student.',
 1832:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1833:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1834:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1835:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1836:     	        $file_counter++;
 1837: 	    }
 1838: 	}
 1839:     }
 1840:     return $result;    
 1841: }
 1842: 
 1843: sub show_problem {
 1844:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1845:     my $rendered;
 1846:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1847:     &Apache::lonxml::remember_problem_counter();
 1848:     if ($mode eq 'both' or $mode eq 'text') {
 1849: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1850: 						       $env{'request.course.id'},
 1851: 						       undef,\%form);
 1852:     }
 1853:     if ($removeform) {
 1854: 	$rendered=~s|<form(.*?)>||g;
 1855: 	$rendered=~s|</form>||g;
 1856: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1857:     }
 1858:     my $companswer;
 1859:     if ($mode eq 'both' or $mode eq 'answer') {
 1860: 	&Apache::lonxml::restore_problem_counter();
 1861: 	$companswer=
 1862: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1863: 						    $env{'request.course.id'},
 1864: 						    %form);
 1865:     }
 1866:     if ($removeform) {
 1867: 	$companswer=~s|<form(.*?)>||g;
 1868: 	$companswer=~s|</form>||g;
 1869: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1870:     }
 1871:     $rendered=
 1872:         '<div class="LC_Box">'
 1873:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1874:        .$rendered
 1875:        .'</div>';
 1876:     $companswer=
 1877:         '<div class="LC_Box">'
 1878:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1879:        .$companswer
 1880:        .'</div>';
 1881:     my $result;
 1882:     if ($mode eq 'both') {
 1883:         $result=$rendered.$companswer;
 1884:     } elsif ($mode eq 'text') {
 1885:         $result=$rendered;
 1886:     } elsif ($mode eq 'answer') {
 1887:         $result=$companswer;
 1888:     }
 1889:     return $result;
 1890: }
 1891: 
 1892: sub files_exist {
 1893:     my ($r, $symb) = @_;
 1894:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1895: 
 1896:     foreach my $student (@students) {
 1897:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1898:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1899: 					      $udom,$uname);
 1900:         my ($string,$timestamp)= &get_last_submission(\%record);
 1901:         foreach my $submission (@$string) {
 1902:             my ($partid,$respid) =
 1903: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1904:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1905: 					   \%record);
 1906:             return 1 if (@$files);
 1907:         }
 1908:     }
 1909:     return 0;
 1910: }
 1911: 
 1912: sub download_all_link {
 1913:     my ($r,$symb) = @_;
 1914:     my $all_students = 
 1915: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1916: 
 1917:     my $parts =
 1918: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1919: 
 1920:     my $identifier = &Apache::loncommon::get_cgi_id();
 1921:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1922:                              'cgi.'.$identifier.'.symb' => $symb,
 1923:                              'cgi.'.$identifier.'.parts' => $parts,});
 1924:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1925: 	      &mt('Download All Submitted Documents').'</a>');
 1926:     return
 1927: }
 1928: 
 1929: sub build_section_inputs {
 1930:     my $section_inputs;
 1931:     if ($env{'form.section'} eq '') {
 1932:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1933:     } else {
 1934:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1935:         foreach my $section (@sections) {
 1936:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1937:         }
 1938:     }
 1939:     return $section_inputs;
 1940: }
 1941: 
 1942: # --------------------------- show submissions of a student, option to grade 
 1943: sub submission {
 1944:     my ($request,$counter,$total) = @_;
 1945:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1946:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1947:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1948:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1949:     my $symb = &get_symb($request); 
 1950:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1951: 
 1952:     if (!&canview($usec)) {
 1953: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1954: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1955: 			$env{'request.course.id'}.')</span>');
 1956: 	$request->print(&show_grading_menu_form($symb));
 1957: 	return;
 1958:     }
 1959: 
 1960:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1961:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1962:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1963:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1964:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1965: 	'" src="'.$request->dir_config('lonIconsURL').
 1966: 	'/check.gif" height="16" border="0" />';
 1967: 
 1968:     my %old_essays;
 1969:     # header info
 1970:     if ($counter == 0) {
 1971: 	&sub_page_js($request);
 1972: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1973: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1974: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1975: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1976: 	    &download_all_link($request, $symb);
 1977: 	}
 1978: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1979: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1980: 
 1981: 	# option to display problem, only once else it cause problems 
 1982:         # with the form later since the problem has a form.
 1983: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1984: 	    my $mode;
 1985: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1986: 		$mode='both';
 1987: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1988: 		$mode='text';
 1989: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1990: 		$mode='answer';
 1991: 	    }
 1992: 	    &Apache::lonxml::clear_problem_counter();
 1993: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1994: 	}
 1995: 
 1996: 	# kwclr is the only variable that is guaranteed to be non blank 
 1997:         # if this subroutine has been called once.
 1998: 	my %keyhash = ();
 1999: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2000: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2001: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2002: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2003: 
 2004: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2005: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2006: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2007: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2008: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2009: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2010: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2011: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2012: 	}
 2013: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2014: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2015: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2016: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2017: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2018: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2019: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2020: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2021: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2022: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2023: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2024: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2025: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2026: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2027: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2028: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2029: 			&build_section_inputs().
 2030: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2031: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2032: 			'<input type="hidden" name="NCT"'.
 2033: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2034: 	if ($env{'form.handgrade'} eq 'yes') {
 2035: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2036: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2037: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2038: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2039: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2040: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2041: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2042: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2043: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2044: 	    }
 2045: 	}
 2046: 	
 2047: 	my ($cts,$prnmsg) = (1,'');
 2048: 	while ($cts <= $env{'form.savemsgN'}) {
 2049: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2050: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2051: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2052: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2053: 		'" />'."\n".
 2054: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2055: 	    $cts++;
 2056: 	}
 2057: 	$request->print($prnmsg);
 2058: 
 2059: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2060: #
 2061: # Print out the keyword options line
 2062: #
 2063: 	    $request->print(<<KEYWORDS);
 2064: &nbsp;<b>Keyword Options:</b>&nbsp;
 2065: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2066: <a href="#" onmousedown="javascript:getSel(); return false"
 2067:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2068: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2069: KEYWORDS
 2070: #
 2071: # Load the other essays for similarity check
 2072: #
 2073:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2074: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2075: 	    $apath=&escape($apath);
 2076: 	    $apath=~s/\W/\_/gs;
 2077: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2078:         }
 2079:     }
 2080: 
 2081: # This is where output for one specific student would start
 2082:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2083:     $request->print(
 2084:         "\n\n"
 2085:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2086:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2087:        ."\n"
 2088:     );
 2089: 
 2090:     # Show additional functions if allowed
 2091:     if ($perm{'vgr'}) {
 2092:         $request->print(
 2093:             &Apache::loncommon::track_student_link(
 2094:                 &mt('View recent activity'),
 2095:                 $uname,$udom,'check')
 2096:            .' '
 2097:         );
 2098:     }
 2099:     if ($perm{'opa'}) {
 2100:         $request->print(
 2101:             &Apache::loncommon::pprmlink(
 2102:                 &mt('Set/Change parameters'),
 2103:                 $uname,$udom,$symb,'check'));
 2104:     }
 2105: 
 2106:     # Show Problem
 2107:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2108: 	my $mode;
 2109: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2110: 	    $mode='both';
 2111: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2112: 	    $mode='text';
 2113: 	} elsif ($env{'form.vAns'} eq 'all') {
 2114: 	    $mode='answer';
 2115: 	}
 2116: 	&Apache::lonxml::clear_problem_counter();
 2117: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2118:     }
 2119: 
 2120:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2121:     my $res_error;
 2122:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2123:     if ($res_error) {
 2124:         $request->print(&navmap_errormsg());
 2125:         return;
 2126:     }
 2127: 
 2128:     # Display student info
 2129:     $request->print(($counter == 0 ? '' : '<br />'));
 2130: 
 2131:     my $result='<div class="LC_Box">'
 2132:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2133:     $result.='<input type="hidden" name="name'.$counter.
 2134:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2135:     if ($env{'form.handgrade'} eq 'no') {
 2136:         $result.='<p class="LC_info">'
 2137:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2138:                 ."</p>\n";
 2139:     }
 2140: 
 2141:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2142:     my $fullname;
 2143:     my $col_fullnames = [];
 2144:     if ($env{'form.handgrade'} eq 'yes') {
 2145: 	(my $sub_result,$fullname,$col_fullnames)=
 2146: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2147: 				 $counter);
 2148: 	$result.=$sub_result;
 2149:     }
 2150:     $request->print($result."\n");
 2151: 
 2152:     # print student answer/submission
 2153:     # Options are (1) Handgraded submission only
 2154:     #             (2) Last submission, includes submission that is not handgraded 
 2155:     #                  (for multi-response type part)
 2156:     #             (3) Last submission plus the parts info
 2157:     #             (4) The whole record for this student
 2158:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2159: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2160: 	
 2161: 	my $lastsubonly;
 2162: 
 2163:         if ($$timestamp eq '') {
 2164:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2165:         } else {
 2166:             $lastsubonly =
 2167:                 '<div class="LC_grade_submissions_body">'
 2168:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2169: 
 2170: 	    my %seenparts;
 2171: 	    my @part_response_id = &flatten_responseType($responseType);
 2172: 	    foreach my $part (@part_response_id) {
 2173: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2174: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2175: 
 2176: 		my ($partid,$respid) = @{ $part };
 2177: 		my $display_part=&get_display_part($partid,$symb);
 2178: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2179: 		    if (exists($seenparts{$partid})) { next; }
 2180: 		    $seenparts{$partid}=1;
 2181: 		    my $submitby='<b>Part:</b> '.$display_part.
 2182: 			' <b>Collaborative submission by:</b> '.
 2183: 			'<a href="javascript:viewSubmitter(\''.
 2184: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2185: 			'\');" target="_self">'.
 2186: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2187: 		    $request->print($submitby);
 2188: 		    next;
 2189: 		}
 2190: 		my $responsetype = $responseType->{$partid}->{$respid};
 2191: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2192:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2193:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2194:                         ' <span class="LC_internal_info">'.
 2195:                         '('.&mt('Part ID: [_1]',$respid).')'.
 2196:                         '</span>&nbsp; &nbsp;'.
 2197: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2198: 		    next;
 2199: 		}
 2200: 		foreach my $submission (@$string) {
 2201: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2202: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2203: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2204: 		    # Similarity check
 2205: 		    my $similar='';
 2206: 		    if($env{'form.checkPlag'}){
 2207: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2208: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2209: 			if ($osim) {
 2210: 			    $osim=int($osim*100.0);
 2211: 			    my %old_course_desc = 
 2212: 				&Apache::lonnet::coursedescription($ocrsid,
 2213: 								   {'one_time' => 1});
 2214: 
 2215:                             if ($hide) {
 2216:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2217:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2218:                             } else {
 2219: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2220: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2221: 				        $osim,
 2222: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2223: 				        $old_course_desc{'description'},
 2224: 				        $old_course_desc{'num'},
 2225: 				        $old_course_desc{'domain'}).
 2226: 				    '</span></h3><blockquote><i>'.
 2227: 				    &keywords_highlight($oessay).
 2228: 				    '</i></blockquote><hr />';
 2229:                             }
 2230: 			}
 2231: 		    }
 2232: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2233: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2234: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2235: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2236: 			my $display_part=&get_display_part($partid,$symb);
 2237:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2238:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2239:                             ' <span class="LC_internal_info">'.
 2240:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2241:                             '</span>&nbsp; &nbsp;';
 2242: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2243: 			if (@$files) {
 2244:                             if ($hide) {
 2245:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2246:                             } else {
 2247:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2248:                                 foreach my $file (@$files) {
 2249:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2250:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2251:                                 }
 2252:                             }
 2253: 			    $lastsubonly.='<br />';
 2254: 			}
 2255:                         if ($hide) {
 2256:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2257:                         } else {
 2258: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2259: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2260: 					     $respid,\%record,$order,undef,$uname,$udom);
 2261:                         }
 2262: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2263: 			$lastsubonly.='</div>';
 2264: 		    }
 2265: 		}
 2266: 	    }
 2267: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2268: 	}
 2269: 	$request->print($lastsubonly);
 2270:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2271: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2272: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2273:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2274: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2275: 								 $env{'request.course.id'},
 2276: 								 $last,'.submission',
 2277: 								 'Apache::grades::keywords_highlight'));
 2278:     }
 2279: 
 2280:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2281: 	.$udom.'" />'."\n");
 2282:     # return if view submission with no grading option
 2283:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2284: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2285: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2286: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2287: 	$toGrade.='</div>'."\n";
 2288: 	if (($env{'form.command'} eq 'submission') || 
 2289: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2290: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2291: 	}
 2292: 	$request->print($toGrade);
 2293: 	return;
 2294:     } else {
 2295: 	$request->print('</div>'."\n");
 2296:     }
 2297: 
 2298:     # essay grading message center
 2299:     if ($env{'form.handgrade'} eq 'yes') {
 2300: 	my $result='<div class="LC_grade_message_center">';
 2301:     
 2302: 	$result.='<div class="LC_grade_message_center_header">'.
 2303: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2304: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2305: 	my $msgfor = $givenn.' '.$lastname;
 2306: 	if (scalar(@$col_fullnames) > 0) {
 2307: 	    my $lastone = pop(@$col_fullnames);
 2308: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2309: 	}
 2310: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2311: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2312: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2313: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2314: 	    ',\''.$msgfor.'\');" target="_self">'.
 2315: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2316: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2317: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2318: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2319: 	    '<br />&nbsp;('.
 2320: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2321: 	$result.='</div></div>';
 2322: 	$request->print($result);
 2323:     }
 2324: 
 2325:     my %seen = ();
 2326:     my @partlist;
 2327:     my @gradePartRespid;
 2328:     my @part_response_id = &flatten_responseType($responseType);
 2329:     $request->print(
 2330:         '<div class="LC_Box">'
 2331:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2332:     );
 2333:     $request->print(&gradeBox_start());
 2334:     foreach my $part_response_id (@part_response_id) {
 2335:     	my ($partid,$respid) = @{ $part_response_id };
 2336: 	my $part_resp = join('_',@{ $part_response_id });
 2337: 	next if ($seen{$partid} > 0);
 2338: 	$seen{$partid}++;
 2339: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2340: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2341: 	push(@partlist,$partid);
 2342: 	push(@gradePartRespid,$partid.'.'.$respid);
 2343: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2344:     }
 2345:     $request->print(&gradeBox_end()); # </div>
 2346:     $request->print('</div>');
 2347: 
 2348:     $request->print('<div class="LC_grade_info_links">');
 2349:     $request->print('</div>');
 2350: 
 2351:     $result='<input type="hidden" name="partlist'.$counter.
 2352: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2353:     $result.='<input type="hidden" name="gradePartRespid'.
 2354: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2355:     my $ctr = 0;
 2356:     while ($ctr < scalar(@partlist)) {
 2357: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2358: 	    $partlist[$ctr].'" />'."\n";
 2359: 	$ctr++;
 2360:     }
 2361:     $request->print($result.''."\n");
 2362: 
 2363: # Done with printing info for one student
 2364: 
 2365:     $request->print('</div>');#LC_grade_show_user
 2366: 
 2367: 
 2368:     # print end of form
 2369:     if ($counter == $total) {
 2370:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2371: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2372: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2373: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2374: 	my $ntstu ='<select name="NTSTU">'.
 2375: 	    '<option>1</option><option>2</option>'.
 2376: 	    '<option>3</option><option>5</option>'.
 2377: 	    '<option>7</option><option>10</option></select>'."\n";
 2378: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2379: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2380:         $endform.=&mt('[_1]student(s)',$ntstu);
 2381: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2382: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2383: 	    '<input type="button" value="'.&mt('Next').'" '.
 2384: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2385:         $endform.='<span class="LC_warning">'.
 2386:                   &mt('(Next and Previous (student) do not save the scores.)').
 2387:                   '</span>'."\n" ;
 2388:         $endform.="<input type='hidden' value='".&get_increment().
 2389:             "' name='increment' />";
 2390: 	$endform.='</td></tr></table></form>';
 2391: 	$endform.=&show_grading_menu_form($symb);
 2392: 	$request->print($endform);
 2393:     }
 2394:     return '';
 2395: }
 2396: 
 2397: sub check_collaborators {
 2398:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2399:     my ($result,@col_fullnames);
 2400:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2401:     foreach my $part (keys(%$handgrade)) {
 2402: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2403: 					'.maxcollaborators',
 2404: 					$symb,$udom,$uname);
 2405: 	next if ($ncol <= 0);
 2406: 	$part =~ s/\_/\./g;
 2407: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2408: 	my (@good_collaborators, @bad_collaborators);
 2409: 	foreach my $possible_collaborator
 2410: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2411: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2412: 	    next if ($possible_collaborator eq '');
 2413: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2414: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2415: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2416: 	    # Doing this grep allows 'fuzzy' specification
 2417: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2418: 			       keys(%$classlist));
 2419: 	    if (! scalar(@matches)) {
 2420: 		push(@bad_collaborators, $possible_collaborator);
 2421: 	    } else {
 2422: 		push(@good_collaborators, @matches);
 2423: 	    }
 2424: 	}
 2425: 	if (scalar(@good_collaborators) != 0) {
 2426: 	    $result.='<br />'.&mt('Collaborators: ');
 2427: 	    foreach my $name (@good_collaborators) {
 2428: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2429: 		push(@col_fullnames, $givenn.' '.$lastname);
 2430: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2431: 	    }
 2432: 	    $result.='<br />'."\n";
 2433: 	    my ($part)=split(/\./,$part);
 2434: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2435: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2436: 		"\n";
 2437: 	}
 2438: 	if (scalar(@bad_collaborators) > 0) {
 2439: 	    $result.='<div class="LC_warning">';
 2440: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2441: 	    $result .= '</div>';
 2442: 	}         
 2443: 	if (scalar(@bad_collaborators > $ncol)) {
 2444: 	    $result .= '<div class="LC_warning">';
 2445: 	    $result .= &mt('This student has submitted too many '.
 2446: 		'collaborators.  Maximum is [_1].',$ncol);
 2447: 	    $result .= '</div>';
 2448: 	}
 2449:     }
 2450:     return ($result,$fullname,\@col_fullnames);
 2451: }
 2452: 
 2453: #--- Retrieve the last submission for all the parts
 2454: sub get_last_submission {
 2455:     my ($returnhash)=@_;
 2456:     my (@string,$timestamp,%lasthidden);
 2457:     if ($$returnhash{'version'}) {
 2458: 	my %lasthash=();
 2459: 	my ($version);
 2460: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2461: 	    foreach my $key (sort(split(/\:/,
 2462: 					$$returnhash{$version.':keys'}))) {
 2463: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2464: 		$timestamp = 
 2465: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2466: 	    }
 2467: 	}
 2468:         my %typeparts;
 2469:         my $showsurv = 
 2470:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2471:         foreach my $key (sort(keys(%lasthash))) {
 2472:             if ($key =~ /\.type$/) {
 2473:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2474:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2475:                     my ($ign,@parts) = split(/\./,$key);
 2476:                     pop(@parts);
 2477:                     unless ($showsurv) {
 2478:                         my $id = join(',',@parts);
 2479:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2480:                     }
 2481:                     delete($lasthash{$key});
 2482:                 }
 2483:             }
 2484:         }
 2485:         my @hidden = keys(%typeparts);
 2486: 	foreach my $key (keys(%lasthash)) {
 2487: 	    next if ($key !~ /\.submission$/);
 2488:             my $hide;
 2489:             if (@hidden) {
 2490:                 foreach my $id (@hidden) {
 2491:                     if ($key =~ /^\Q$id\E/) {
 2492:                         $hide = 1;
 2493:                         last;
 2494:                     }
 2495:                 }
 2496:             }
 2497: 	    my ($partid,$foo) = split(/submission$/,$key);
 2498: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2499: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2500: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2501: 	}
 2502:     }
 2503:     if (!@string) {
 2504: 	$string[0] =
 2505: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2506:     }
 2507:     return (\@string,\$timestamp);
 2508: }
 2509: 
 2510: #--- High light keywords, with style choosen by user.
 2511: sub keywords_highlight {
 2512:     my $string    = shift;
 2513:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2514:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2515:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2516:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2517:     foreach my $keyword (@keylist) {
 2518: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2519:     }
 2520:     return $string;
 2521: }
 2522: 
 2523: #--- Called from submission routine
 2524: sub processHandGrade {
 2525:     my ($request) = shift;
 2526:     my $symb   = &get_symb($request);
 2527:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2528:     my $button = $env{'form.gradeOpt'};
 2529:     my $ngrade = $env{'form.NCT'};
 2530:     my $ntstu  = $env{'form.NTSTU'};
 2531:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2532:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2533: 
 2534:     if ($button eq 'Save & Next') {
 2535: 	my $ctr = 0;
 2536: 	while ($ctr < $ngrade) {
 2537: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2538: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2539: 	    if ($errorflag eq 'no_score') {
 2540: 		$ctr++;
 2541: 		next;
 2542: 	    }
 2543: 	    if ($errorflag eq 'not_allowed') {
 2544: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2545: 		$ctr++;
 2546: 		next;
 2547: 	    }
 2548: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2549: 	    my ($subject,$message,$msgstatus) = ('','','');
 2550: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2551:             my ($feedurl,$showsymb) =
 2552: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2553: 	    my $messagetail;
 2554: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2555: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2556: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2557: 		$subject.=' ['.$restitle.']';
 2558: 		my (@msgnum) = split(/,/,$includemsg);
 2559: 		foreach (@msgnum) {
 2560: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2561: 		}
 2562: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2563: 		if ($env{'form.withgrades'.$ctr}) {
 2564: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2565: 		    $messagetail = " for <a href=\"".
 2566: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2567: 		}
 2568: 		$msgstatus = 
 2569:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2570: 						     $message.$messagetail,
 2571:                                                      undef,$feedurl,undef,
 2572:                                                      undef,undef,$showsymb,
 2573:                                                      $restitle);
 2574: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2575: 				$msgstatus);
 2576: 	    }
 2577: 	    if ($env{'form.collaborator'.$ctr}) {
 2578: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2579: 		foreach my $collabstr (@collabstrs) {
 2580: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2581: 		    foreach my $collaborator (@collaborators) {
 2582: 			my ($errorflag,$pts,$wgt) = 
 2583: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2584: 					   $env{'form.unamedom'.$ctr},$part);
 2585: 			if ($errorflag eq 'not_allowed') {
 2586: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2587: 			    next;
 2588: 			} elsif ($message ne '') {
 2589: 			    my ($baseurl,$showsymb) = 
 2590: 				&get_feedurl_and_symb($symb,$collaborator,
 2591: 						      $udom);
 2592: 			    if ($env{'form.withgrades'.$ctr}) {
 2593: 				$messagetail = " for <a href=\"".
 2594:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2595: 			    }
 2596: 			    $msgstatus = 
 2597: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2598: 			}
 2599: 		    }
 2600: 		}
 2601: 	    }
 2602: 	    $ctr++;
 2603: 	}
 2604:     }
 2605: 
 2606:     if ($env{'form.handgrade'} eq 'yes') {
 2607: 	# Keywords sorted in alphabatical order
 2608: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2609: 	my %keyhash = ();
 2610: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2611: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2612: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2613: 	$env{'form.keywords'} = join(' ',@keywords);
 2614: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2615: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2616: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2617: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2618: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2619: 
 2620: 	# message center - Order of message gets changed. Blank line is eliminated.
 2621: 	# New messages are saved in env for the next student.
 2622: 	# All messages are saved in nohist_handgrade.db
 2623: 	my ($ctr,$idx) = (1,1);
 2624: 	while ($ctr <= $env{'form.savemsgN'}) {
 2625: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2626: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2627: 		$idx++;
 2628: 	    }
 2629: 	    $ctr++;
 2630: 	}
 2631: 	$ctr = 0;
 2632: 	while ($ctr < $ngrade) {
 2633: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2634: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2635: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2636: 		$idx++;
 2637: 	    }
 2638: 	    $ctr++;
 2639: 	}
 2640: 	$env{'form.savemsgN'} = --$idx;
 2641: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2642: 	my $putresult = &Apache::lonnet::put
 2643: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2644:     }
 2645:     # Called by Save & Refresh from Highlight Attribute Window
 2646:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2647:     if ($env{'form.refresh'} eq 'on') {
 2648: 	my ($ctr,$total) = (0,0);
 2649: 	while ($ctr < $ngrade) {
 2650: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2651: 	    $ctr++;
 2652: 	}
 2653: 	$env{'form.NTSTU'}=$ngrade;
 2654: 	$ctr = 0;
 2655: 	while ($ctr < $total) {
 2656: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2657: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2658: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2659: 	    &submission($request,$ctr,$total-1);
 2660: 	    $ctr++;
 2661: 	}
 2662: 	return '';
 2663:     }
 2664: 
 2665: # Go directly to grade student - from submission or link from chart page
 2666:     if ($button eq 'Grade Student') {
 2667: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2668: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2669: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2670: 	$env{'form.fullname'} = $$fullname{$processUser};
 2671: 	&submission($request,0,0);
 2672: 	return '';
 2673:     }
 2674: 
 2675:     # Get the next/previous one or group of students
 2676:     my $firststu = $env{'form.unamedom0'};
 2677:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2678:     my $ctr = 2;
 2679:     while ($laststu eq '') {
 2680: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2681: 	$ctr++;
 2682: 	$laststu = $firststu if ($ctr > $ngrade);
 2683:     }
 2684: 
 2685:     my (@parsedlist,@nextlist);
 2686:     my ($nextflg) = 0;
 2687:     foreach my $item (sort 
 2688: 	     {
 2689: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2690: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2691: 		 }
 2692: 		 return $a cmp $b;
 2693: 	     } (keys(%$fullname))) {
 2694: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2695: 	    push(@parsedlist,$item);
 2696: 	}
 2697: 	$nextflg = 1 if ($item eq $laststu);
 2698: 	if ($button eq 'Previous') {
 2699: 	    last if ($item eq $firststu);
 2700: 	    push(@parsedlist,$item);
 2701: 	}
 2702:     }
 2703:     $ctr = 0;
 2704:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2705:     my $res_error;
 2706:     my ($partlist) = &response_type($symb,\$res_error);
 2707:     if ($res_error) {
 2708:         $request->print(&navmap_errormsg());
 2709:         return;
 2710:     }
 2711:     foreach my $student (@parsedlist) {
 2712: 	my $submitonly=$env{'form.submitonly'};
 2713: 	my ($uname,$udom) = split(/:/,$student);
 2714: 	
 2715: 	if ($submitonly eq 'queued') {
 2716: 	    my %queue_status = 
 2717: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2718: 							$udom,$uname);
 2719: 	    next if (!defined($queue_status{'gradingqueue'}));
 2720: 	}
 2721: 
 2722: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2723: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2724: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2725: 	    my $submitted = 0;
 2726: 	    my $ungraded = 0;
 2727: 	    my $incorrect = 0;
 2728: 	    foreach my $item (keys(%status)) {
 2729: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2730: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2731: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2732: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2733: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2734: 		    $submitted = 0;
 2735: 		}
 2736: 	    }
 2737: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2738: 				     $submitonly eq 'incorrect' ||
 2739: 				     $submitonly eq 'graded'));
 2740: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2741: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2742: 	}
 2743: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2744: 	last if ($ctr == $ntstu);
 2745: 	$ctr++;
 2746:     }
 2747: 
 2748:     $ctr = 0;
 2749:     my $total = scalar(@nextlist)-1;
 2750: 
 2751:     foreach (sort(@nextlist)) {
 2752: 	my ($uname,$udom,$submitter) = split(/:/);
 2753: 	$env{'form.student'}  = $uname;
 2754: 	$env{'form.userdom'}  = $udom;
 2755: 	$env{'form.fullname'} = $$fullname{$_};
 2756: 	&submission($request,$ctr,$total);
 2757: 	$ctr++;
 2758:     }
 2759:     if ($total < 0) {
 2760: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2761: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2762: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2763: 	$the_end.=&show_grading_menu_form($symb);
 2764: 	$request->print($the_end);
 2765:     }
 2766:     return '';
 2767: }
 2768: 
 2769: #---- Save the score and award for each student, if changed
 2770: sub saveHandGrade {
 2771:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2772:     my @version_parts;
 2773:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2774: 					   $env{'request.course.id'});
 2775:     if (!&canmodify($usec)) { return('not_allowed'); }
 2776:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2777:     my @parts_graded;
 2778:     my %newrecord  = ();
 2779:     my ($pts,$wgt) = ('','');
 2780:     my %aggregate = ();
 2781:     my $aggregateflag = 0;
 2782:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2783:     foreach my $new_part (@parts) {
 2784: 	#collaborator ($submi may vary for different parts
 2785: 	if ($submitter && $new_part ne $part) { next; }
 2786: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2787: 	if ($dropMenu eq 'excused') {
 2788: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2789: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2790: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2791: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2792: 		}
 2793: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2794: 	    }
 2795: 	} elsif ($dropMenu eq 'reset status'
 2796: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2797: 	    foreach my $key (keys(%record)) {
 2798: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2799: 	    }
 2800: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2801: 		"$env{'user.name'}:$env{'user.domain'}";
 2802:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2803: 
 2804:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2805: 					       [$new_part]);
 2806:             my $aggtries =$totaltries;
 2807:             if ($last_resets{$new_part}) {
 2808:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2809: 					   $new_part);
 2810:             }
 2811: 
 2812:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2813:             if ($aggtries > 0) {
 2814:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2815:                 $aggregateflag = 1;
 2816:             }
 2817: 	} elsif ($dropMenu eq '') {
 2818: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2819: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2820: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2821: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2822: 		next;
 2823: 	    }
 2824: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2825: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2826: 	    my $partial= $pts/$wgt;
 2827: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2828: 		#do not update score for part if not changed.
 2829:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2830: 		next;
 2831: 	    } else {
 2832: 	        push(@parts_graded,$new_part);
 2833: 	    }
 2834: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2835: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2836: 	    }
 2837: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2838: 	    if ($partial == 0) {
 2839: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2840: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2841: 		}
 2842: 	    } else {
 2843: 		if ($record{$reckey} ne 'correct_by_override') {
 2844: 		    $newrecord{$reckey} = 'correct_by_override';
 2845: 		}
 2846: 	    }	    
 2847: 	    if ($submitter && 
 2848: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2849: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2850: 	    }
 2851: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2852: 		"$env{'user.name'}:$env{'user.domain'}";
 2853: 	}
 2854: 	# unless problem has been graded, set flag to version the submitted files
 2855: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2856: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2857: 	        $dropMenu eq 'reset status')
 2858: 	   {
 2859: 	    push(@version_parts,$new_part);
 2860: 	}
 2861:     }
 2862:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2863:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2864: 
 2865:     if (%newrecord) {
 2866:         if (@version_parts) {
 2867:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2868:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2869: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2870: 	    foreach my $new_part (@version_parts) {
 2871: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2872: 				$new_part,\%newrecord);
 2873: 	    }
 2874:         }
 2875: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2876: 				$env{'request.course.id'},$domain,$stuname);
 2877: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2878: 				     $cdom,$cnum,$domain,$stuname);
 2879:     }
 2880:     if ($aggregateflag) {
 2881:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2882: 			      $cdom,$cnum);
 2883:     }
 2884:     return ('',$pts,$wgt);
 2885: }
 2886: 
 2887: sub check_and_remove_from_queue {
 2888:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2889:     my @ungraded_parts;
 2890:     foreach my $part (@{$parts}) {
 2891: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2892: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2893: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2894: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2895: 		) {
 2896: 	    push(@ungraded_parts, $part);
 2897: 	}
 2898:     }
 2899:     if ( !@ungraded_parts ) {
 2900: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2901: 					       $cnum,$domain,$stuname);
 2902:     }
 2903: }
 2904: 
 2905: sub handback_files {
 2906:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2907:     my $portfolio_root = '/userfiles/portfolio';
 2908:     my $res_error;
 2909:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2910:     if ($res_error) {
 2911:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2912:         return;
 2913:     }
 2914:     my @part_response_id = &flatten_responseType($responseType);
 2915:     foreach my $part_response_id (@part_response_id) {
 2916:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2917: 	my $part_resp = join('_',@{ $part_response_id });
 2918:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2919:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2920:                 my $file_counter = 1;
 2921: 		my $file_msg;
 2922:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2923:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2924:                     my ($directory,$answer_file) = 
 2925:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2926:                     my ($answer_name,$answer_ver,$answer_ext) =
 2927: 		        &file_name_version_ext($answer_file);
 2928: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2929:                     my $getpropath = 1;
 2930: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2931: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2932:                     # fix file name
 2933:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2934:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2935:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2936:             	                                $save_file_name);
 2937:                     if ($result !~ m|^/uploaded/|) {
 2938:                         $request->print('<br /><span class="LC_error">'.
 2939:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2940:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2941:                                         '</span>');
 2942:                     } else {
 2943:                         # mark the file as read only
 2944:                         my @files = ($save_file_name);
 2945:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2946:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2947: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2948: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2949: 			}
 2950:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2951: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2952: 
 2953:                     }
 2954:                     $request->print("<br />".$fname." will be the uploaded file name");
 2955:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2956:                     $file_counter++;
 2957:                 }
 2958: 		my $subject = "File Handed Back by Instructor ";
 2959: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2960: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2961: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2962: 		$message .= " and can be found in your portfolio space.";
 2963: 		my ($feedurl,$showsymb) = 
 2964: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2965:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2966: 		my $msgstatus = 
 2967:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2968: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2969:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2970:             }
 2971:         }
 2972:     return;
 2973: }
 2974: 
 2975: sub get_feedurl_and_symb {
 2976:     my ($symb,$uname,$udom) = @_;
 2977:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2978:     $url = &Apache::lonnet::clutter($url);
 2979:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2980: 					$symb,$udom,$uname);
 2981:     if ($encrypturl =~ /^yes$/i) {
 2982: 	&Apache::lonenc::encrypted(\$url,1);
 2983: 	&Apache::lonenc::encrypted(\$symb,1);
 2984:     }
 2985:     return ($url,$symb);
 2986: }
 2987: 
 2988: sub get_submitted_files {
 2989:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2990:     my @files;
 2991:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2992:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2993:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2994:     	    push(@files,$file_url.$file);
 2995:         }
 2996:     }
 2997:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2998:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2999:     }
 3000:     return (\@files);
 3001: }
 3002: 
 3003: # ----------- Provides number of tries since last reset.
 3004: sub get_num_tries {
 3005:     my ($record,$last_reset,$part) = @_;
 3006:     my $timestamp = '';
 3007:     my $num_tries = 0;
 3008:     if ($$record{'version'}) {
 3009:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3010:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3011:                 $timestamp = $$record{$version.':timestamp'};
 3012:                 if ($timestamp > $last_reset) {
 3013:                     $num_tries ++;
 3014:                 } else {
 3015:                     last;
 3016:                 }
 3017:             }
 3018:         }
 3019:     }
 3020:     return $num_tries;
 3021: }
 3022: 
 3023: # ----------- Determine decrements required in aggregate totals 
 3024: sub decrement_aggs {
 3025:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3026:     my %decrement = (
 3027:                         attempts => 0,
 3028:                         users => 0,
 3029:                         correct => 0
 3030:                     );
 3031:     $decrement{'attempts'} = $aggtries;
 3032:     if ($solvedstatus =~ /^correct/) {
 3033:         $decrement{'correct'} = 1;
 3034:     }
 3035:     if ($aggtries == $totaltries) {
 3036:         $decrement{'users'} = 1;
 3037:     }
 3038:     foreach my $type (keys(%decrement)) {
 3039:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3040:     }
 3041:     return;
 3042: }
 3043: 
 3044: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3045: sub get_last_resets {
 3046:     my ($symb,$courseid,$partids) =@_;
 3047:     my %last_resets;
 3048:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3049:     my $cname = $env{'course.'.$courseid.'.num'};
 3050:     my @keys;
 3051:     foreach my $part (@{$partids}) {
 3052: 	push(@keys,"$symb\0$part\0resettime");
 3053:     }
 3054:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3055: 				     $cdom,$cname);
 3056:     foreach my $part (@{$partids}) {
 3057: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3058:     }
 3059:     return %last_resets;
 3060: }
 3061: 
 3062: # ----------- Handles creating versions for portfolio files as answers
 3063: sub version_portfiles {
 3064:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3065:     my $version_parts = join('|',@$v_flag);
 3066:     my @returned_keys;
 3067:     my $parts = join('|', @$parts_graded);
 3068:     my $portfolio_root = '/userfiles/portfolio';
 3069:     foreach my $key (keys(%$record)) {
 3070:         my $new_portfiles;
 3071:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3072:             my @versioned_portfiles;
 3073:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3074:             foreach my $file (@portfiles) {
 3075:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3076:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3077: 		my ($answer_name,$answer_ver,$answer_ext) =
 3078: 		    &file_name_version_ext($answer_file);
 3079:                 my $getpropath = 1;    
 3080:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3081:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3082:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3083:                 if ($new_answer ne 'problem getting file') {
 3084:                     push(@versioned_portfiles, $directory.$new_answer);
 3085:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3086:                         [$directory.$new_answer],
 3087:                         [$symb,$env{'request.course.id'},'graded']);
 3088:                 }
 3089:             }
 3090:             $$record{$key} = join(',',@versioned_portfiles);
 3091:             push(@returned_keys,$key);
 3092:         }
 3093:     } 
 3094:     return (@returned_keys);   
 3095: }
 3096: 
 3097: sub get_next_version {
 3098:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3099:     my $version;
 3100:     foreach my $row (@$dir_list) {
 3101:         my ($file) = split(/\&/,$row,2);
 3102:         my ($file_name,$file_version,$file_ext) =
 3103: 	    &file_name_version_ext($file);
 3104:         if (($file_name eq $answer_name) && 
 3105: 	    ($file_ext eq $answer_ext)) {
 3106:                 # gets here if filename and extension match, regardless of version
 3107:                 if ($file_version ne '') {
 3108:                 # a versioned file is found  so save it for later
 3109:                 if ($file_version > $version) {
 3110: 		    $version = $file_version;
 3111: 	        }
 3112:             }
 3113:         }
 3114:     } 
 3115:     $version ++;
 3116:     return($version);
 3117: }
 3118: 
 3119: sub version_selected_portfile {
 3120:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3121:     my ($answer_name,$answer_ver,$answer_ext) =
 3122:         &file_name_version_ext($file_name);
 3123:     my $new_answer;
 3124:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3125:     if($env{'form.copy'} eq '-1') {
 3126:         $new_answer = 'problem getting file';
 3127:     } else {
 3128:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3129:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3130:                             $stu_name,$domain,'copy',
 3131: 		        '/portfolio'.$directory.$new_answer);
 3132:     }    
 3133:     return ($new_answer);
 3134: }
 3135: 
 3136: sub file_name_version_ext {
 3137:     my ($file)=@_;
 3138:     my @file_parts = split(/\./, $file);
 3139:     my ($name,$version,$ext);
 3140:     if (@file_parts > 1) {
 3141: 	$ext=pop(@file_parts);
 3142: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3143: 	    $version=pop(@file_parts);
 3144: 	}
 3145: 	$name=join('.',@file_parts);
 3146:     } else {
 3147: 	$name=join('.',@file_parts);
 3148:     }
 3149:     return($name,$version,$ext);
 3150: }
 3151: 
 3152: #--------------------------------------------------------------------------------------
 3153: #
 3154: #-------------------------- Next few routines handles grading by section or whole class
 3155: #
 3156: #--- Javascript to handle grading by section or whole class
 3157: sub viewgrades_js {
 3158:     my ($request) = shift;
 3159: 
 3160:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3161:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3162:    function writePoint(partid,weight,point) {
 3163: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3164: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3165: 	if (point == "textval") {
 3166: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3167: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3168: 		alert("$alertmsg"+parseFloat(point));
 3169: 		var resetbox = false;
 3170: 		for (var i=0; i<radioButton.length; i++) {
 3171: 		    if (radioButton[i].checked) {
 3172: 			textbox.value = i;
 3173: 			resetbox = true;
 3174: 		    }
 3175: 		}
 3176: 		if (!resetbox) {
 3177: 		    textbox.value = "";
 3178: 		}
 3179: 		return;
 3180: 	    }
 3181: 	    if (parseFloat(point) > parseFloat(weight)) {
 3182: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3183: 				   ") greater than the weight for the part. Accept?");
 3184: 		if (resp == false) {
 3185: 		    textbox.value = "";
 3186: 		    return;
 3187: 		}
 3188: 	    }
 3189: 	    for (var i=0; i<radioButton.length; i++) {
 3190: 		radioButton[i].checked=false;
 3191: 		if (parseFloat(point) == i) {
 3192: 		    radioButton[i].checked=true;
 3193: 		}
 3194: 	    }
 3195: 
 3196: 	} else {
 3197: 	    textbox.value = parseFloat(point);
 3198: 	}
 3199: 	for (i=0;i<document.classgrade.total.value;i++) {
 3200: 	    var user = document.classgrade["ctr"+i].value;
 3201: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3202: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3203: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3204: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3205: 	    if (saveval != "correct") {
 3206: 		scorename.value = point;
 3207: 		if (selname[0].selected != true) {
 3208: 		    selname[0].selected = true;
 3209: 		}
 3210: 	    }
 3211: 	}
 3212: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3213:     }
 3214: 
 3215:     function writeRadText(partid,weight) {
 3216: 	var selval   = document.classgrade["SELVAL_"+partid];
 3217: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3218:         var override = document.classgrade["FORCE_"+partid].checked;
 3219: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3220: 	if (selval[1].selected || selval[2].selected) {
 3221: 	    for (var i=0; i<radioButton.length; i++) {
 3222: 		radioButton[i].checked=false;
 3223: 
 3224: 	    }
 3225: 	    textbox.value = "";
 3226: 
 3227: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3228: 		var user = document.classgrade["ctr"+i].value;
 3229: 		user = user.replace(new RegExp(':', 'g'),"_");
 3230: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3231: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3232: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3233: 		if ((saveval != "correct") || override) {
 3234: 		    scorename.value = "";
 3235: 		    if (selval[1].selected) {
 3236: 			selname[1].selected = true;
 3237: 		    } else {
 3238: 			selname[2].selected = true;
 3239: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3240: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3241: 		    }
 3242: 		}
 3243: 	    }
 3244: 	} else {
 3245: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3246: 		var user = document.classgrade["ctr"+i].value;
 3247: 		user = user.replace(new RegExp(':', 'g'),"_");
 3248: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3249: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3250: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3251: 		if ((saveval != "correct") || override) {
 3252: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3253: 		    selname[0].selected = true;
 3254: 		}
 3255: 	    }
 3256: 	}	    
 3257:     }
 3258: 
 3259:     function changeSelect(partid,user) {
 3260: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3261: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3262: 	var point  = textbox.value;
 3263: 	var weight = document.classgrade["weight_"+partid].value;
 3264: 
 3265: 	if (isNaN(point) || parseFloat(point) < 0) {
 3266: 	    alert("$alertmsg"+parseFloat(point));
 3267: 	    textbox.value = "";
 3268: 	    return;
 3269: 	}
 3270: 	if (parseFloat(point) > parseFloat(weight)) {
 3271: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3272: 			       ") greater than the weight of the part. Accept?");
 3273: 	    if (resp == false) {
 3274: 		textbox.value = "";
 3275: 		return;
 3276: 	    }
 3277: 	}
 3278: 	selval[0].selected = true;
 3279:     }
 3280: 
 3281:     function changeOneScore(partid,user) {
 3282: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3283: 	if (selval[1].selected || selval[2].selected) {
 3284: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3285: 	    if (selval[2].selected) {
 3286: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3287: 	    }
 3288:         }
 3289:     }
 3290: 
 3291:     function resetEntry(numpart) {
 3292: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3293: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3294: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3295: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3296: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3297: 	    for (var i=0; i<radioButton.length; i++) {
 3298: 		radioButton[i].checked=false;
 3299: 
 3300: 	    }
 3301: 	    textbox.value = "";
 3302: 	    selval[0].selected = true;
 3303: 
 3304: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3305: 		var user = document.classgrade["ctr"+i].value;
 3306: 		user = user.replace(new RegExp(':', 'g'),"_");
 3307: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3308: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3309: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3310: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3311: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3312: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3313: 		if (saveselval == "excused") {
 3314: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3315: 		} else {
 3316: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3317: 		}
 3318: 	    }
 3319: 	}
 3320:     }
 3321: 
 3322: VIEWJAVASCRIPT
 3323: }
 3324: 
 3325: #--- show scores for a section or whole class w/ option to change/update a score
 3326: sub viewgrades {
 3327:     my ($request) = shift;
 3328:     &viewgrades_js($request);
 3329: 
 3330:     my ($symb) = &get_symb($request);
 3331:     #need to make sure we have the correct data for later EXT calls, 
 3332:     #thus invalidate the cache
 3333:     &Apache::lonnet::devalidatecourseresdata(
 3334:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3335:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3336:     &Apache::lonnet::clear_EXT_cache_status();
 3337: 
 3338:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3339:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3340: 
 3341:     #view individual student submission form - called using Javascript viewOneStudent
 3342:     $result.=&jscriptNform($symb);
 3343: 
 3344:     #beginning of class grading form
 3345:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3346:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3347: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3348: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3349: 	&build_section_inputs().
 3350: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3351: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3352: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3353: 
 3354:     my ($common_header,$specific_header);
 3355:     if ($env{'form.section'} eq 'all') {
 3356: 	$common_header = &mt('Assign Common Grade to Class');
 3357:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3358:     } elsif ($env{'form.section'} eq 'none') {
 3359:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3360: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3361:     } else {
 3362:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3363:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3364: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3365:     }
 3366:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3367:     #radio buttons/text box for assigning points for a section or class.
 3368:     #handles different parts of a problem
 3369:     my $res_error;
 3370:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3371:     if ($res_error) {
 3372:         return &navmap_errormsg();
 3373:     }
 3374:     my %weight = ();
 3375:     my $ctsparts = 0;
 3376:     my %seen = ();
 3377:     my @part_response_id = &flatten_responseType($responseType);
 3378:     foreach my $part_response_id (@part_response_id) {
 3379:     	my ($partid,$respid) = @{ $part_response_id };
 3380: 	my $part_resp = join('_',@{ $part_response_id });
 3381: 	next if $seen{$partid};
 3382: 	$seen{$partid}++;
 3383: 	my $handgrade=$$handgrade{$part_resp};
 3384: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3385: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3386: 
 3387: 	my $display_part=&get_display_part($partid,$symb);
 3388: 	my $radio.='<table border="0"><tr>';  
 3389: 	my $ctr = 0;
 3390: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3391: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3392: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3393: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3394: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3395: 	    $ctr++;
 3396: 	}
 3397: 	$radio.='</tr></table>';
 3398: 	my $line = '<input type="text" name="TEXTVAL_'.
 3399: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3400: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3401: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3402: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3403: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3404: 		$weight{$partid}.')"> '.
 3405: 	    '<option selected="selected"> </option>'.
 3406: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3407: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3408: 	    '</select></td>'.
 3409:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3410: 	$line.='<input type="hidden" name="partid_'.
 3411: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3412: 	$line.='<input type="hidden" name="weight_'.
 3413: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3414: 
 3415: 	$result.=
 3416: 	    &Apache::loncommon::start_data_table_row()."\n".
 3417: 	    '<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>'.
 3418: 	    &Apache::loncommon::end_data_table_row()."\n";
 3419: 	$ctsparts++;
 3420:     }
 3421:     $result.=&Apache::loncommon::end_data_table()."\n".
 3422: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3423:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3424: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3425: 
 3426:     #table listing all the students in a section/class
 3427:     #header of table
 3428:     $result.= '<h3>'.$specific_header.'</h3>'.
 3429:               &Apache::loncommon::start_data_table().
 3430: 	      &Apache::loncommon::start_data_table_header_row().
 3431: 	      '<th>'.&mt('No.').'</th>'.
 3432: 	      '<th>'.&nameUserString('header')."</th>\n";
 3433:     my $partserror;
 3434:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3435:     if ($partserror) {
 3436:         return &navmap_errormsg();
 3437:     }
 3438:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3439:     my @partids = ();
 3440:     foreach my $part (@parts) {
 3441: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3442:         my $narrowtext = &mt('Tries');
 3443: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3444: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3445: 	my ($partid) = &split_part_type($part);
 3446:         push(@partids,$partid);
 3447: 	my $display_part=&get_display_part($partid,$symb);
 3448: 	if ($display =~ /^Partial Credit Factor/) {
 3449: 	    $result.='<th>'.
 3450: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3451: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3452: 	    next;
 3453: 	    
 3454: 	} else {
 3455: 	    if ($display =~ /Problem Status/) {
 3456: 		my $grade_status_mt = &mt('Grade Status');
 3457: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3458: 	    }
 3459: 	    my $part_mt = &mt('Part:');
 3460: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3461: 	}
 3462: 
 3463: 	$result.='<th>'.$display.'</th>'."\n";
 3464:     }
 3465:     $result.=&Apache::loncommon::end_data_table_header_row();
 3466: 
 3467:     my %last_resets = 
 3468: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3469: 
 3470:     #get info for each student
 3471:     #list all the students - with points and grade status
 3472:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3473:     my $ctr = 0;
 3474:     foreach (sort 
 3475: 	     {
 3476: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3477: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3478: 		 }
 3479: 		 return $a cmp $b;
 3480: 	     } (keys(%$fullname))) {
 3481: 	$ctr++;
 3482: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3483: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3484:     }
 3485:     $result.=&Apache::loncommon::end_data_table();
 3486:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3487:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3488: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3489:     if (scalar(%$fullname) eq 0) {
 3490: 	my $colspan=3+scalar(@parts);
 3491: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3492:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3493: 	$result='<span class="LC_warning">'.
 3494: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3495: 	        $section_display, $stu_status).
 3496: 	    '</span>';
 3497:     }
 3498:     $result.=&show_grading_menu_form($symb);
 3499:     return $result;
 3500: }
 3501: 
 3502: #--- call by previous routine to display each student
 3503: sub viewstudentgrade {
 3504:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3505:     my ($uname,$udom) = split(/:/,$student);
 3506:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3507:     my %aggregates = (); 
 3508:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3509: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3510: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3511: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3512: 	'\');" target="_self">'.$fullname.'</a> '.
 3513: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3514:     $student=~s/:/_/; # colon doen't work in javascript for names
 3515:     foreach my $apart (@$parts) {
 3516: 	my ($part,$type) = &split_part_type($apart);
 3517: 	my $score=$record{"resource.$part.$type"};
 3518:         $result.='<td align="center">';
 3519:         my ($aggtries,$totaltries);
 3520:         unless (exists($aggregates{$part})) {
 3521: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3522: 
 3523: 	    $aggtries = $totaltries;
 3524:             if ($$last_resets{$part}) {  
 3525:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3526: 					   $part);
 3527:             }
 3528:             $result.='<input type="hidden" name="'.
 3529:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3530:             $result.='<input type="hidden" name="'.
 3531:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3532:             $aggregates{$part} = 1;
 3533:         }
 3534: 	if ($type eq 'awarded') {
 3535: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3536: 	    $result.='<input type="hidden" name="'.
 3537: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3538: 	    $result.='<input type="text" name="'.
 3539: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3540:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3541: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3542: 	} elsif ($type eq 'solved') {
 3543: 	    my ($status,$foo)=split(/_/,$score,2);
 3544: 	    $status = 'nothing' if ($status eq '');
 3545: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3546: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3547: 	    $result.='&nbsp;<select name="'.
 3548: 		'GD_'.$student.'_'.$part.'_solved" '.
 3549:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3550: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3551: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3552: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3553: 	    $result.="</select>&nbsp;</td>\n";
 3554: 	} else {
 3555: 	    $result.='<input type="hidden" name="'.
 3556: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3557: 		    "\n";
 3558: 	    $result.='<input type="text" name="'.
 3559: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3560: 		'value="'.$score.'" size="4" /></td>'."\n";
 3561: 	}
 3562:     }
 3563:     $result.=&Apache::loncommon::end_data_table_row();
 3564:     return $result;
 3565: }
 3566: 
 3567: #--- change scores for all the students in a section/class
 3568: #    record does not get update if unchanged
 3569: sub editgrades {
 3570:     my ($request) = @_;
 3571: 
 3572:     my $symb=&get_symb($request);
 3573:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3574:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3575:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3576:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3577: 
 3578:     my $result= &Apache::loncommon::start_data_table().
 3579: 	&Apache::loncommon::start_data_table_header_row().
 3580: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3581: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3582:     my %scoreptr = (
 3583: 		    'correct'  =>'correct_by_override',
 3584: 		    'incorrect'=>'incorrect_by_override',
 3585: 		    'excused'  =>'excused',
 3586: 		    'ungraded' =>'ungraded_attempted',
 3587:                     'credited' =>'credit_attempted',
 3588: 		    'nothing'  => '',
 3589: 		    );
 3590:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3591: 
 3592:     my (@partid);
 3593:     my %weight = ();
 3594:     my %columns = ();
 3595:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3596: 
 3597:     my $partserror;
 3598:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3599:     if ($partserror) {
 3600:         return &navmap_errormsg();
 3601:     }
 3602:     my $header;
 3603:     while ($ctr < $env{'form.totalparts'}) {
 3604: 	my $partid = $env{'form.partid_'.$ctr};
 3605: 	push(@partid,$partid);
 3606: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3607: 	$ctr++;
 3608:     }
 3609:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3610:     foreach my $partid (@partid) {
 3611: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3612: 	    '<th align="center">'.&mt('New Score').'</th>';
 3613: 	$columns{$partid}=2;
 3614: 	foreach my $stores (@parts) {
 3615: 	    my ($part,$type) = &split_part_type($stores);
 3616: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3617: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3618: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3619: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3620:             my $narrowtext = &mt('Tries');
 3621: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3622: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3623: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3624: 	    $columns{$partid}+=2;
 3625: 	}
 3626:     }
 3627:     foreach my $partid (@partid) {
 3628: 	my $display_part=&get_display_part($partid,$symb);
 3629: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3630: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3631: 	    '</th>';
 3632: 
 3633:     }
 3634:     $result .= &Apache::loncommon::end_data_table_header_row().
 3635: 	&Apache::loncommon::start_data_table_header_row().
 3636: 	$header.
 3637: 	&Apache::loncommon::end_data_table_header_row();
 3638:     my @noupdate;
 3639:     my ($updateCtr,$noupdateCtr) = (1,1);
 3640:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3641: 	my $line;
 3642: 	my $user = $env{'form.ctr'.$i};
 3643: 	my ($uname,$udom)=split(/:/,$user);
 3644: 	my %newrecord;
 3645: 	my $updateflag = 0;
 3646: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3647: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3648: 	if (!&canmodify($usec)) {
 3649: 	    my $numcols=scalar(@partid)*4+2;
 3650: 	    push(@noupdate,
 3651: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3652: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3653: 	    next;
 3654: 	}
 3655:         my %aggregate = ();
 3656:         my $aggregateflag = 0;
 3657: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3658: 	foreach (@partid) {
 3659: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3660: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3661: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3662: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3663: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3664: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3665: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3666: 	    my $score;
 3667: 	    if ($partial eq '') {
 3668: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3669: 	    } elsif ($partial > 0) {
 3670: 		$score = 'correct_by_override';
 3671: 	    } elsif ($partial == 0) {
 3672: 		$score = 'incorrect_by_override';
 3673: 	    }
 3674: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3675: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3676: 
 3677: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3678: 		"$env{'user.name'}:$env{'user.domain'}";
 3679: 	    if ($dropMenu eq 'reset status' &&
 3680: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3681: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3682: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3683: 		$newrecord{'resource.'.$_.'.award'} = '';
 3684: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3685: 		$updateflag = 1;
 3686:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3687:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3688:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3689:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3690:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3691:                     $aggregateflag = 1;
 3692:                 }
 3693: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3694: 		$updateflag = 1;
 3695: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3696: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3697: 		$rec_update++;
 3698: 	    }
 3699: 
 3700: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3701: 		'<td align="center">'.$awarded.
 3702: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3703: 
 3704: 
 3705: 	    my $partid=$_;
 3706: 	    foreach my $stores (@parts) {
 3707: 		my ($part,$type) = &split_part_type($stores);
 3708: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3709: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3710: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3711: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3712: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3713: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3714: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3715: 		    $updateflag=1;
 3716: 		}
 3717: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3718: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3719: 	    }
 3720: 	}
 3721: 	$line.="\n";
 3722: 
 3723: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3724: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3725: 
 3726: 	if ($updateflag) {
 3727: 	    $count++;
 3728: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3729: 				    $udom,$uname);
 3730: 
 3731: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3732: 					      $cnum,$udom,$uname)) {
 3733: 		# need to figure out if should be in queue.
 3734: 		my %record =  
 3735: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3736: 					     $udom,$uname);
 3737: 		my $all_graded = 1;
 3738: 		my $none_graded = 1;
 3739: 		foreach my $part (@parts) {
 3740: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3741: 			$all_graded = 0;
 3742: 		    } else {
 3743: 			$none_graded = 0;
 3744: 		    }
 3745: 		}
 3746: 
 3747: 		if ($all_graded || $none_graded) {
 3748: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3749: 							   $symb,$cdom,$cnum,
 3750: 							   $udom,$uname);
 3751: 		}
 3752: 	    }
 3753: 
 3754: 	    $result.=&Apache::loncommon::start_data_table_row().
 3755: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3756: 		&Apache::loncommon::end_data_table_row();
 3757: 	    $updateCtr++;
 3758: 	} else {
 3759: 	    push(@noupdate,
 3760: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3761: 	    $noupdateCtr++;
 3762: 	}
 3763:         if ($aggregateflag) {
 3764:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3765: 				  $cdom,$cnum);
 3766:         }
 3767:     }
 3768:     if (@noupdate) {
 3769: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3770: 	my $numcols=scalar(@partid)*4+2;
 3771: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3772: 	    '<td align="center" colspan="'.$numcols.'">'.
 3773: 	    &mt('No Changes Occurred For the Students Below').
 3774: 	    '</td>'.
 3775: 	    &Apache::loncommon::end_data_table_row();
 3776: 	foreach my $line (@noupdate) {
 3777: 	    $result.=
 3778: 		&Apache::loncommon::start_data_table_row().
 3779: 		$line.
 3780: 		&Apache::loncommon::end_data_table_row();
 3781: 	}
 3782:     }
 3783:     $result .= &Apache::loncommon::end_data_table().
 3784: 	&show_grading_menu_form($symb);
 3785:     my $msg = '<p><b>'.
 3786: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3787: 	    $rec_update,$count).'</b><br />'.
 3788: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3789: 	'</b></p>';
 3790:     return $title.$msg.$result;
 3791: }
 3792: 
 3793: sub split_part_type {
 3794:     my ($partstr) = @_;
 3795:     my ($temp,@allparts)=split(/_/,$partstr);
 3796:     my $type=pop(@allparts);
 3797:     my $part=join('_',@allparts);
 3798:     return ($part,$type);
 3799: }
 3800: 
 3801: #------------- end of section for handling grading by section/class ---------
 3802: #
 3803: #----------------------------------------------------------------------------
 3804: 
 3805: 
 3806: #----------------------------------------------------------------------------
 3807: #
 3808: #-------------------------- Next few routines handles grading by csv upload
 3809: #
 3810: #--- Javascript to handle csv upload
 3811: sub csvupload_javascript_reverse_associate {
 3812:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3813:     my $error2=&mt('You need to specify at least one grading field');
 3814:   return(<<ENDPICK);
 3815:   function verify(vf) {
 3816:     var foundsomething=0;
 3817:     var founduname=0;
 3818:     var foundID=0;
 3819:     for (i=0;i<=vf.nfields.value;i++) {
 3820:       tw=eval('vf.f'+i+'.selectedIndex');
 3821:       if (i==0 && tw!=0) { foundID=1; }
 3822:       if (i==1 && tw!=0) { founduname=1; }
 3823:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3824:     }
 3825:     if (founduname==0 && foundID==0) {
 3826: 	alert('$error1');
 3827: 	return;
 3828:     }
 3829:     if (foundsomething==0) {
 3830: 	alert('$error2');
 3831: 	return;
 3832:     }
 3833:     vf.submit();
 3834:   }
 3835:   function flip(vf,tf) {
 3836:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3837:     var i;
 3838:     for (i=0;i<=vf.nfields.value;i++) {
 3839:       //can not pick the same destination field for both name and domain
 3840:       if (((i ==0)||(i ==1)) && 
 3841:           ((tf==0)||(tf==1)) && 
 3842:           (i!=tf) &&
 3843:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3844:         eval('vf.f'+i+'.selectedIndex=0;')
 3845:       }
 3846:     }
 3847:   }
 3848: ENDPICK
 3849: }
 3850: 
 3851: sub csvupload_javascript_forward_associate {
 3852:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3853:     my $error2=&mt('You need to specify at least one grading field');
 3854:   return(<<ENDPICK);
 3855:   function verify(vf) {
 3856:     var foundsomething=0;
 3857:     var founduname=0;
 3858:     var foundID=0;
 3859:     for (i=0;i<=vf.nfields.value;i++) {
 3860:       tw=eval('vf.f'+i+'.selectedIndex');
 3861:       if (tw==1) { foundID=1; }
 3862:       if (tw==2) { founduname=1; }
 3863:       if (tw>3) { foundsomething=1; }
 3864:     }
 3865:     if (founduname==0 && foundID==0) {
 3866: 	alert('$error1');
 3867: 	return;
 3868:     }
 3869:     if (foundsomething==0) {
 3870: 	alert('$error2');
 3871: 	return;
 3872:     }
 3873:     vf.submit();
 3874:   }
 3875:   function flip(vf,tf) {
 3876:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3877:     var i;
 3878:     //can not pick the same destination field twice
 3879:     for (i=0;i<=vf.nfields.value;i++) {
 3880:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3881:         eval('vf.f'+i+'.selectedIndex=0;')
 3882:       }
 3883:     }
 3884:   }
 3885: ENDPICK
 3886: }
 3887: 
 3888: sub csvuploadmap_header {
 3889:     my ($request,$symb,$datatoken,$distotal)= @_;
 3890:     my $javascript;
 3891:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3892: 	$javascript=&csvupload_javascript_reverse_associate();
 3893:     } else {
 3894: 	$javascript=&csvupload_javascript_forward_associate();
 3895:     }
 3896: 
 3897:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3898:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3899:     my $ignore=&mt('Ignore First Line');
 3900:     $symb = &Apache::lonenc::check_encrypt($symb);
 3901:     $request->print(<<ENDPICK);
 3902: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3903: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3904: $result
 3905: <hr />
 3906: <h3>Identify fields</h3>
 3907: Total number of records found in file: $distotal <hr />
 3908: Enter as many fields as you can. The system will inform you and bring you back
 3909: to this page if the data selected is insufficient to run your class.<hr />
 3910: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3911: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3912: <input type="hidden" name="associate"  value="" />
 3913: <input type="hidden" name="phase"      value="three" />
 3914: <input type="hidden" name="datatoken"  value="$datatoken" />
 3915: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3916: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3917: <input type="hidden" name="upfile_associate" 
 3918:                                        value="$env{'form.upfile_associate'}" />
 3919: <input type="hidden" name="symb"       value="$symb" />
 3920: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3921: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3922: <input type="hidden" name="command"    value="csvuploadoptions" />
 3923: <hr />
 3924: ENDPICK
 3925:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3926:     return '';
 3927: 
 3928: }
 3929: 
 3930: sub csvupload_fields {
 3931:     my ($symb,$errorref) = @_;
 3932:     my (@parts) = &getpartlist($symb,$errorref);
 3933:     if (ref($errorref)) {
 3934:         if ($$errorref) {
 3935:             return;
 3936:         }
 3937:     }
 3938: 
 3939:     my @fields=(['ID','Student/Employee ID'],
 3940: 		['username','Student Username'],
 3941: 		['domain','Student Domain']);
 3942:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3943:     foreach my $part (sort(@parts)) {
 3944: 	my @datum;
 3945: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3946: 	my $name=$part;
 3947: 	if  (!$display) { $display = $name; }
 3948: 	@datum=($name,$display);
 3949: 	if ($name=~/^stores_(.*)_awarded/) {
 3950: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3951: 	}
 3952: 	push(@fields,\@datum);
 3953:     }
 3954:     return (@fields);
 3955: }
 3956: 
 3957: sub csvuploadmap_footer {
 3958:     my ($request,$i,$keyfields) =@_;
 3959:     $request->print(<<ENDPICK);
 3960: </table>
 3961: <input type="hidden" name="nfields" value="$i" />
 3962: <input type="hidden" name="keyfields" value="$keyfields" />
 3963: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3964: </form>
 3965: ENDPICK
 3966: }
 3967: 
 3968: sub checkforfile_js {
 3969:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3970:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3971:     function checkUpload(formname) {
 3972: 	if (formname.upfile.value == "") {
 3973: 	    alert("$alertmsg");
 3974: 	    return false;
 3975: 	}
 3976: 	formname.submit();
 3977:     }
 3978: CSVFORMJS
 3979:     return $result;
 3980: }
 3981: 
 3982: sub upcsvScores_form {
 3983:     my ($request) = shift;
 3984:     my ($symb)=&get_symb($request);
 3985:     if (!$symb) {return '';}
 3986:     my $result=&checkforfile_js();
 3987:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3988:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3989:     $result.=$table;
 3990:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3991:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3992:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3993: 	'</b></td></tr>'."\n";
 3994:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3995:     my $upload=&mt("Upload Scores");
 3996:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3997:     my $ignore=&mt('Ignore First Line');
 3998:     $symb = &Apache::lonenc::check_encrypt($symb);
 3999:     $result.=<<ENDUPFORM;
 4000: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4001: <input type="hidden" name="symb" value="$symb" />
 4002: <input type="hidden" name="command" value="csvuploadmap" />
 4003: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4004: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4005: $upfile_select
 4006: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4007: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4008: </form>
 4009: ENDUPFORM
 4010:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4011:                            &mt("How do I create a CSV file from a spreadsheet"))
 4012:     .'</td></tr></table>'."\n";
 4013:     $result.='</td></tr></table><br /><br />'."\n";
 4014:     $result.=&show_grading_menu_form($symb);
 4015:     return $result;
 4016: }
 4017: 
 4018: 
 4019: sub csvuploadmap {
 4020:     my ($request)= @_;
 4021:     my ($symb)=&get_symb($request);
 4022:     if (!$symb) {return '';}
 4023: 
 4024:     my $datatoken;
 4025:     if (!$env{'form.datatoken'}) {
 4026: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4027:     } else {
 4028: 	$datatoken=$env{'form.datatoken'};
 4029: 	&Apache::loncommon::load_tmp_file($request);
 4030:     }
 4031:     my @records=&Apache::loncommon::upfile_record_sep();
 4032:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4033:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4034:     my ($i,$keyfields);
 4035:     if (@records) {
 4036:         my $fieldserror;
 4037: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4038:         if ($fieldserror) {
 4039:             $request->print(&navmap_errormsg());
 4040:             return;
 4041:         }
 4042: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4043: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4044: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4045: 							  \@fields);
 4046: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4047: 	    chop($keyfields);
 4048: 	} else {
 4049: 	    unshift(@fields,['none','']);
 4050: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4051: 							    \@fields);
 4052:             foreach my $rec (@records) {
 4053:                 my %temp = &Apache::loncommon::record_sep($rec);
 4054:                 if (%temp) {
 4055:                     $keyfields=join(',',sort(keys(%temp)));
 4056:                     last;
 4057:                 }
 4058:             }
 4059: 	}
 4060:     }
 4061:     &csvuploadmap_footer($request,$i,$keyfields);
 4062:     $request->print(&show_grading_menu_form($symb));
 4063: 
 4064:     return '';
 4065: }
 4066: 
 4067: sub csvuploadoptions {
 4068:     my ($request)= @_;
 4069:     my ($symb)=&get_symb($request);
 4070:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4071:     my $ignore=&mt('Ignore First Line');
 4072:     $request->print(<<ENDPICK);
 4073: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4074: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4075: <input type="hidden" name="command"    value="csvuploadassign" />
 4076: <!--
 4077: <p>
 4078: <label>
 4079:    <input type="checkbox" name="show_full_results" />
 4080:    Show a table of all changes
 4081: </label>
 4082: </p>
 4083: -->
 4084: <p>
 4085: <label>
 4086:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4087:    Overwrite any existing score
 4088: </label>
 4089: </p>
 4090: ENDPICK
 4091:     my %fields=&get_fields();
 4092:     if (!defined($fields{'domain'})) {
 4093: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4094: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4095:     }
 4096:     foreach my $key (sort(keys(%env))) {
 4097: 	if ($key !~ /^form\.(.*)$/) { next; }
 4098: 	my $cleankey=$1;
 4099: 	if ($cleankey eq 'command') { next; }
 4100: 	$request->print('<input type="hidden" name="'.$cleankey.
 4101: 			'"  value="'.$env{$key}.'" />'."\n");
 4102:     }
 4103:     # FIXME do a check for any duplicated user ids...
 4104:     # FIXME do a check for any invalid user ids?...
 4105:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4106: <hr /></form>'."\n");
 4107:     $request->print(&show_grading_menu_form($symb));
 4108:     return '';
 4109: }
 4110: 
 4111: sub get_fields {
 4112:     my %fields;
 4113:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4114:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4115: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4116: 	    if ($env{'form.f'.$i} ne 'none') {
 4117: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4118: 	    }
 4119: 	} else {
 4120: 	    if ($env{'form.f'.$i} ne 'none') {
 4121: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4122: 	    }
 4123: 	}
 4124:     }
 4125:     return %fields;
 4126: }
 4127: 
 4128: sub csvuploadassign {
 4129:     my ($request)= @_;
 4130:     my ($symb)=&get_symb($request);
 4131:     if (!$symb) {return '';}
 4132:     my $error_msg = '';
 4133:     &Apache::loncommon::load_tmp_file($request);
 4134:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4135:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4136:     my %fields=&get_fields();
 4137:     $request->print('<h3>Assigning Grades</h3>');
 4138:     my $courseid=$env{'request.course.id'};
 4139:     my ($classlist) = &getclasslist('all',0);
 4140:     my @notallowed;
 4141:     my @skipped;
 4142:     my $countdone=0;
 4143:     foreach my $grade (@gradedata) {
 4144: 	my %entries=&Apache::loncommon::record_sep($grade);
 4145: 	my $domain;
 4146: 	if ($entries{$fields{'domain'}}) {
 4147: 	    $domain=$entries{$fields{'domain'}};
 4148: 	} else {
 4149: 	    $domain=$env{'form.default_domain'};
 4150: 	}
 4151: 	$domain=~s/\s//g;
 4152: 	my $username=$entries{$fields{'username'}};
 4153: 	$username=~s/\s//g;
 4154: 	if (!$username) {
 4155: 	    my $id=$entries{$fields{'ID'}};
 4156: 	    $id=~s/\s//g;
 4157: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4158: 	    $username=$ids{$id};
 4159: 	}
 4160: 	if (!exists($$classlist{"$username:$domain"})) {
 4161: 	    my $id=$entries{$fields{'ID'}};
 4162: 	    $id=~s/\s//g;
 4163: 	    if ($id) {
 4164: 		push(@skipped,"$id:$domain");
 4165: 	    } else {
 4166: 		push(@skipped,"$username:$domain");
 4167: 	    }
 4168: 	    next;
 4169: 	}
 4170: 	my $usec=$classlist->{"$username:$domain"}[5];
 4171: 	if (!&canmodify($usec)) {
 4172: 	    push(@notallowed,"$username:$domain");
 4173: 	    next;
 4174: 	}
 4175: 	my %points;
 4176: 	my %grades;
 4177: 	foreach my $dest (keys(%fields)) {
 4178: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4179: 		$dest eq 'domain') { next; }
 4180: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4181: 	    if ($dest=~/stores_(.*)_points/) {
 4182: 		my $part=$1;
 4183: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4184: 					      $symb,$domain,$username);
 4185:                 if ($wgt) {
 4186:                     $entries{$fields{$dest}}=~s/\s//g;
 4187:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4188:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4189:                                           : 'correct_by_override';
 4190:                     $grades{"resource.$part.awarded"}=$pcr;
 4191:                     $grades{"resource.$part.solved"}=$award;
 4192:                     $points{$part}=1;
 4193:                 } else {
 4194:                     $error_msg = "<br />" .
 4195:                         &mt("Some point values were assigned"
 4196:                             ." for problems with a weight "
 4197:                             ."of zero. These values were "
 4198:                             ."ignored.");
 4199:                 }
 4200: 	    } else {
 4201: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4202: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4203: 		my $store_key=$dest;
 4204: 		$store_key=~s/^stores/resource/;
 4205: 		$store_key=~s/_/\./g;
 4206: 		$grades{$store_key}=$entries{$fields{$dest}};
 4207: 	    }
 4208: 	}
 4209: 	if (! %grades) { 
 4210:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4211:         } else {
 4212: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4213: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4214: 					   $env{'request.course.id'},
 4215: 					   $domain,$username);
 4216: 	   if ($result eq 'ok') {
 4217: 	      $request->print('.');
 4218: 	   } else {
 4219: 	      $request->print("<p><span class=\"LC_error\">".
 4220:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4221:                                   "$username:$domain",$result)."</span></p>");
 4222: 	   }
 4223: 	   $request->rflush();
 4224: 	   $countdone++;
 4225:         }
 4226:     }
 4227:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4228:     if (@skipped) {
 4229: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4230:         $request->print(join(', ',@skipped));
 4231:     }
 4232:     if (@notallowed) {
 4233: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4234: 	$request->print(join(', ',@notallowed));
 4235:     }
 4236:     $request->print("<br />\n");
 4237:     $request->print(&show_grading_menu_form($symb));
 4238:     return $error_msg;
 4239: }
 4240: #------------- end of section for handling csv file upload ---------
 4241: #
 4242: #-------------------------------------------------------------------
 4243: #
 4244: #-------------- Next few routines handle grading by page/sequence
 4245: #
 4246: #--- Select a page/sequence and a student to grade
 4247: sub pickStudentPage {
 4248:     my ($request) = shift;
 4249: 
 4250:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4251:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4252: 
 4253: function checkPickOne(formname) {
 4254:     if (radioSelection(formname.student) == null) {
 4255: 	alert("$alertmsg");
 4256: 	return;
 4257:     }
 4258:     ptr = pullDownSelection(formname.selectpage);
 4259:     formname.page.value = formname["page"+ptr].value;
 4260:     formname.title.value = formname["title"+ptr].value;
 4261:     formname.submit();
 4262: }
 4263: 
 4264: LISTJAVASCRIPT
 4265:     &commonJSfunctions($request);
 4266:     my ($symb) = &get_symb($request);
 4267:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4268:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4269:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4270: 
 4271:     my $result='<h3><span class="LC_info">&nbsp;'.
 4272: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4273: 
 4274:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4275:     my $map_error;
 4276:     my ($titles,$symbx) = &getSymbMap($map_error);
 4277:     if ($map_error) {
 4278:         $request->print(&navmap_errormsg());
 4279:         return; 
 4280:     }
 4281:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4282: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4283: #    my $type=($curpage =~ /\.(page|sequence)/);
 4284:     my $select = '<select name="selectpage">'."\n";
 4285:     my $ctr=0;
 4286:     foreach (@$titles) {
 4287: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4288: 	$select.='<option value="'.$ctr.'" '.
 4289: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4290: 	    '>'.$showtitle.'</option>'."\n";
 4291: 	$ctr++;
 4292:     }
 4293:     $select.= '</select>';
 4294:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4295: 
 4296:     $ctr=0;
 4297:     foreach (@$titles) {
 4298: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4299: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4300: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4301: 	$ctr++;
 4302:     }
 4303:     $result.='<input type="hidden" name="page" />'."\n".
 4304: 	'<input type="hidden" name="title" />'."\n";
 4305: 
 4306:     my $options =
 4307: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4308: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4309:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4310: 
 4311:     $options =
 4312: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4313: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4314: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4315:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4316:     
 4317:     $result.=&build_section_inputs();
 4318:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4319:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4320: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4321: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4322: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4323: 
 4324:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4325: 
 4326:     $result.='&nbsp;<input type="button" '.
 4327:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4328: 
 4329:     $request->print($result);
 4330: 
 4331:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4332: 	&Apache::loncommon::start_data_table().
 4333: 	&Apache::loncommon::start_data_table_header_row().
 4334: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4335: 	'<th>'.&nameUserString('header').'</th>'.
 4336: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4337: 	'<th>'.&nameUserString('header').'</th>'.
 4338: 	&Apache::loncommon::end_data_table_header_row();
 4339:  
 4340:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4341:     my $ptr = 1;
 4342:     foreach my $student (sort 
 4343: 			 {
 4344: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4345: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4346: 			     }
 4347: 			     return $a cmp $b;
 4348: 			 } (keys(%$fullname))) {
 4349: 	my ($uname,$udom) = split(/:/,$student);
 4350: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4351:                                   : '</td>');
 4352: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4353: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4354: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4355: 	$studentTable.=
 4356: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4357:                          : '');
 4358: 	$ptr++;
 4359:     }
 4360:     if ($ptr%2 == 0) {
 4361: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4362: 	    &Apache::loncommon::end_data_table_row();
 4363:     }
 4364:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4365:     $studentTable.='<input type="button" '.
 4366:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4367: 
 4368:     $studentTable.=&show_grading_menu_form($symb);
 4369:     $request->print($studentTable);
 4370: 
 4371:     return '';
 4372: }
 4373: 
 4374: sub getSymbMap {
 4375:     my ($map_error) = @_;
 4376:     my $navmap = Apache::lonnavmaps::navmap->new();
 4377:     unless (ref($navmap)) {
 4378:         if (ref($map_error)) {
 4379:             $$map_error = 'navmap';
 4380:         }
 4381:         return;
 4382:     }
 4383:     my %symbx = ();
 4384:     my @titles = ();
 4385:     my $minder = 0;
 4386: 
 4387:     # Gather every sequence that has problems.
 4388:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4389: 					       1,0,1);
 4390:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4391: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4392: 	    my $title = $minder.'.'.
 4393: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4394: 	    push(@titles, $title); # minder in case two titles are identical
 4395: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4396: 	    $minder++;
 4397: 	}
 4398:     }
 4399:     return \@titles,\%symbx;
 4400: }
 4401: 
 4402: #
 4403: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4404: sub displayPage {
 4405:     my ($request) = shift;
 4406: 
 4407:     my ($symb) = &get_symb($request);
 4408:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4409:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4410:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4411:     my $pageTitle = $env{'form.page'};
 4412:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4413:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4414:     my $usec=$classlist->{$env{'form.student'}}[5];
 4415: 
 4416:     #need to make sure we have the correct data for later EXT calls, 
 4417:     #thus invalidate the cache
 4418:     &Apache::lonnet::devalidatecourseresdata(
 4419:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4420:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4421:     &Apache::lonnet::clear_EXT_cache_status();
 4422: 
 4423:     if (!&canview($usec)) {
 4424: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4425: 	$request->print(&show_grading_menu_form($symb));
 4426: 	return;
 4427:     }
 4428:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4429:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4430: 	'</h3>'."\n";
 4431:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4432:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4433: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4434:     } else {
 4435: 	delete($env{'form.CODE'});
 4436:     }
 4437:     &sub_page_js($request);
 4438:     $request->print($result);
 4439: 
 4440:     my $navmap = Apache::lonnavmaps::navmap->new();
 4441:     unless (ref($navmap)) {
 4442:         $request->print(&navmap_errormsg());
 4443:         $request->print(&show_grading_menu_form($symb));
 4444:         return;
 4445:     }
 4446:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4447:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4448:     if (!$map) {
 4449: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4450: 	$request->print(&show_grading_menu_form($symb));
 4451: 	return; 
 4452:     }
 4453:     my $iterator = $navmap->getIterator($map->map_start(),
 4454: 					$map->map_finish());
 4455: 
 4456:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4457: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4458: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4459: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4460: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4461: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4462: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4463: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4464: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4465: 
 4466:     if (defined($env{'form.CODE'})) {
 4467: 	$studentTable.=
 4468: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4469:     }
 4470:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4471: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4472: 
 4473:     $studentTable.='&nbsp;<span class="LC_info">'.
 4474:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4475:         '</span>'."\n".
 4476: 	&Apache::loncommon::start_data_table().
 4477: 	&Apache::loncommon::start_data_table_header_row().
 4478: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4479: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4480: 	&Apache::loncommon::end_data_table_header_row();
 4481: 
 4482:     &Apache::lonxml::clear_problem_counter();
 4483:     my ($depth,$question,$prob) = (1,1,1);
 4484:     $iterator->next(); # skip the first BEGIN_MAP
 4485:     my $curRes = $iterator->next(); # for "current resource"
 4486:     while ($depth > 0) {
 4487:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4488:         if($curRes == $iterator->END_MAP) { $depth--; }
 4489: 
 4490:         if (ref($curRes) && $curRes->is_problem()) {
 4491: 	    my $parts = $curRes->parts();
 4492:             my $title = $curRes->compTitle();
 4493: 	    my $symbx = $curRes->symb();
 4494: 	    $studentTable.=
 4495: 		&Apache::loncommon::start_data_table_row().
 4496: 		'<td align="center" valign="top" >'.$prob.
 4497: 		(scalar(@{$parts}) == 1 ? '' 
 4498: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4499: 							scalar(@{$parts}))
 4500: 		 ).
 4501: 		 '</td>';
 4502: 	    $studentTable.='<td valign="top">';
 4503: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4504: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4505: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4506: 					     undef,'both',\%form);
 4507: 	    } else {
 4508: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4509: 		$companswer =~ s|<form(.*?)>||g;
 4510: 		$companswer =~ s|</form>||g;
 4511: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4512: #		    $companswer =~ s/$1/ /ms;
 4513: #		    $request->print('match='.$1."<br />\n");
 4514: #		}
 4515: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4516: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4517: 	    }
 4518: 
 4519: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4520: 
 4521: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4522: 		if ($record{'version'} eq '') {
 4523: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4524: 		} else {
 4525: 		    my %responseType = ();
 4526: 		    foreach my $partid (@{$parts}) {
 4527: 			my @responseIds =$curRes->responseIds($partid);
 4528: 			my @responseType =$curRes->responseType($partid);
 4529: 			my %responseIds;
 4530: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4531: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4532: 			}
 4533: 			$responseType{$partid} = \%responseIds;
 4534: 		    }
 4535: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4536: 
 4537: 		}
 4538: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4539: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4540: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4541: 									$env{'request.course.id'},
 4542: 									'','.submission');
 4543:  
 4544: 	    }
 4545: 	    if (&canmodify($usec)) {
 4546:             $studentTable.=&gradeBox_start();
 4547: 		foreach my $partid (@{$parts}) {
 4548: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4549: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4550: 		    $question++;
 4551: 		}
 4552:             $studentTable.=&gradeBox_end();
 4553: 		$prob++;
 4554: 	    }
 4555: 	    $studentTable.='</td></tr>';
 4556: 
 4557: 	}
 4558:         $curRes = $iterator->next();
 4559:     }
 4560: 
 4561:     $studentTable.=
 4562:         '</table>'."\n".
 4563:         '<input type="button" value="'.&mt('Save').'" '.
 4564:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4565:         '</form>'."\n";
 4566:     $studentTable.=&show_grading_menu_form($symb);
 4567:     $request->print($studentTable);
 4568: 
 4569:     return '';
 4570: }
 4571: 
 4572: sub displaySubByDates {
 4573:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4574:     my $isCODE=0;
 4575:     my $isTask = ($symb =~/\.task$/);
 4576:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4577:     my $studentTable=&Apache::loncommon::start_data_table().
 4578: 	&Apache::loncommon::start_data_table_header_row().
 4579: 	'<th>'.&mt('Date/Time').'</th>'.
 4580: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4581: 	'<th>'.&mt('Submission').'</th>'.
 4582: 	'<th>'.&mt('Status').'</th>'.
 4583: 	&Apache::loncommon::end_data_table_header_row();
 4584:     my ($version);
 4585:     my %mark;
 4586:     my %orders;
 4587:     $mark{'correct_by_student'} = $checkIcon;
 4588:     if (!exists($$record{'1:timestamp'})) {
 4589: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4590:     }
 4591: 
 4592:     my $interaction;
 4593:     my $no_increment = 1;
 4594:     for ($version=1;$version<=$$record{'version'};$version++) {
 4595: 	my $timestamp = 
 4596: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4597: 	if (exists($$record{$version.':resource.0.version'})) {
 4598: 	    $interaction = $$record{$version.':resource.0.version'};
 4599: 	}
 4600: 
 4601: 	my $where = ($isTask ? "$version:resource.$interaction"
 4602: 		             : "$version:resource");
 4603: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4604: 	    '<td>'.$timestamp.'</td>';
 4605: 	if ($isCODE) {
 4606: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4607: 	}
 4608: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4609: 	my @displaySub = ();
 4610: 	foreach my $partid (@{$parts}) {
 4611:             my $hidden;
 4612:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4613:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4614:                 $hidden = 1;
 4615:             }
 4616: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4617: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4618: 	    
 4619: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4620: 	    my $display_part=&get_display_part($partid,$symb);
 4621: 	    foreach my $matchKey (@matchKey) {
 4622: 		if (exists($$record{$version.':'.$matchKey}) &&
 4623: 		    $$record{$version.':'.$matchKey} ne '') {
 4624:                     
 4625: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4626: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4627:                     $displaySub[0].='<span class="LC_nobreak"';
 4628:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4629:                                    .' <span class="LC_internal_info">'
 4630:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4631:                                    .'</span>'
 4632:                                    .' <b>';
 4633:                     if ($hidden) {
 4634:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4635:                     } else {
 4636: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4637: 			    $displaySub[0].=&mt('Trial not counted');
 4638: 		        } else {
 4639: 			    $displaySub[0].=&mt('Trial: [_1]',
 4640: 					    $$record{"$where.$partid.tries"});
 4641: 		        }
 4642: 		        my $responseType=($isTask ? 'Task'
 4643:                                               : $responseType->{$partid}->{$responseId});
 4644: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4645: 		        if (!exists($orders{$partid}->{$responseId})) {
 4646: 			    $orders{$partid}->{$responseId}=
 4647: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4648:                                            $no_increment);
 4649: 		        }
 4650: 		        $displaySub[0].='</b></span>'; # /nobreak
 4651: 		        $displaySub[0].='&nbsp; '.
 4652: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4653:                     }
 4654: 		}
 4655: 	    }
 4656: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4657: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4658: 				    $$record{"$where.$partid.checkedin"},
 4659: 				    $$record{"$where.$partid.checkedin.slot"}).
 4660: 					'<br />';
 4661: 	    }
 4662: 	    if (exists $$record{"$where.$partid.award"}) {
 4663: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4664: 		    lc($$record{"$where.$partid.award"}).' '.
 4665: 		    $mark{$$record{"$where.$partid.solved"}}.
 4666: 		    '<br />';
 4667: 	    }
 4668: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4669: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4670: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4671: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4672: 		$displaySub[2].=
 4673: 		    $$record{"$version:resource.$partid.regrader"}.
 4674: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4675: 	    }
 4676: 	}
 4677: 	# needed because old essay regrader has not parts info
 4678: 	if (exists $$record{"$version:resource.regrader"}) {
 4679: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4680: 	}
 4681: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4682: 	if ($displaySub[2]) {
 4683: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4684: 	}
 4685: 	$studentTable.='&nbsp;</td>'.
 4686: 	    &Apache::loncommon::end_data_table_row();
 4687:     }
 4688:     $studentTable.=&Apache::loncommon::end_data_table();
 4689:     return $studentTable;
 4690: }
 4691: 
 4692: sub updateGradeByPage {
 4693:     my ($request) = shift;
 4694: 
 4695:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4696:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4697:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4698:     my $pageTitle = $env{'form.page'};
 4699:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4700:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4701:     my $usec=$classlist->{$env{'form.student'}}[5];
 4702:     if (!&canmodify($usec)) {
 4703: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4704: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4705: 	return;
 4706:     }
 4707:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4708:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4709: 	'</h3>'."\n";
 4710: 
 4711:     $request->print($result);
 4712: 
 4713: 
 4714:     my $navmap = Apache::lonnavmaps::navmap->new();
 4715:     unless (ref($navmap)) {
 4716:         $request->print(&navmap_errormsg());
 4717:         return;
 4718:     }
 4719:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4720:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4721:     if (!$map) {
 4722: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4723: 	my ($symb)=&get_symb($request);
 4724: 	$request->print(&show_grading_menu_form($symb));
 4725: 	return; 
 4726:     }
 4727:     my $iterator = $navmap->getIterator($map->map_start(),
 4728: 					$map->map_finish());
 4729: 
 4730:     my $studentTable=
 4731: 	&Apache::loncommon::start_data_table().
 4732: 	&Apache::loncommon::start_data_table_header_row().
 4733: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4734: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4735: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4736: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4737: 	&Apache::loncommon::end_data_table_header_row();
 4738: 
 4739:     $iterator->next(); # skip the first BEGIN_MAP
 4740:     my $curRes = $iterator->next(); # for "current resource"
 4741:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4742:     while ($depth > 0) {
 4743:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4744:         if($curRes == $iterator->END_MAP) { $depth--; }
 4745: 
 4746:         if (ref($curRes) && $curRes->is_problem()) {
 4747: 	    my $parts = $curRes->parts();
 4748:             my $title = $curRes->compTitle();
 4749: 	    my $symbx = $curRes->symb();
 4750: 	    $studentTable.=
 4751: 		&Apache::loncommon::start_data_table_row().
 4752: 		'<td align="center" valign="top" >'.$prob.
 4753: 		(scalar(@{$parts}) == 1 ? '' 
 4754:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4755: 		.')').'</td>';
 4756: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4757: 
 4758: 	    my %newrecord=();
 4759: 	    my @displayPts=();
 4760:             my %aggregate = ();
 4761:             my $aggregateflag = 0;
 4762: 	    foreach my $partid (@{$parts}) {
 4763: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4764: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4765: 
 4766: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4767: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4768: 		my $partial = $newpts/$wgt;
 4769: 		my $score;
 4770: 		if ($partial > 0) {
 4771: 		    $score = 'correct_by_override';
 4772: 		} elsif ($newpts ne '') { #empty is taken as 0
 4773: 		    $score = 'incorrect_by_override';
 4774: 		}
 4775: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4776: 		if ($dropMenu eq 'excused') {
 4777: 		    $partial = '';
 4778: 		    $score = 'excused';
 4779: 		} elsif ($dropMenu eq 'reset status'
 4780: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4781: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4782: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4783: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4784: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4785: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4786: 		    $changeflag++;
 4787: 		    $newpts = '';
 4788:                     
 4789:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4790:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4791:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4792:                     if ($aggtries > 0) {
 4793:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4794:                         $aggregateflag = 1;
 4795:                     }
 4796: 		}
 4797: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4798: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4799: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4800: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4801: 		    '&nbsp;<br />';
 4802: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4803: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4804: 		    '&nbsp;<br />';
 4805: 		$question++;
 4806: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4807: 
 4808: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4809: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4810: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4811: 		    if (scalar(keys(%newrecord)) > 0);
 4812: 
 4813: 		$changeflag++;
 4814: 	    }
 4815: 	    if (scalar(keys(%newrecord)) > 0) {
 4816: 		my %record = 
 4817: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4818: 					     $udom,$uname);
 4819: 
 4820: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4821: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4822: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4823: 		    $newrecord{'resource.CODE'} = '';
 4824: 		}
 4825: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4826: 					$udom,$uname);
 4827: 		%record = &Apache::lonnet::restore($symbx,
 4828: 						   $env{'request.course.id'},
 4829: 						   $udom,$uname);
 4830: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4831: 					     $cdom,$cnum,$udom,$uname);
 4832: 	    }
 4833: 	    
 4834:             if ($aggregateflag) {
 4835:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4836:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4837:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4838:             }
 4839: 
 4840: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4841: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4842: 		&Apache::loncommon::end_data_table_row();
 4843: 
 4844: 	    $prob++;
 4845: 	}
 4846:         $curRes = $iterator->next();
 4847:     }
 4848: 
 4849:     $studentTable.=&Apache::loncommon::end_data_table();
 4850:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4851:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4852: 		  &mt('The scores were changed for [quant,_1,problem].',
 4853: 		  $changeflag));
 4854:     $request->print($grademsg.$studentTable);
 4855: 
 4856:     return '';
 4857: }
 4858: 
 4859: #-------- end of section for handling grading by page/sequence ---------
 4860: #
 4861: #-------------------------------------------------------------------
 4862: 
 4863: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4864: #
 4865: #------ start of section for handling grading by page/sequence ---------
 4866: 
 4867: =pod
 4868: 
 4869: =head1 Bubble sheet grading routines
 4870: 
 4871:   For this documentation:
 4872: 
 4873:    'scanline' refers to the full line of characters
 4874:    from the file that we are parsing that represents one entire sheet
 4875: 
 4876:    'bubble line' refers to the data
 4877:    representing the line of bubbles that are on the physical bubble sheet
 4878: 
 4879: 
 4880: The overall process is that a scanned in bubble sheet data is uploaded
 4881: into a course. When a user wants to grade, they select a
 4882: sequence/folder of resources, a file of bubble sheet info, and pick
 4883: one of the predefined configurations for what each scanline looks
 4884: like.
 4885: 
 4886: Next each scanline is checked for any errors of either 'missing
 4887: bubbles' (it's an error because it may have been mis-scanned
 4888: because too light bubbling), 'double bubble' (each bubble line should
 4889: have no more that one letter picked), invalid or duplicated CODE,
 4890: invalid student/employee ID
 4891: 
 4892: If the CODE option is used that determines the randomization of the
 4893: homework problems, either way the student/employee ID is looked up into a
 4894: username:domain.
 4895: 
 4896: During the validation phase the instructor can choose to skip scanlines. 
 4897: 
 4898: After the validation phase, there are now 3 bubble sheet files
 4899: 
 4900:   scantron_original_filename (unmodified original file)
 4901:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4902:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4903: 
 4904: Also there is a separate hash nohist_scantrondata that contains extra
 4905: correction information that isn't representable in the bubble sheet
 4906: file (see &scantron_getfile() for more information)
 4907: 
 4908: After all scanlines are either valid, marked as valid or skipped, then
 4909: foreach line foreach problem in the picked sequence, an ssi request is
 4910: made that simulates a user submitting their selected letter(s) against
 4911: the homework problem.
 4912: 
 4913: =over 4
 4914: 
 4915: 
 4916: 
 4917: =item defaultFormData
 4918: 
 4919:   Returns html hidden inputs used to hold context/default values.
 4920: 
 4921:  Arguments:
 4922:   $symb - $symb of the current resource 
 4923: 
 4924: =cut
 4925: 
 4926: sub defaultFormData {
 4927:     my ($symb)=@_;
 4928:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4929:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4930:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4931: }
 4932: 
 4933: 
 4934: =pod 
 4935: 
 4936: =item getSequenceDropDown
 4937: 
 4938:    Return html dropdown of possible sequences to grade
 4939:  
 4940:  Arguments:
 4941:    $symb - $symb of the current resource
 4942:    $map_error - ref to scalar which will container error if
 4943:                 $navmap object is unavailable in &getSymbMap().
 4944: 
 4945: =cut
 4946: 
 4947: sub getSequenceDropDown {
 4948:     my ($symb,$map_error)=@_;
 4949:     my $result='<select name="selectpage">'."\n";
 4950:     my ($titles,$symbx) = &getSymbMap($map_error);
 4951:     if (ref($map_error)) {
 4952:         return if ($$map_error);
 4953:     }
 4954:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4955:     my $ctr=0;
 4956:     foreach (@$titles) {
 4957: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4958: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4959: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4960: 	    '>'.$showtitle.'</option>'."\n";
 4961: 	$ctr++;
 4962:     }
 4963:     $result.= '</select>';
 4964:     return $result;
 4965: }
 4966: 
 4967: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4968:                                    # key is zero-based index - 0, 1, 2 ...
 4969: 
 4970: my %first_bubble_line;             # First bubble line no. for each bubble.
 4971: 
 4972: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4973:                                    # matchresponse or rankresponse, where 
 4974:                                    # an individual response can have multiple 
 4975:                                    # lines
 4976: 
 4977: my %responsetype_per_response;     # responsetype for each response
 4978: 
 4979: # Save and restore the bubble lines array to the form env.
 4980: 
 4981: 
 4982: sub save_bubble_lines {
 4983:     foreach my $line (keys(%bubble_lines_per_response)) {
 4984: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4985: 	$env{"form.scantron.first_bubble_line.$line"} =
 4986: 	    $first_bubble_line{$line};
 4987:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4988:             $subdivided_bubble_lines{$line};
 4989:         $env{"form.scantron.responsetype.$line"} =
 4990:             $responsetype_per_response{$line};
 4991:     }
 4992: }
 4993: 
 4994: 
 4995: sub restore_bubble_lines {
 4996:     my $line = 0;
 4997:     %bubble_lines_per_response = ();
 4998:     while ($env{"form.scantron.bubblelines.$line"}) {
 4999: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5000: 	$bubble_lines_per_response{$line} = $value;
 5001: 	$first_bubble_line{$line}  =
 5002: 	    $env{"form.scantron.first_bubble_line.$line"};
 5003:         $subdivided_bubble_lines{$line} =
 5004:             $env{"form.scantron.sub_bubblelines.$line"};
 5005:         $responsetype_per_response{$line} =
 5006:             $env{"form.scantron.responsetype.$line"};
 5007: 	$line++;
 5008:     }
 5009: }
 5010: 
 5011: #  Given the parsed scanline, get the response for 
 5012: #  'answer' number n:
 5013: 
 5014: sub get_response_bubbles {
 5015:     my ($parsed_line, $response)  = @_;
 5016: 
 5017:     my $bubble_line = $first_bubble_line{$response-1} +1;
 5018:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 5019:     
 5020:     my $selected = "";
 5021: 
 5022:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 5023: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 5024: 	$bubble_line++;
 5025:     }
 5026:     return $selected;
 5027: }
 5028: 
 5029: =pod 
 5030: 
 5031: =item scantron_filenames
 5032: 
 5033:    Returns a list of the scantron files in the current course 
 5034: 
 5035: =cut
 5036: 
 5037: sub scantron_filenames {
 5038:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5039:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5040:     my $getpropath = 1;
 5041:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 5042:                                        $getpropath);
 5043:     my @possiblenames;
 5044:     foreach my $filename (sort(@files)) {
 5045: 	($filename)=split(/&/,$filename);
 5046: 	if ($filename!~/^scantron_orig_/) { next ; }
 5047: 	$filename=~s/^scantron_orig_//;
 5048: 	push(@possiblenames,$filename);
 5049:     }
 5050:     return @possiblenames;
 5051: }
 5052: 
 5053: =pod 
 5054: 
 5055: =item scantron_uploads
 5056: 
 5057:    Returns  html drop-down list of scantron files in current course.
 5058: 
 5059:  Arguments:
 5060:    $file2grade - filename to set as selected in the dropdown
 5061: 
 5062: =cut
 5063: 
 5064: sub scantron_uploads {
 5065:     my ($file2grade) = @_;
 5066:     my $result=	'<select name="scantron_selectfile">';
 5067:     $result.="<option></option>";
 5068:     foreach my $filename (sort(&scantron_filenames())) {
 5069: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5070:     }
 5071:     $result.="</select>";
 5072:     return $result;
 5073: }
 5074: 
 5075: =pod 
 5076: 
 5077: =item scantron_scantab
 5078: 
 5079:   Returns html drop down of the scantron formats in the scantronformat.tab
 5080:   file.
 5081: 
 5082: =cut
 5083: 
 5084: sub scantron_scantab {
 5085:     my $result='<select name="scantron_format">'."\n";
 5086:     $result.='<option></option>'."\n";
 5087:     my @lines = &get_scantronformat_file();
 5088:     if (@lines > 0) {
 5089:         foreach my $line (@lines) {
 5090:             next if (($line =~ /^\#/) || ($line eq ''));
 5091: 	    my ($name,$descrip)=split(/:/,$line);
 5092: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5093:         }
 5094:     }
 5095:     $result.='</select>'."\n";
 5096:     return $result;
 5097: }
 5098: 
 5099: =pod
 5100: 
 5101: =item get_scantronformat_file
 5102: 
 5103:   Returns an array containing lines from the scantron format file for
 5104:   the domain of the course.
 5105: 
 5106:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5107:   lines are from this file.
 5108: 
 5109:   Otherwise, if a default.tab has been published in RES space by the 
 5110:   domainconfig user, lines are from this file.
 5111: 
 5112:   Otherwise, fall back to getting lines from the legacy file on the
 5113:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5114: 
 5115: =cut
 5116: 
 5117: sub get_scantronformat_file {
 5118:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5119:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5120:     my $gottab = 0;
 5121:     my @lines;
 5122:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5123:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5124:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5125:             if ($formatfile ne '-1') {
 5126:                 @lines = split("\n",$formatfile,-1);
 5127:                 $gottab = 1;
 5128:             }
 5129:         }
 5130:     }
 5131:     if (!$gottab) {
 5132:         my $confname = $cdom.'-domainconfig';
 5133:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5134:         my $formatfile =  &Apache::lonnet::getfile($default);
 5135:         if ($formatfile ne '-1') {
 5136:             @lines = split("\n",$formatfile,-1);
 5137:             $gottab = 1;
 5138:         }
 5139:     }
 5140:     if (!$gottab) {
 5141:         my @domains = &Apache::lonnet::current_machine_domains();
 5142:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5143:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5144:             @lines = <$fh>;
 5145:             close($fh);
 5146:         } else {
 5147:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5148:             @lines = <$fh>;
 5149:             close($fh);
 5150:         }
 5151:     }
 5152:     return @lines;
 5153: }
 5154: 
 5155: =pod 
 5156: 
 5157: =item scantron_CODElist
 5158: 
 5159:   Returns html drop down of the saved CODE lists from current course,
 5160:   generated from earlier printings.
 5161: 
 5162: =cut
 5163: 
 5164: sub scantron_CODElist {
 5165:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5166:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5167:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5168:     my $namechoice='<option></option>';
 5169:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5170: 	if ($name =~ /^error: 2 /) { next; }
 5171: 	if ($name =~ /^type\0/) { next; }
 5172: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5173:     }
 5174:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5175:     return $namechoice;
 5176: }
 5177: 
 5178: =pod 
 5179: 
 5180: =item scantron_CODEunique
 5181: 
 5182:   Returns the html for "Each CODE to be used once" radio.
 5183: 
 5184: =cut
 5185: 
 5186: sub scantron_CODEunique {
 5187:     my $result='<span class="LC_nobreak">
 5188:                  <label><input type="radio" name="scantron_CODEunique"
 5189:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5190:                 </span>
 5191:                 <span class="LC_nobreak">
 5192:                  <label><input type="radio" name="scantron_CODEunique"
 5193:                         value="no" />'.&mt('No').' </label>
 5194:                 </span>';
 5195:     return $result;
 5196: }
 5197: 
 5198: =pod 
 5199: 
 5200: =item scantron_selectphase
 5201: 
 5202:   Generates the initial screen to start the bubble sheet process.
 5203:   Allows for - starting a grading run.
 5204:              - downloading existing scan data (original, corrected
 5205:                                                 or skipped info)
 5206: 
 5207:              - uploading new scan data
 5208: 
 5209:  Arguments:
 5210:   $r          - The Apache request object
 5211:   $file2grade - name of the file that contain the scanned data to score
 5212: 
 5213: =cut
 5214: 
 5215: sub scantron_selectphase {
 5216:     my ($r,$file2grade) = @_;
 5217:     my ($symb)=&get_symb($r);
 5218:     if (!$symb) {return '';}
 5219:     my $map_error;
 5220:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5221:     if ($map_error) {
 5222:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5223:         return;
 5224:     }
 5225:     my $default_form_data=&defaultFormData($symb);
 5226:     my $grading_menu_button=&show_grading_menu_form($symb);
 5227:     my $file_selector=&scantron_uploads($file2grade);
 5228:     my $format_selector=&scantron_scantab();
 5229:     my $CODE_selector=&scantron_CODElist();
 5230:     my $CODE_unique=&scantron_CODEunique();
 5231:     my $result;
 5232: 
 5233:     $ssi_error = 0;
 5234: 
 5235:     # Chunk of form to prompt for a file to grade and how:
 5236: 
 5237:     $result.= '
 5238:     <br />
 5239:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5240:     <input type="hidden" name="command" value="scantron_warning" />
 5241:     '.$default_form_data.'
 5242:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5243:        '.&Apache::loncommon::start_data_table_header_row().'
 5244:             <th colspan="2">
 5245:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5246:             </th>
 5247:        '.&Apache::loncommon::end_data_table_header_row().'
 5248:        '.&Apache::loncommon::start_data_table_row().'
 5249:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5250:        '.&Apache::loncommon::end_data_table_row().'
 5251:        '.&Apache::loncommon::start_data_table_row().'
 5252:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5253:        '.&Apache::loncommon::end_data_table_row().'
 5254:        '.&Apache::loncommon::start_data_table_row().'
 5255:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5256:        '.&Apache::loncommon::end_data_table_row().'
 5257:        '.&Apache::loncommon::start_data_table_row().'
 5258:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5259:        '.&Apache::loncommon::end_data_table_row().'
 5260:        '.&Apache::loncommon::start_data_table_row().'
 5261:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5262:        '.&Apache::loncommon::end_data_table_row().'
 5263:        '.&Apache::loncommon::start_data_table_row().'
 5264: 	    <td> '.&mt('Options:').' </td>
 5265:             <td>
 5266: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5267:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5268:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5269: 	    </td>
 5270:        '.&Apache::loncommon::end_data_table_row().'
 5271:        '.&Apache::loncommon::start_data_table_row().'
 5272:             <td colspan="2">
 5273:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5274:             </td>
 5275:        '.&Apache::loncommon::end_data_table_row().'
 5276:     '.&Apache::loncommon::end_data_table().'
 5277:     </form>
 5278: ';
 5279:    
 5280:     $r->print($result);
 5281: 
 5282:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5283:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5284: 
 5285: 	# Chunk of form to prompt for a scantron file upload.
 5286: 
 5287:         $r->print('
 5288:     <br />
 5289:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5290:        '.&Apache::loncommon::start_data_table_header_row().'
 5291:             <th>
 5292:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5293:             </th>
 5294:        '.&Apache::loncommon::end_data_table_header_row().'
 5295:        '.&Apache::loncommon::start_data_table_row().'
 5296:             <td>
 5297: ');
 5298:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5299:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5300:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5301:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5302:     function checkUpload(formname) {
 5303: 	if (formname.upfile.value == "") {
 5304: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5305: 	    return false;
 5306: 	}
 5307: 	formname.submit();
 5308:     }'));
 5309:     $r->print('
 5310:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5311:                 '.$default_form_data.'
 5312:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5313:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5314:                 <input name="command" value="scantronupload_save" type="hidden" />
 5315:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5316:                 <br />
 5317:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5318:               </form>
 5319: ');
 5320: 
 5321:         $r->print('
 5322:             </td>
 5323:        '.&Apache::loncommon::end_data_table_row().'
 5324:        '.&Apache::loncommon::end_data_table().'
 5325: ');
 5326:     }
 5327: 
 5328:     # Chunk of the form that prompts to view a scoring office file,
 5329:     # corrected file, skipped records in a file.
 5330: 
 5331:     $r->print('
 5332:    <br />
 5333:    <form action="/adm/grades" name="scantron_download">
 5334:      '.$default_form_data.'
 5335:      <input type="hidden" name="command" value="scantron_download" />
 5336:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5337:        '.&Apache::loncommon::start_data_table_header_row().'
 5338:               <th>
 5339:                 &nbsp;'.&mt('Download a scoring office file').'
 5340:               </th>
 5341:        '.&Apache::loncommon::end_data_table_header_row().'
 5342:        '.&Apache::loncommon::start_data_table_row().'
 5343:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5344:                 <br />
 5345:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5346:        '.&Apache::loncommon::end_data_table_row().'
 5347:      '.&Apache::loncommon::end_data_table().'
 5348:    </form>
 5349:    <br />
 5350: ');
 5351: 
 5352:     &Apache::lonpickcode::code_list($r,2);
 5353: 
 5354:     $r->print('<br /><form method="post" name="checkscantron">'.
 5355:              $default_form_data."\n".
 5356:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5357:              &Apache::loncommon::start_data_table_header_row()."\n".
 5358:              '<th colspan="2">
 5359:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5360:              '</th>'."\n".
 5361:               &Apache::loncommon::end_data_table_header_row()."\n".
 5362:               &Apache::loncommon::start_data_table_row()."\n".
 5363:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5364:               '<td> '.$sequence_selector.' </td>'.
 5365:               &Apache::loncommon::end_data_table_row()."\n".
 5366:               &Apache::loncommon::start_data_table_row()."\n".
 5367:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5368:               '<td> '.$file_selector.' </td>'."\n".
 5369:               &Apache::loncommon::end_data_table_row()."\n".
 5370:               &Apache::loncommon::start_data_table_row()."\n".
 5371:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5372:               '<td> '.$format_selector.' </td>'."\n".
 5373:               &Apache::loncommon::end_data_table_row()."\n".
 5374:               &Apache::loncommon::start_data_table_row()."\n".
 5375:               '<td> '.&mt('Options').' </td>'."\n".
 5376:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5377:               &Apache::loncommon::end_data_table_row()."\n".
 5378:               &Apache::loncommon::start_data_table_row()."\n".
 5379:               '<td colspan="2">'."\n".
 5380:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5381:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5382:               '</td>'."\n".
 5383:               &Apache::loncommon::end_data_table_row()."\n".
 5384:               &Apache::loncommon::end_data_table()."\n".
 5385:               '</form><br />');
 5386:     $r->print($grading_menu_button);
 5387:     return;
 5388: }
 5389: 
 5390: =pod
 5391: 
 5392: =item get_scantron_config
 5393: 
 5394:    Parse and return the scantron configuration line selected as a
 5395:    hash of configuration file fields.
 5396: 
 5397:  Arguments:
 5398:     which - the name of the configuration to parse from the file.
 5399: 
 5400: 
 5401:  Returns:
 5402:             If the named configuration is not in the file, an empty
 5403:             hash is returned.
 5404:     a hash with the fields
 5405:       name         - internal name for the this configuration setup
 5406:       description  - text to display to operator that describes this config
 5407:       CODElocation - if 0 or the string 'none'
 5408:                           - no CODE exists for this config
 5409:                      if -1 || the string 'letter'
 5410:                           - a CODE exists for this config and is
 5411:                             a string of letters
 5412:                      Unsupported value (but planned for future support)
 5413:                           if a positive integer
 5414:                                - The CODE exists as the first n items from
 5415:                                  the question section of the form
 5416:                           if the string 'number'
 5417:                                - The CODE exists for this config and is
 5418:                                  a string of numbers
 5419:       CODEstart   - (only matter if a CODE exists) column in the line where
 5420:                      the CODE starts
 5421:       CODElength  - length of the CODE
 5422:       IDstart     - column where the student/employee ID starts
 5423:       IDlength    - length of the student/employee ID info
 5424:       Qstart      - column where the information from the bubbled
 5425:                     'questions' start
 5426:       Qlength     - number of columns comprising a single bubble line from
 5427:                     the sheet. (usually either 1 or 10)
 5428:       Qon         - either a single character representing the character used
 5429:                     to signal a bubble was chosen in the positional setup, or
 5430:                     the string 'letter' if the letter of the chosen bubble is
 5431:                     in the final, or 'number' if a number representing the
 5432:                     chosen bubble is in the file (1->A 0->J)
 5433:       Qoff        - the character used to represent that a bubble was
 5434:                     left blank
 5435:       PaperID     - if the scanning process generates a unique number for each
 5436:                     sheet scanned the column that this ID number starts in
 5437:       PaperIDlength - number of columns that comprise the unique ID number
 5438:                       for the sheet of paper
 5439:       FirstName   - column that the first name starts in
 5440:       FirstNameLength - number of columns that the first name spans
 5441:  
 5442:       LastName    - column that the last name starts in
 5443:       LastNameLength - number of columns that the last name spans
 5444: 
 5445: =cut
 5446: 
 5447: sub get_scantron_config {
 5448:     my ($which) = @_;
 5449:     my @lines = &get_scantronformat_file();
 5450:     my %config;
 5451:     #FIXME probably should move to XML it has already gotten a bit much now
 5452:     foreach my $line (@lines) {
 5453: 	my ($name,$descrip)=split(/:/,$line);
 5454: 	if ($name ne $which ) { next; }
 5455: 	chomp($line);
 5456: 	my @config=split(/:/,$line);
 5457: 	$config{'name'}=$config[0];
 5458: 	$config{'description'}=$config[1];
 5459: 	$config{'CODElocation'}=$config[2];
 5460: 	$config{'CODEstart'}=$config[3];
 5461: 	$config{'CODElength'}=$config[4];
 5462: 	$config{'IDstart'}=$config[5];
 5463: 	$config{'IDlength'}=$config[6];
 5464: 	$config{'Qstart'}=$config[7];
 5465:  	$config{'Qlength'}=$config[8];
 5466: 	$config{'Qoff'}=$config[9];
 5467: 	$config{'Qon'}=$config[10];
 5468: 	$config{'PaperID'}=$config[11];
 5469: 	$config{'PaperIDlength'}=$config[12];
 5470: 	$config{'FirstName'}=$config[13];
 5471: 	$config{'FirstNamelength'}=$config[14];
 5472: 	$config{'LastName'}=$config[15];
 5473: 	$config{'LastNamelength'}=$config[16];
 5474: 	last;
 5475:     }
 5476:     return %config;
 5477: }
 5478: 
 5479: =pod 
 5480: 
 5481: =item username_to_idmap
 5482: 
 5483:     creates a hash keyed by student/employee ID with values of the corresponding
 5484:     student username:domain.
 5485: 
 5486:   Arguments:
 5487: 
 5488:     $classlist - reference to the class list hash. This is a hash
 5489:                  keyed by student name:domain  whose elements are references
 5490:                  to arrays containing various chunks of information
 5491:                  about the student. (See loncoursedata for more info).
 5492: 
 5493:   Returns
 5494:     %idmap - the constructed hash
 5495: 
 5496: =cut
 5497: 
 5498: sub username_to_idmap {
 5499:     my ($classlist)= @_;
 5500:     my %idmap;
 5501:     foreach my $student (keys(%$classlist)) {
 5502: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5503: 	    $student;
 5504:     }
 5505:     return %idmap;
 5506: }
 5507: 
 5508: =pod
 5509: 
 5510: =item scantron_fixup_scanline
 5511: 
 5512:    Process a requested correction to a scanline.
 5513: 
 5514:   Arguments:
 5515:     $scantron_config   - hash from &get_scantron_config()
 5516:     $scan_data         - hash of correction information 
 5517:                           (see &scantron_getfile())
 5518:     $line              - existing scanline
 5519:     $whichline         - line number of the passed in scanline
 5520:     $field             - type of change to process 
 5521:                          (either 
 5522:                           'ID'     -> correct the student/employee ID
 5523:                           'CODE'   -> correct the CODE
 5524:                           'answer' -> fixup the submitted answers)
 5525:     
 5526:    $args               - hash of additional info,
 5527:                           - 'ID' 
 5528:                                'newid' -> studentID to use in replacement
 5529:                                           of existing one
 5530:                           - 'CODE' 
 5531:                                'CODE_ignore_dup' - set to true if duplicates
 5532:                                                    should be ignored.
 5533: 	                       'CODE' - is new code or 'use_unfound'
 5534:                                         if the existing unfound code should
 5535:                                         be used as is
 5536:                           - 'answer'
 5537:                                'response' - new answer or 'none' if blank
 5538:                                'question' - the bubble line to change
 5539:                                'questionnum' - the question identifier,
 5540:                                                may include subquestion. 
 5541: 
 5542:   Returns:
 5543:     $line - the modified scanline
 5544: 
 5545:   Side effects: 
 5546:     $scan_data - may be updated
 5547: 
 5548: =cut
 5549: 
 5550: 
 5551: sub scantron_fixup_scanline {
 5552:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5553:     if ($field eq 'ID') {
 5554: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5555: 	    return ($line,1,'New value too large');
 5556: 	}
 5557: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5558: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5559: 				     $args->{'newid'});
 5560: 	}
 5561: 	substr($line,$$scantron_config{'IDstart'}-1,
 5562: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5563: 	if ($args->{'newid'}=~/^\s*$/) {
 5564: 	    &scan_data($scan_data,"$whichline.user",
 5565: 		       $args->{'username'}.':'.$args->{'domain'});
 5566: 	}
 5567:     } elsif ($field eq 'CODE') {
 5568: 	if ($args->{'CODE_ignore_dup'}) {
 5569: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5570: 	}
 5571: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5572: 	if ($args->{'CODE'} ne 'use_unfound') {
 5573: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5574: 		return ($line,1,'New CODE value too large');
 5575: 	    }
 5576: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5577: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5578: 	    }
 5579: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5580: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5581: 	}
 5582:     } elsif ($field eq 'answer') {
 5583: 	my $length=$scantron_config->{'Qlength'};
 5584: 	my $off=$scantron_config->{'Qoff'};
 5585: 	my $on=$scantron_config->{'Qon'};
 5586: 	my $answer=${off}x$length;
 5587: 	if ($args->{'response'} eq 'none') {
 5588: 	    &scan_data($scan_data,
 5589: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5590: 	} else {
 5591: 	    if ($on eq 'letter') {
 5592: 		my @alphabet=('A'..'Z');
 5593: 		$answer=$alphabet[$args->{'response'}];
 5594: 	    } elsif ($on eq 'number') {
 5595: 		$answer=$args->{'response'}+1;
 5596: 		if ($answer == 10) { $answer = '0'; }
 5597: 	    } else {
 5598: 		substr($answer,$args->{'response'},1)=$on;
 5599: 	    }
 5600: 	    &scan_data($scan_data,
 5601: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5602: 	}
 5603: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5604: 	substr($line,$where-1,$length)=$answer;
 5605:     }
 5606:     return $line;
 5607: }
 5608: 
 5609: =pod
 5610: 
 5611: =item scan_data
 5612: 
 5613:     Edit or look up  an item in the scan_data hash.
 5614: 
 5615:   Arguments:
 5616:     $scan_data  - The hash (see scantron_getfile)
 5617:     $key        - shorthand of the key to edit (actual key is
 5618:                   scantronfilename_key).
 5619:     $data        - New value of the hash entry.
 5620:     $delete      - If true, the entry is removed from the hash.
 5621: 
 5622:   Returns:
 5623:     The new value of the hash table field (undefined if deleted).
 5624: 
 5625: =cut
 5626: 
 5627: 
 5628: sub scan_data {
 5629:     my ($scan_data,$key,$value,$delete)=@_;
 5630:     my $filename=$env{'form.scantron_selectfile'};
 5631:     if (defined($value)) {
 5632: 	$scan_data->{$filename.'_'.$key} = $value;
 5633:     }
 5634:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5635:     return $scan_data->{$filename.'_'.$key};
 5636: }
 5637: 
 5638: # ----- These first few routines are general use routines.----
 5639: 
 5640: # Return the number of occurences of a pattern in a string.
 5641: 
 5642: sub occurence_count {
 5643:     my ($string, $pattern) = @_;
 5644: 
 5645:     my @matches = ($string =~ /$pattern/g);
 5646: 
 5647:     return scalar(@matches);
 5648: }
 5649: 
 5650: 
 5651: # Take a string known to have digits and convert all the
 5652: # digits into letters in the range J,A..I.
 5653: 
 5654: sub digits_to_letters {
 5655:     my ($input) = @_;
 5656: 
 5657:     my @alphabet = ('J', 'A'..'I');
 5658: 
 5659:     my @input    = split(//, $input);
 5660:     my $output ='';
 5661:     for (my $i = 0; $i < scalar(@input); $i++) {
 5662: 	if ($input[$i] =~ /\d/) {
 5663: 	    $output .= $alphabet[$input[$i]];
 5664: 	} else {
 5665: 	    $output .= $input[$i];
 5666: 	}
 5667:     }
 5668:     return $output;
 5669: }
 5670: 
 5671: =pod 
 5672: 
 5673: =item scantron_parse_scanline
 5674: 
 5675:   Decodes a scanline from the selected scantron file
 5676: 
 5677:  Arguments:
 5678:     line             - The text of the scantron file line to process
 5679:     whichline        - Line number
 5680:     scantron_config  - Hash describing the format of the scantron lines.
 5681:     scan_data        - Hash of extra information about the scanline
 5682:                        (see scantron_getfile for more information)
 5683:     just_header      - True if should not process question answers but only
 5684:                        the stuff to the left of the answers.
 5685:  Returns:
 5686:    Hash containing the result of parsing the scanline
 5687: 
 5688:    Keys are all proceeded by the string 'scantron.'
 5689: 
 5690:        CODE    - the CODE in use for this scanline
 5691:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5692:                  by the operator
 5693:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5694:                             CODEs were selected, but the usage has been
 5695:                             forced by the operator
 5696:        ID  - student/employee ID
 5697:        PaperID - if used, the ID number printed on the sheet when the 
 5698:                  paper was scanned
 5699:        FirstName - first name from the sheet
 5700:        LastName  - last name from the sheet
 5701: 
 5702:      if just_header was not true these key may also exist
 5703: 
 5704:        missingerror - a list of bubble ranges that are considered to be answers
 5705:                       to a single question that don't have any bubbles filled in.
 5706:                       Of the form questionnumber:firstbubblenumber:count.
 5707:        doubleerror  - a list of bubble ranges that are considered to be answers
 5708:                       to a single question that have more than one bubble filled in.
 5709:                       Of the form questionnumber::firstbubblenumber:count
 5710:    
 5711:                 In the above, count is the number of bubble responses in the
 5712:                 input line needed to represent the possible answers to the question.
 5713:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5714:                 per line would have count = 2.
 5715: 
 5716:        maxquest     - the number of the last bubble line that was parsed
 5717: 
 5718:        (<number> starts at 1)
 5719:        <number>.answer - zero or more letters representing the selected
 5720:                          letters from the scanline for the bubble line 
 5721:                          <number>.
 5722:                          if blank there was either no bubble or there where
 5723:                          multiple bubbles, (consult the keys missingerror and
 5724:                          doubleerror if this is an error condition)
 5725: 
 5726: =cut
 5727: 
 5728: sub scantron_parse_scanline {
 5729:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5730: 
 5731:     my %record;
 5732:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5733:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5734:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5735:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5736: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5737: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5738: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5739: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5740: 	    $record{'scantron.CODE'}=substr($data,
 5741: 					    $$scantron_config{'CODEstart'}-1,
 5742: 					    $$scantron_config{'CODElength'});
 5743: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5744: 		$record{'scantron.useCODE'}=1;
 5745: 	    }
 5746: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5747: 		$record{'scantron.CODE_ignore_dup'}=1;
 5748: 	    }
 5749: 	} else {
 5750: 	    #FIXME interpret first N questions
 5751: 	}
 5752:     }
 5753:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5754: 				  $$scantron_config{'IDlength'});
 5755:     $record{'scantron.PaperID'}=
 5756: 	substr($data,$$scantron_config{'PaperID'}-1,
 5757: 	       $$scantron_config{'PaperIDlength'});
 5758:     $record{'scantron.FirstName'}=
 5759: 	substr($data,$$scantron_config{'FirstName'}-1,
 5760: 	       $$scantron_config{'FirstNamelength'});
 5761:     $record{'scantron.LastName'}=
 5762: 	substr($data,$$scantron_config{'LastName'}-1,
 5763: 	       $$scantron_config{'LastNamelength'});
 5764:     if ($just_header) { return \%record; }
 5765: 
 5766:     my @alphabet=('A'..'Z');
 5767:     my $questnum=0;
 5768:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5769: 
 5770:     chomp($questions);		# Get rid of any trailing \n.
 5771:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5772:     while (length($questions)) {
 5773: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5774:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5775:                              || 1;
 5776:         $questnum++;
 5777:         my $quest_id = $questnum;
 5778:         my $currentquest = substr($questions,0,$answer_length);
 5779:         $questions       = substr($questions,$answer_length);
 5780:         if (length($currentquest) < $answer_length) { next; }
 5781: 
 5782:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5783:             my $subquestnum = 1;
 5784:             my $subquestions = $currentquest;
 5785:             my @subanswers_needed = 
 5786:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5787:             foreach my $subans (@subanswers_needed) {
 5788:                 my $subans_length =
 5789:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5790:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5791:                 $subquestions   = substr($subquestions,$subans_length);
 5792:                 $quest_id = "$questnum.$subquestnum";
 5793:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5794:                     ($$scantron_config{'Qon'} eq 'number')) {
 5795:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5796:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5797:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5798:                 } else {
 5799:                     $ansnum = &scantron_validator_positional($ansnum,
 5800:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5801:                 }
 5802:                 $subquestnum ++;
 5803:             }
 5804:         } else {
 5805:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5806:                 ($$scantron_config{'Qon'} eq 'number')) {
 5807:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5808:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5809:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5810:             } else {
 5811:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5812:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5813:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5814:             }
 5815:         }
 5816:     }
 5817:     $record{'scantron.maxquest'}=$questnum;
 5818:     return \%record;
 5819: }
 5820: 
 5821: sub scantron_validator_lettnum {
 5822:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5823:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5824: 
 5825:     # Qon 'letter' implies for each slot in currquest we have:
 5826:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5827:     #    about anything else (esp. a value of Qoff) for missing
 5828:     #    bubbles.
 5829:     #
 5830:     # Qon 'number' implies each slot gives a digit that indexes the
 5831:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5832:     #    and * or ? for double bubbles on a single line.
 5833:     #
 5834: 
 5835:     my $matchon;
 5836:     if ($$scantron_config{'Qon'} eq 'letter') {
 5837:         $matchon = '[A-Z]';
 5838:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5839:         $matchon = '\d';
 5840:     }
 5841:     my $occurrences = 0;
 5842:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5843:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5844:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5845:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5846:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5847:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5848:         my @singlelines = split('',$currquest);
 5849:         foreach my $entry (@singlelines) {
 5850:             $occurrences = &occurence_count($entry,$matchon);
 5851:             if ($occurrences > 1) {
 5852:                 last;
 5853:             }
 5854:         } 
 5855:     } else {
 5856:         $occurrences = &occurence_count($currquest,$matchon); 
 5857:     }
 5858:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5859:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5860:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5861:             my $bubble = substr($currquest,$ans,1);
 5862:             if ($bubble =~ /$matchon/ ) {
 5863:                 if ($$scantron_config{'Qon'} eq 'number') {
 5864:                     if ($bubble == 0) {
 5865:                         $bubble = 10; 
 5866:                     }
 5867:                     $record->{"scantron.$ansnum.answer"} = 
 5868:                         $alphabet->[$bubble-1];
 5869:                 } else {
 5870:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5871:                 }
 5872:             } else {
 5873:                 $record->{"scantron.$ansnum.answer"}='';
 5874:             }
 5875:             $ansnum++;
 5876:         }
 5877:     } elsif (!defined($currquest)
 5878:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5879:             || (&occurence_count($currquest,$matchon) == 0)) {
 5880:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5881:             $record->{"scantron.$ansnum.answer"}='';
 5882:             $ansnum++;
 5883:         }
 5884:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5885:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5886:         }
 5887:     } else {
 5888:         if ($$scantron_config{'Qon'} eq 'number') {
 5889:             $currquest = &digits_to_letters($currquest);            
 5890:         }
 5891:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5892:             my $bubble = substr($currquest,$ans,1);
 5893:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5894:             $ansnum++;
 5895:         }
 5896:     }
 5897:     return $ansnum;
 5898: }
 5899: 
 5900: sub scantron_validator_positional {
 5901:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5902:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5903: 
 5904:     # Otherwise there's a positional notation;
 5905:     # each bubble line requires Qlength items, and there are filled in
 5906:     # bubbles for each case where there 'Qon' characters.
 5907:     #
 5908: 
 5909:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5910: 
 5911:     # If the split only gives us one element.. the full length of the
 5912:     # answer string, no bubbles are filled in:
 5913: 
 5914:     if ($answers_needed eq '') {
 5915:         return;
 5916:     }
 5917: 
 5918:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5919:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5920:             $record->{"scantron.$ansnum.answer"}='';
 5921:             $ansnum++;
 5922:         }
 5923:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5924:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5925:         }
 5926:     } elsif (scalar(@array) == 2) {
 5927:         my $location = length($array[0]);
 5928:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5929:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5930:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5931:             if ($ans eq $line_num) {
 5932:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5933:             } else {
 5934:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5935:             }
 5936:             $ansnum++;
 5937:          }
 5938:     } else {
 5939:         #  If there's more than one instance of a bubble character
 5940:         #  That's a double bubble; with positional notation we can
 5941:         #  record all the bubbles filled in as well as the
 5942:         #  fact this response consists of multiple bubbles.
 5943:         #
 5944:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5945:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5946:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5947:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5948:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5949:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5950:             my $doubleerror = 0;
 5951:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5952:                    (!$doubleerror)) {
 5953:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5954:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5955:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5956:                if (length(@currarray) > 2) {
 5957:                    $doubleerror = 1;
 5958:                } 
 5959:             }
 5960:             if ($doubleerror) {
 5961:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5962:             }
 5963:         } else {
 5964:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5965:         }
 5966:         my $item = $ansnum;
 5967:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5968:             $record->{"scantron.$item.answer"} = '';
 5969:             $item ++;
 5970:         }
 5971: 
 5972:         my @ans=@array;
 5973:         my $i=0;
 5974:         my $increment = 0;
 5975:         while ($#ans) {
 5976:             $i+=length($ans[0]) + $increment;
 5977:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5978:             my $bubble = $i%$$scantron_config{'Qlength'};
 5979:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5980:             shift(@ans);
 5981:             $increment = 1;
 5982:         }
 5983:         $ansnum += $answers_needed;
 5984:     }
 5985:     return $ansnum;
 5986: }
 5987: 
 5988: =pod
 5989: 
 5990: =item scantron_add_delay
 5991: 
 5992:    Adds an error message that occurred during the grading phase to a
 5993:    queue of messages to be shown after grading pass is complete
 5994: 
 5995:  Arguments:
 5996:    $delayqueue  - arrary ref of hash ref of error messages
 5997:    $scanline    - the scanline that caused the error
 5998:    $errormesage - the error message
 5999:    $errorcode   - a numeric code for the error
 6000: 
 6001:  Side Effects:
 6002:    updates the $delayqueue to have a new hash ref of the error
 6003: 
 6004: =cut
 6005: 
 6006: sub scantron_add_delay {
 6007:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6008:     push(@$delayqueue,
 6009: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6010: 	  'ecode' => $errorcode }
 6011: 	 );
 6012: }
 6013: 
 6014: =pod
 6015: 
 6016: =item scantron_find_student
 6017: 
 6018:    Finds the username for the current scanline
 6019: 
 6020:   Arguments:
 6021:    $scantron_record - hash result from scantron_parse_scanline
 6022:    $scan_data       - hash of correction information 
 6023:                       (see &scantron_getfile() form more information)
 6024:    $idmap           - hash from &username_to_idmap()
 6025:    $line            - number of current scanline
 6026:  
 6027:   Returns:
 6028:    Either 'username:domain' or undef if unknown
 6029: 
 6030: =cut
 6031: 
 6032: sub scantron_find_student {
 6033:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6034:     my $scanID=$$scantron_record{'scantron.ID'};
 6035:     if ($scanID =~ /^\s*$/) {
 6036:  	return &scan_data($scan_data,"$line.user");
 6037:     }
 6038:     foreach my $id (keys(%$idmap)) {
 6039:  	if (lc($id) eq lc($scanID)) {
 6040:  	    return $$idmap{$id};
 6041:  	}
 6042:     }
 6043:     return undef;
 6044: }
 6045: 
 6046: =pod
 6047: 
 6048: =item scantron_filter
 6049: 
 6050:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6051:    hidden resources was selected
 6052: 
 6053: =cut
 6054: 
 6055: sub scantron_filter {
 6056:     my ($curres)=@_;
 6057: 
 6058:     if (ref($curres) && $curres->is_problem()) {
 6059: 	# if the user has asked to not have either hidden
 6060: 	# or 'randomout' controlled resources to be graded
 6061: 	# don't include them
 6062: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6063: 	    && $curres->randomout) {
 6064: 	    return 0;
 6065: 	}
 6066: 	return 1;
 6067:     }
 6068:     return 0;
 6069: }
 6070: 
 6071: =pod
 6072: 
 6073: =item scantron_process_corrections
 6074: 
 6075:    Gets correction information out of submitted form data and corrects
 6076:    the scanline
 6077: 
 6078: =cut
 6079: 
 6080: sub scantron_process_corrections {
 6081:     my ($r) = @_;
 6082:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6083:     my ($scanlines,$scan_data)=&scantron_getfile();
 6084:     my $classlist=&Apache::loncoursedata::get_classlist();
 6085:     my $which=$env{'form.scantron_line'};
 6086:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6087:     my ($skip,$err,$errmsg);
 6088:     if ($env{'form.scantron_skip_record'}) {
 6089: 	$skip=1;
 6090:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6091: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6092: 	    $env{'form.scantron_domain'};
 6093: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6094: 	($line,$err,$errmsg)=
 6095: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6096: 				     'ID',{'newid'=>$newid,
 6097: 				    'username'=>$env{'form.scantron_username'},
 6098: 				    'domain'=>$env{'form.scantron_domain'}});
 6099:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6100: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6101: 	my $newCODE;
 6102: 	my %args;
 6103: 	if      ($resolution eq 'use_unfound') {
 6104: 	    $newCODE='use_unfound';
 6105: 	} elsif ($resolution eq 'use_found') {
 6106: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6107: 	} elsif ($resolution eq 'use_typed') {
 6108: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6109: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6110: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6111: 	}
 6112: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6113: 	    $args{'CODE_ignore_dup'}=1;
 6114: 	}
 6115: 	$args{'CODE'}=$newCODE;
 6116: 	($line,$err,$errmsg)=
 6117: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6118: 				     'CODE',\%args);
 6119:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6120: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6121: 	    ($line,$err,$errmsg)=
 6122: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6123: 					 $which,'answer',
 6124: 					 { 'question'=>$question,
 6125: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6126:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6127: 	    if ($err) { last; }
 6128: 	}
 6129:     }
 6130:     if ($err) {
 6131: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6132:     } else {
 6133: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6134: 	&scantron_putfile($scanlines,$scan_data);
 6135:     }
 6136: }
 6137: 
 6138: =pod
 6139: 
 6140: =item reset_skipping_status
 6141: 
 6142:    Forgets the current set of remember skipped scanlines (and thus
 6143:    reverts back to considering all lines in the
 6144:    scantron_skipped_<filename> file)
 6145: 
 6146: =cut
 6147: 
 6148: sub reset_skipping_status {
 6149:     my ($scanlines,$scan_data)=&scantron_getfile();
 6150:     &scan_data($scan_data,'remember_skipping',undef,1);
 6151:     &scantron_putfile(undef,$scan_data);
 6152: }
 6153: 
 6154: =pod
 6155: 
 6156: =item start_skipping
 6157: 
 6158:    Marks a scanline to be skipped. 
 6159: 
 6160: =cut
 6161: 
 6162: sub start_skipping {
 6163:     my ($scan_data,$i)=@_;
 6164:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6165:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6166: 	$remembered{$i}=2;
 6167:     } else {
 6168: 	$remembered{$i}=1;
 6169:     }
 6170:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6171: }
 6172: 
 6173: =pod
 6174: 
 6175: =item should_be_skipped
 6176: 
 6177:    Checks whether a scanline should be skipped.
 6178: 
 6179: =cut
 6180: 
 6181: sub should_be_skipped {
 6182:     my ($scanlines,$scan_data,$i)=@_;
 6183:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6184: 	# not redoing old skips
 6185: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6186: 	return 0;
 6187:     }
 6188:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6189: 
 6190:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6191: 	return 0;
 6192:     }
 6193:     return 1;
 6194: }
 6195: 
 6196: =pod
 6197: 
 6198: =item remember_current_skipped
 6199: 
 6200:    Discovers what scanlines are in the scantron_skipped_<filename>
 6201:    file and remembers them into scan_data for later use.
 6202: 
 6203: =cut
 6204: 
 6205: sub remember_current_skipped {
 6206:     my ($scanlines,$scan_data)=&scantron_getfile();
 6207:     my %to_remember;
 6208:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6209: 	if ($scanlines->{'skipped'}[$i]) {
 6210: 	    $to_remember{$i}=1;
 6211: 	}
 6212:     }
 6213: 
 6214:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6215:     &scantron_putfile(undef,$scan_data);
 6216: }
 6217: 
 6218: =pod
 6219: 
 6220: =item check_for_error
 6221: 
 6222:     Checks if there was an error when attempting to remove a specific
 6223:     scantron_.. bubble sheet data file. Prints out an error if
 6224:     something went wrong.
 6225: 
 6226: =cut
 6227: 
 6228: sub check_for_error {
 6229:     my ($r,$result)=@_;
 6230:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6231: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6232:     }
 6233: }
 6234: 
 6235: =pod
 6236: 
 6237: =item scantron_warning_screen
 6238: 
 6239:    Interstitial screen to make sure the operator has selected the
 6240:    correct options before we start the validation phase.
 6241: 
 6242: =cut
 6243: 
 6244: sub scantron_warning_screen {
 6245:     my ($button_text)=@_;
 6246:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6247:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6248:     my $CODElist;
 6249:     if ($scantron_config{'CODElocation'} &&
 6250: 	$scantron_config{'CODEstart'} &&
 6251: 	$scantron_config{'CODElength'}) {
 6252: 	$CODElist=$env{'form.scantron_CODElist'};
 6253: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6254: 	$CODElist=
 6255: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6256: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6257:     }
 6258:     return ('
 6259: <p>
 6260: <span class="LC_warning">
 6261: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6262: </p>
 6263: <table>
 6264: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6265: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6266: '.$CODElist.'
 6267: </table>
 6268: <br />
 6269: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6270: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6271: 
 6272: <br />
 6273: ');
 6274: }
 6275: 
 6276: =pod
 6277: 
 6278: =item scantron_do_warning
 6279: 
 6280:    Check if the operator has picked something for all required
 6281:    fields. Error out if something is missing.
 6282: 
 6283: =cut
 6284: 
 6285: sub scantron_do_warning {
 6286:     my ($r)=@_;
 6287:     my ($symb)=&get_symb($r);
 6288:     if (!$symb) {return '';}
 6289:     my $default_form_data=&defaultFormData($symb);
 6290:     $r->print(&scantron_form_start().$default_form_data);
 6291:     if ( $env{'form.selectpage'} eq '' ||
 6292: 	 $env{'form.scantron_selectfile'} eq '' ||
 6293: 	 $env{'form.scantron_format'} eq '' ) {
 6294: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6295: 	if ( $env{'form.selectpage'} eq '') {
 6296: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6297: 	} 
 6298: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6299: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6300: 	} 
 6301: 	if ( $env{'form.scantron_format'} eq '') {
 6302: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6303: 	} 
 6304:     } else {
 6305: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6306: 	$r->print('
 6307: '.$warning.'
 6308: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6309: <input type="hidden" name="command" value="scantron_validate" />
 6310: ');
 6311:     }
 6312:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6313:     return '';
 6314: }
 6315: 
 6316: =pod
 6317: 
 6318: =item scantron_form_start
 6319: 
 6320:     html hidden input for remembering all selected grading options
 6321: 
 6322: =cut
 6323: 
 6324: sub scantron_form_start {
 6325:     my ($max_bubble)=@_;
 6326:     my $result= <<SCANTRONFORM;
 6327: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6328:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6329:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6330:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6331:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6332:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6333:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6334:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6335:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6336:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6337: SCANTRONFORM
 6338: 
 6339:   my $line = 0;
 6340:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6341:        my $chunk =
 6342: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6343:        $chunk .=
 6344: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6345:        $chunk .= 
 6346:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6347:        $chunk .=
 6348:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6349:        $result .= $chunk;
 6350:        $line++;
 6351:    }
 6352:     return $result;
 6353: }
 6354: 
 6355: =pod
 6356: 
 6357: =item scantron_validate_file
 6358: 
 6359:     Dispatch routine for doing validation of a bubble sheet data file.
 6360: 
 6361:     Also processes any necessary information resets that need to
 6362:     occur before validation begins (ignore previous corrections,
 6363:     restarting the skipped records processing)
 6364: 
 6365: =cut
 6366: 
 6367: sub scantron_validate_file {
 6368:     my ($r) = @_;
 6369:     my ($symb)=&get_symb($r);
 6370:     if (!$symb) {return '';}
 6371:     my $default_form_data=&defaultFormData($symb);
 6372:     
 6373:     # do the detection of only doing skipped records first befroe we delete
 6374:     # them when doing the corrections reset
 6375:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6376: 	&reset_skipping_status();
 6377:     }
 6378:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6379: 	&remember_current_skipped();
 6380: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6381:     }
 6382: 
 6383:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6384: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6385: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6386: 	&check_for_error($r,&scantron_remove_scan_data());
 6387: 	$env{'form.scantron_options_ignore'}='done';
 6388:     }
 6389: 
 6390:     if ($env{'form.scantron_corrections'}) {
 6391: 	&scantron_process_corrections($r);
 6392:     }
 6393:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6394:     #get the student pick code ready
 6395:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6396:     my $nav_error;
 6397:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6398:     if ($nav_error) {
 6399:         $r->print(&navmap_errormsg());
 6400:         return '';
 6401:     }
 6402:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6403:     $r->print($result);
 6404:     
 6405:     my @validate_phases=( 'sequence',
 6406: 			  'ID',
 6407: 			  'CODE',
 6408: 			  'doublebubble',
 6409: 			  'missingbubbles');
 6410:     if (!$env{'form.validatepass'}) {
 6411: 	$env{'form.validatepass'} = 0;
 6412:     }
 6413:     my $currentphase=$env{'form.validatepass'};
 6414: 
 6415: 
 6416:     my $stop=0;
 6417:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6418: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6419: 	$r->rflush();
 6420: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6421: 	{
 6422: 	    no strict 'refs';
 6423: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6424: 	}
 6425:     }
 6426:     if (!$stop) {
 6427: 	my $warning=&scantron_warning_screen('Start Grading');
 6428: 	$r->print(&mt('Validation process complete.').'<br />'.
 6429:                   $warning.
 6430:                   &mt('Perform verification for each student after storage of submissions?').
 6431:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6432:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6433:                   ('&nbsp;'x3).'<label>'.
 6434:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6435:                   '</label></span><br />'.
 6436:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6437:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6438:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6439:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6440:     } else {
 6441: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6442: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6443:     }
 6444:     if ($stop) {
 6445: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6446: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6447: 	    $r->print(' '.&mt('this error').' <br />');
 6448: 
 6449: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6450: 	} else {
 6451:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6452: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6453:             } else {
 6454:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6455:             }
 6456: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6457: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6458: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6459: 	}
 6460:     }
 6461:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6462:     return '';
 6463: }
 6464: 
 6465: 
 6466: =pod
 6467: 
 6468: =item scantron_remove_file
 6469: 
 6470:    Removes the requested bubble sheet data file, makes sure that
 6471:    scantron_original_<filename> is never removed
 6472: 
 6473: 
 6474: =cut
 6475: 
 6476: sub scantron_remove_file {
 6477:     my ($which)=@_;
 6478:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6479:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6480:     my $file='scantron_';
 6481:     if ($which eq 'corrected' || $which eq 'skipped') {
 6482: 	$file.=$which.'_';
 6483:     } else {
 6484: 	return 'refused';
 6485:     }
 6486:     $file.=$env{'form.scantron_selectfile'};
 6487:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6488: }
 6489: 
 6490: 
 6491: =pod
 6492: 
 6493: =item scantron_remove_scan_data
 6494: 
 6495:    Removes all scan_data correction for the requested bubble sheet
 6496:    data file.  (In the case that both the are doing skipped records we need
 6497:    to remember the old skipped lines for the time being so that element
 6498:    persists for a while.)
 6499: 
 6500: =cut
 6501: 
 6502: sub scantron_remove_scan_data {
 6503:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6504:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6505:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6506:     my @todelete;
 6507:     my $filename=$env{'form.scantron_selectfile'};
 6508:     foreach my $key (@keys) {
 6509: 	if ($key=~/^\Q$filename\E_/) {
 6510: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6511: 		$key=~/remember_skipping/) {
 6512: 		next;
 6513: 	    }
 6514: 	    push(@todelete,$key);
 6515: 	}
 6516:     }
 6517:     my $result;
 6518:     if (@todelete) {
 6519: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6520: 				       \@todelete,$cdom,$cname);
 6521:     } else {
 6522: 	$result = 'ok';
 6523:     }
 6524:     return $result;
 6525: }
 6526: 
 6527: 
 6528: =pod
 6529: 
 6530: =item scantron_getfile
 6531: 
 6532:     Fetches the requested bubble sheet data file (all 3 versions), and
 6533:     the scan_data hash
 6534:   
 6535:   Arguments:
 6536:     None
 6537: 
 6538:   Returns:
 6539:     2 hash references
 6540: 
 6541:      - first one has 
 6542:          orig      -
 6543:          corrected -
 6544:          skipped   -  each of which points to an array ref of the specified
 6545:                       file broken up into individual lines
 6546:          count     - number of scanlines
 6547:  
 6548:      - second is the scan_data hash possible keys are
 6549:        ($number refers to scanline numbered $number and thus the key affects
 6550:         only that scanline
 6551:         $bubline refers to the specific bubble line element and the aspects
 6552:         refers to that specific bubble line element)
 6553: 
 6554:        $number.user - username:domain to use
 6555:        $number.CODE_ignore_dup 
 6556:                     - ignore the duplicate CODE error 
 6557:        $number.useCODE
 6558:                     - use the CODE in the scanline as is
 6559:        $number.no_bubble.$bubline
 6560:                     - it is valid that there is no bubbled in bubble
 6561:                       at $number $bubline
 6562:        remember_skipping
 6563:                     - a frozen hash containing keys of $number and values
 6564:                       of either 
 6565:                         1 - we are on a 'do skipped records pass' and plan
 6566:                             on processing this line
 6567:                         2 - we are on a 'do skipped records pass' and this
 6568:                             scanline has been marked to skip yet again
 6569: 
 6570: =cut
 6571: 
 6572: sub scantron_getfile {
 6573:     #FIXME really would prefer a scantron directory
 6574:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6575:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6576:     my $lines;
 6577:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6578: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6579:     my %scanlines;
 6580:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6581:     my $temp=$scanlines{'orig'};
 6582:     $scanlines{'count'}=$#$temp;
 6583: 
 6584:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6585: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6586:     if ($lines eq '-1') {
 6587: 	$scanlines{'corrected'}=[];
 6588:     } else {
 6589: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6590:     }
 6591:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6592: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6593:     if ($lines eq '-1') {
 6594: 	$scanlines{'skipped'}=[];
 6595:     } else {
 6596: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6597:     }
 6598:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6599:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6600:     my %scan_data = @tmp;
 6601:     return (\%scanlines,\%scan_data);
 6602: }
 6603: 
 6604: =pod
 6605: 
 6606: =item lonnet_putfile
 6607: 
 6608:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6609: 
 6610:  Arguments:
 6611:    $contents - data to store
 6612:    $filename - filename to store $contents into
 6613: 
 6614:  Returns:
 6615:    result value from &Apache::lonnet::finishuserfileupload
 6616: 
 6617: =cut
 6618: 
 6619: sub lonnet_putfile {
 6620:     my ($contents,$filename)=@_;
 6621:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6622:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6623:     $env{'form.sillywaytopassafilearound'}=$contents;
 6624:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6625: 
 6626: }
 6627: 
 6628: =pod
 6629: 
 6630: =item scantron_putfile
 6631: 
 6632:     Stores the current version of the bubble sheet data files, and the
 6633:     scan_data hash. (Does not modify the original version only the
 6634:     corrected and skipped versions.
 6635: 
 6636:  Arguments:
 6637:     $scanlines - hash ref that looks like the first return value from
 6638:                  &scantron_getfile()
 6639:     $scan_data - hash ref that looks like the second return value from
 6640:                  &scantron_getfile()
 6641: 
 6642: =cut
 6643: 
 6644: sub scantron_putfile {
 6645:     my ($scanlines,$scan_data) = @_;
 6646:     #FIXME really would prefer a scantron directory
 6647:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6648:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6649:     if ($scanlines) {
 6650: 	my $prefix='scantron_';
 6651: # no need to update orig, shouldn't change
 6652: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6653: #		    $env{'form.scantron_selectfile'});
 6654: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6655: 			$prefix.'corrected_'.
 6656: 			$env{'form.scantron_selectfile'});
 6657: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6658: 			$prefix.'skipped_'.
 6659: 			$env{'form.scantron_selectfile'});
 6660:     }
 6661:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6662: }
 6663: 
 6664: =pod
 6665: 
 6666: =item scantron_get_line
 6667: 
 6668:    Returns the correct version of the scanline
 6669: 
 6670:  Arguments:
 6671:     $scanlines - hash ref that looks like the first return value from
 6672:                  &scantron_getfile()
 6673:     $scan_data - hash ref that looks like the second return value from
 6674:                  &scantron_getfile()
 6675:     $i         - number of the requested line (starts at 0)
 6676: 
 6677:  Returns:
 6678:    A scanline, (either the original or the corrected one if it
 6679:    exists), or undef if the requested scanline should be
 6680:    skipped. (Either because it's an skipped scanline, or it's an
 6681:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6682:    pass.
 6683: 
 6684: =cut
 6685: 
 6686: sub scantron_get_line {
 6687:     my ($scanlines,$scan_data,$i)=@_;
 6688:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6689:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6690:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6691:     return $scanlines->{'orig'}[$i]; 
 6692: }
 6693: 
 6694: =pod
 6695: 
 6696: =item scantron_todo_count
 6697: 
 6698:     Counts the number of scanlines that need processing.
 6699: 
 6700:  Arguments:
 6701:     $scanlines - hash ref that looks like the first return value from
 6702:                  &scantron_getfile()
 6703:     $scan_data - hash ref that looks like the second return value from
 6704:                  &scantron_getfile()
 6705: 
 6706:  Returns:
 6707:     $count - number of scanlines to process
 6708: 
 6709: =cut
 6710: 
 6711: sub get_todo_count {
 6712:     my ($scanlines,$scan_data)=@_;
 6713:     my $count=0;
 6714:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6715: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6716: 	if ($line=~/^[\s\cz]*$/) { next; }
 6717: 	$count++;
 6718:     }
 6719:     return $count;
 6720: }
 6721: 
 6722: =pod
 6723: 
 6724: =item scantron_put_line
 6725: 
 6726:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6727:     data file.
 6728: 
 6729:  Arguments:
 6730:     $scanlines - hash ref that looks like the first return value from
 6731:                  &scantron_getfile()
 6732:     $scan_data - hash ref that looks like the second return value from
 6733:                  &scantron_getfile()
 6734:     $i         - line number to update
 6735:     $newline   - contents of the updated scanline
 6736:     $skip      - if true make the line for skipping and update the
 6737:                  'skipped' file
 6738: 
 6739: =cut
 6740: 
 6741: sub scantron_put_line {
 6742:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6743:     if ($skip) {
 6744: 	$scanlines->{'skipped'}[$i]=$newline;
 6745: 	&start_skipping($scan_data,$i);
 6746: 	return;
 6747:     }
 6748:     $scanlines->{'corrected'}[$i]=$newline;
 6749: }
 6750: 
 6751: =pod
 6752: 
 6753: =item scantron_clear_skip
 6754: 
 6755:    Remove a line from the 'skipped' file
 6756: 
 6757:  Arguments:
 6758:     $scanlines - hash ref that looks like the first return value from
 6759:                  &scantron_getfile()
 6760:     $scan_data - hash ref that looks like the second return value from
 6761:                  &scantron_getfile()
 6762:     $i         - line number to update
 6763: 
 6764: =cut
 6765: 
 6766: sub scantron_clear_skip {
 6767:     my ($scanlines,$scan_data,$i)=@_;
 6768:     if (exists($scanlines->{'skipped'}[$i])) {
 6769: 	undef($scanlines->{'skipped'}[$i]);
 6770: 	return 1;
 6771:     }
 6772:     return 0;
 6773: }
 6774: 
 6775: =pod
 6776: 
 6777: =item scantron_filter_not_exam
 6778: 
 6779:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6780:    filter out resources that are not marked as 'exam' mode
 6781: 
 6782: =cut
 6783: 
 6784: sub scantron_filter_not_exam {
 6785:     my ($curres)=@_;
 6786:     
 6787:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6788: 	# if the user has asked to not have either hidden
 6789: 	# or 'randomout' controlled resources to be graded
 6790: 	# don't include them
 6791: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6792: 	    && $curres->randomout) {
 6793: 	    return 0;
 6794: 	}
 6795: 	return 1;
 6796:     }
 6797:     return 0;
 6798: }
 6799: 
 6800: =pod
 6801: 
 6802: =item scantron_validate_sequence
 6803: 
 6804:     Validates the selected sequence, checking for resource that are
 6805:     not set to exam mode.
 6806: 
 6807: =cut
 6808: 
 6809: sub scantron_validate_sequence {
 6810:     my ($r,$currentphase) = @_;
 6811: 
 6812:     my $navmap=Apache::lonnavmaps::navmap->new();
 6813:     unless (ref($navmap)) {
 6814:         $r->print(&navmap_errormsg());
 6815:         return (1,$currentphase);
 6816:     }
 6817:     my (undef,undef,$sequence)=
 6818: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6819: 
 6820:     my $map=$navmap->getResourceByUrl($sequence);
 6821: 
 6822:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6823:                                     value="ignore" />');
 6824:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6825: 	my @resources=
 6826: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6827: 	if (@resources) {
 6828: 	    $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>");
 6829: 	    return (1,$currentphase);
 6830: 	}
 6831:     }
 6832: 
 6833:     return (0,$currentphase+1);
 6834: }
 6835: 
 6836: 
 6837: 
 6838: sub scantron_validate_ID {
 6839:     my ($r,$currentphase) = @_;
 6840:     
 6841:     #get student info
 6842:     my $classlist=&Apache::loncoursedata::get_classlist();
 6843:     my %idmap=&username_to_idmap($classlist);
 6844: 
 6845:     #get scantron line setup
 6846:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6847:     my ($scanlines,$scan_data)=&scantron_getfile();
 6848: 
 6849:     my $nav_error;
 6850:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6851:     if ($nav_error) {
 6852:         $r->print(&navmap_errormsg());
 6853:         return(1,$currentphase);
 6854:     }
 6855: 
 6856:     my %found=('ids'=>{},'usernames'=>{});
 6857:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6858: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6859: 	if ($line=~/^[\s\cz]*$/) { next; }
 6860: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6861: 						 $scan_data);
 6862: 	my $id=$$scan_record{'scantron.ID'};
 6863: 	my $found;
 6864: 	foreach my $checkid (keys(%idmap)) {
 6865: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6866: 	}
 6867: 	if ($found) {
 6868: 	    my $username=$idmap{$found};
 6869: 	    if ($found{'ids'}{$found}) {
 6870: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6871: 					 $line,'duplicateID',$found);
 6872: 		return(1,$currentphase);
 6873: 	    } elsif ($found{'usernames'}{$username}) {
 6874: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6875: 					 $line,'duplicateID',$username);
 6876: 		return(1,$currentphase);
 6877: 	    }
 6878: 	    #FIXME store away line we previously saw the ID on to use above
 6879: 	    $found{'ids'}{$found}++;
 6880: 	    $found{'usernames'}{$username}++;
 6881: 	} else {
 6882: 	    if ($id =~ /^\s*$/) {
 6883: 		my $username=&scan_data($scan_data,"$i.user");
 6884: 		if (defined($username) && $found{'usernames'}{$username}) {
 6885: 		    &scantron_get_correction($r,$i,$scan_record,
 6886: 					     \%scantron_config,
 6887: 					     $line,'duplicateID',$username);
 6888: 		    return(1,$currentphase);
 6889: 		} elsif (!defined($username)) {
 6890: 		    &scantron_get_correction($r,$i,$scan_record,
 6891: 					     \%scantron_config,
 6892: 					     $line,'incorrectID');
 6893: 		    return(1,$currentphase);
 6894: 		}
 6895: 		$found{'usernames'}{$username}++;
 6896: 	    } else {
 6897: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6898: 					 $line,'incorrectID');
 6899: 		return(1,$currentphase);
 6900: 	    }
 6901: 	}
 6902:     }
 6903: 
 6904:     return (0,$currentphase+1);
 6905: }
 6906: 
 6907: 
 6908: sub scantron_get_correction {
 6909:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6910: #FIXME in the case of a duplicated ID the previous line, probably need
 6911: #to show both the current line and the previous one and allow skipping
 6912: #the previous one or the current one
 6913: 
 6914:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6915: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6916: 			    " for PaperID <tt>[_1]</tt>",
 6917: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6918:     } else {
 6919: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6920: 			    " in scanline [_1] <pre>[_2]</pre>",
 6921: 			    $i,$line)."</p> \n");
 6922:     }
 6923:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6924: 			  "The name on the paper is [_2],[_3]",
 6925: 			  $$scan_record{'scantron.ID'},
 6926: 			  $$scan_record{'scantron.LastName'},
 6927: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6928: 
 6929:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6930:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6931:                            # Array populated for doublebubble or
 6932:     my @lines_to_correct;  # missingbubble errors to build javascript
 6933:                            # to validate radio button checking   
 6934: 
 6935:     if ($error =~ /ID$/) {
 6936: 	if ($error eq 'incorrectID') {
 6937: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6938: 		      "</p>\n");
 6939: 	} elsif ($error eq 'duplicateID') {
 6940: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6941: 	}
 6942: 	$r->print($message);
 6943: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6944: 	$r->print("\n<ul><li> ");
 6945: 	#FIXME it would be nice if this sent back the user ID and
 6946: 	#could do partial userID matches
 6947: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6948: 				       'scantron_username','scantron_domain'));
 6949: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6950: 	$r->print("\n@".
 6951: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6952: 
 6953: 	$r->print('</li>');
 6954:     } elsif ($error =~ /CODE$/) {
 6955: 	if ($error eq 'incorrectCODE') {
 6956: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6957: 	} elsif ($error eq 'duplicateCODE') {
 6958: 	    $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");
 6959: 	}
 6960: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6961: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6962: 	$r->print($message);
 6963: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6964: 	$r->print("\n<br /> ");
 6965: 	my $i=0;
 6966: 	if ($error eq 'incorrectCODE' 
 6967: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6968: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6969: 	    if ($closest > 0) {
 6970: 		foreach my $testcode (@{$closest}) {
 6971: 		    my $checked='';
 6972: 		    if (!$i) { $checked=' checked="checked"'; }
 6973: 		    $r->print("
 6974:    <label>
 6975:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6976:        ".&mt("Use the similar CODE [_1] instead.",
 6977: 	    "<b><tt>".$testcode."</tt></b>")."
 6978:     </label>
 6979:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6980: 		    $r->print("\n<br />");
 6981: 		    $i++;
 6982: 		}
 6983: 	    }
 6984: 	}
 6985: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6986: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6987: 	    $r->print("
 6988:     <label>
 6989:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6990:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6991: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6992:     </label>");
 6993: 	    $r->print("\n<br />");
 6994: 	}
 6995: 
 6996: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6997: function change_radio(field) {
 6998:     var slct=document.scantronupload.scantron_CODE_resolution;
 6999:     var i;
 7000:     for (i=0;i<slct.length;i++) {
 7001:         if (slct[i].value==field) { slct[i].checked=true; }
 7002:     }
 7003: }
 7004: ENDSCRIPT
 7005: 	my $href="/adm/pickcode?".
 7006: 	   "form=".&escape("scantronupload").
 7007: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7008: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7009: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7010: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7011: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7012: 	    $r->print("
 7013:     <label>
 7014:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7015:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7016: 	     "<a target='_blank' href='$href'>","</a>")."
 7017:     </label> 
 7018:     ".&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\')" />'));
 7019: 	    $r->print("\n<br />");
 7020: 	}
 7021: 	$r->print("
 7022:     <label>
 7023:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7024:        ".&mt("Use [_1] as the CODE.",
 7025: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7026: 	$r->print("\n<br /><br />");
 7027:     } elsif ($error eq 'doublebubble') {
 7028: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7029: 
 7030: 	# The form field scantron_questions is acutally a list of line numbers.
 7031: 	# represented by this form so:
 7032: 
 7033: 	my $line_list = &questions_to_line_list($arg);
 7034: 
 7035: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7036: 		  $line_list.'" />');
 7037: 	$r->print($message);
 7038: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7039: 	foreach my $question (@{$arg}) {
 7040: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7041:                                                    $scan_record, $error);
 7042:             push(@lines_to_correct,@linenums);
 7043: 	}
 7044:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7045:     } elsif ($error eq 'missingbubble') {
 7046: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 7047: 	$r->print($message);
 7048: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7049: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7050: 
 7051: 	# The form field scantron_questions is actually a list of line numbers not
 7052: 	# a list of question numbers. Therefore:
 7053: 	#
 7054: 	
 7055: 	my $line_list = &questions_to_line_list($arg);
 7056: 
 7057: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7058: 		  $line_list.'" />');
 7059: 	foreach my $question (@{$arg}) {
 7060: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7061:                                                    $scan_record, $error);
 7062:             push(@lines_to_correct,@linenums);
 7063: 	}
 7064:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7065:     } else {
 7066: 	$r->print("\n<ul>");
 7067:     }
 7068:     $r->print("\n</li></ul>");
 7069: }
 7070: 
 7071: sub verify_bubbles_checked {
 7072:     my (@ansnums) = @_;
 7073:     my $ansnumstr = join('","',@ansnums);
 7074:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7075:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7076: function verify_bubble_radio(form) {
 7077:     var ansnumArray = new Array ("$ansnumstr");
 7078:     var need_bubble_count = 0;
 7079:     for (var i=0; i<ansnumArray.length; i++) {
 7080:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7081:             var bubble_picked = 0; 
 7082:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7083:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7084:                     bubble_picked = 1;
 7085:                 }
 7086:             }
 7087:             if (bubble_picked == 0) {
 7088:                 need_bubble_count ++;
 7089:             }
 7090:         }
 7091:     }
 7092:     if (need_bubble_count) {
 7093:         alert("$warning");
 7094:         return;
 7095:     }
 7096:     form.submit(); 
 7097: }
 7098: ENDSCRIPT
 7099:     return $output;
 7100: }
 7101: 
 7102: =pod
 7103: 
 7104: =item  questions_to_line_list
 7105: 
 7106: Converts a list of questions into a string of comma separated
 7107: line numbers in the answer sheet used by the questions.  This is
 7108: used to fill in the scantron_questions form field.
 7109: 
 7110:   Arguments:
 7111:      questions    - Reference to an array of questions.
 7112: 
 7113: =cut
 7114: 
 7115: 
 7116: sub questions_to_line_list {
 7117:     my ($questions) = @_;
 7118:     my @lines;
 7119: 
 7120:     foreach my $item (@{$questions}) {
 7121:         my $question = $item;
 7122:         my ($first,$count,$last);
 7123:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7124:             $question = $1;
 7125:             my $subquestion = $2;
 7126:             $first = $first_bubble_line{$question-1} + 1;
 7127:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7128:             my $subcount = 1;
 7129:             while ($subcount<$subquestion) {
 7130:                 $first += $subans[$subcount-1];
 7131:                 $subcount ++;
 7132:             }
 7133:             $count = $subans[$subquestion-1];
 7134:         } else {
 7135: 	    $first   = $first_bubble_line{$question-1} + 1;
 7136: 	    $count   = $bubble_lines_per_response{$question-1};
 7137:         }
 7138:         $last = $first+$count-1;
 7139:         push(@lines, ($first..$last));
 7140:     }
 7141:     return join(',', @lines);
 7142: }
 7143: 
 7144: =pod 
 7145: 
 7146: =item prompt_for_corrections
 7147: 
 7148: Prompts for a potentially multiline correction to the
 7149: user's bubbling (factors out common code from scantron_get_correction
 7150: for multi and missing bubble cases).
 7151: 
 7152:  Arguments:
 7153:    $r           - Apache request object.
 7154:    $question    - The question number to prompt for.
 7155:    $scan_config - The scantron file configuration hash.
 7156:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7157:    $error       - Type of error
 7158: 
 7159:  Implicit inputs:
 7160:    %bubble_lines_per_response   - Starting line numbers for each question.
 7161:                                   Numbered from 0 (but question numbers are from
 7162:                                   1.
 7163:    %first_bubble_line           - Starting bubble line for each question.
 7164:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7165:                                   type problems render as separate sub-questions, 
 7166:                                   in exam mode. This hash contains a 
 7167:                                   comma-separated list of the lines per 
 7168:                                   sub-question.
 7169:    %responsetype_per_response   - essayresponse, formularesponse,
 7170:                                   stringresponse, imageresponse, reactionresponse,
 7171:                                   and organicresponse type problem parts can have
 7172:                                   multiple lines per response if the weight
 7173:                                   assigned exceeds 10.  In this case, only
 7174:                                   one bubble per line is permitted, but more 
 7175:                                   than one line might contain bubbles, e.g.
 7176:                                   bubbling of: line 1 - J, line 2 - J, 
 7177:                                   line 3 - B would assign 22 points.  
 7178: 
 7179: =cut
 7180: 
 7181: sub prompt_for_corrections {
 7182:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7183:     my ($current_line,$lines);
 7184:     my @linenums;
 7185:     my $questionnum = $question;
 7186:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7187:         $question = $1;
 7188:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7189:         my $subquestion = $2;
 7190:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7191:         my $subcount = 1;
 7192:         while ($subcount<$subquestion) {
 7193:             $current_line += $subans[$subcount-1];
 7194:             $subcount ++;
 7195:         }
 7196:         $lines = $subans[$subquestion-1];
 7197:     } else {
 7198:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7199:         $lines        = $bubble_lines_per_response{$question-1};
 7200:     }
 7201:     if ($lines > 1) {
 7202:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7203:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7204:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7205:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7206:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7207:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7208:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7209:             $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 />');
 7210:         } else {
 7211:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7212:         }
 7213:     }
 7214:     for (my $i =0; $i < $lines; $i++) {
 7215:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7216: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7217: 	        		  $questionnum,$error,split('', $selected));
 7218:         push(@linenums,$current_line);
 7219: 	$current_line++;
 7220:     }
 7221:     if ($lines > 1) {
 7222: 	$r->print("<hr /><br />");
 7223:     }
 7224:     return @linenums;
 7225: }
 7226: 
 7227: =pod
 7228: 
 7229: =item scantron_bubble_selector
 7230:   
 7231:    Generates the html radiobuttons to correct a single bubble line
 7232:    possibly showing the existing the selected bubbles if known
 7233: 
 7234:  Arguments:
 7235:     $r           - Apache request object
 7236:     $scan_config - hash from &get_scantron_config()
 7237:     $line        - Number of the line being displayed.
 7238:     $questionnum - Question number (may include subquestion)
 7239:     $error       - Type of error.
 7240:     @selected    - Array of bubbles picked on this line.
 7241: 
 7242: =cut
 7243: 
 7244: sub scantron_bubble_selector {
 7245:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7246:     my $max=$$scan_config{'Qlength'};
 7247: 
 7248:     my $scmode=$$scan_config{'Qon'};
 7249:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7250: 
 7251:     my @alphabet=('A'..'Z');
 7252:     $r->print(&Apache::loncommon::start_data_table().
 7253:               &Apache::loncommon::start_data_table_row());
 7254:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7255:     for (my $i=0;$i<$max+1;$i++) {
 7256: 	$r->print("\n".'<td align="center">');
 7257: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7258: 	else { $r->print('&nbsp;'); }
 7259: 	$r->print('</td>');
 7260:     }
 7261:     $r->print(&Apache::loncommon::end_data_table_row().
 7262:               &Apache::loncommon::start_data_table_row());
 7263:     for (my $i=0;$i<$max;$i++) {
 7264: 	$r->print("\n".
 7265: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7266: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7267:     }
 7268:     my $nobub_checked = ' ';
 7269:     if ($error eq 'missingbubble') {
 7270:         $nobub_checked = ' checked = "checked" ';
 7271:     }
 7272:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7273: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7274:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7275:               $line.'" value="'.$questionnum.'" /></td>');
 7276:     $r->print(&Apache::loncommon::end_data_table_row().
 7277:               &Apache::loncommon::end_data_table());
 7278: }
 7279: 
 7280: =pod
 7281: 
 7282: =item num_matches
 7283: 
 7284:    Counts the number of characters that are the same between the two arguments.
 7285: 
 7286:  Arguments:
 7287:    $orig - CODE from the scanline
 7288:    $code - CODE to match against
 7289: 
 7290:  Returns:
 7291:    $count - integer count of the number of same characters between the
 7292:             two arguments
 7293: 
 7294: =cut
 7295: 
 7296: sub num_matches {
 7297:     my ($orig,$code) = @_;
 7298:     my @code=split(//,$code);
 7299:     my @orig=split(//,$orig);
 7300:     my $same=0;
 7301:     for (my $i=0;$i<scalar(@code);$i++) {
 7302: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7303:     }
 7304:     return $same;
 7305: }
 7306: 
 7307: =pod
 7308: 
 7309: =item scantron_get_closely_matching_CODEs
 7310: 
 7311:    Cycles through all CODEs and finds the set that has the greatest
 7312:    number of same characters as the provided CODE
 7313: 
 7314:  Arguments:
 7315:    $allcodes - hash ref returned by &get_codes()
 7316:    $CODE     - CODE from the current scanline
 7317: 
 7318:  Returns:
 7319:    2 element list
 7320:     - first elements is number of how closely matching the best fit is 
 7321:       (5 means best set has 5 matching characters)
 7322:     - second element is an arrary ref containing the set of valid CODEs
 7323:       that best fit the passed in CODE
 7324: 
 7325: =cut
 7326: 
 7327: sub scantron_get_closely_matching_CODEs {
 7328:     my ($allcodes,$CODE)=@_;
 7329:     my @CODEs;
 7330:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7331: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7332:     }
 7333: 
 7334:     return ($#CODEs,$CODEs[-1]);
 7335: }
 7336: 
 7337: =pod
 7338: 
 7339: =item get_codes
 7340: 
 7341:    Builds a hash which has keys of all of the valid CODEs from the selected
 7342:    set of remembered CODEs.
 7343: 
 7344:  Arguments:
 7345:   $old_name - name of the set of remembered CODEs
 7346:   $cdom     - domain of the course
 7347:   $cnum     - internal course name
 7348: 
 7349:  Returns:
 7350:   %allcodes - keys are the valid CODEs, values are all 1
 7351: 
 7352: =cut
 7353: 
 7354: sub get_codes {
 7355:     my ($old_name, $cdom, $cnum) = @_;
 7356:     if (!$old_name) {
 7357: 	$old_name=$env{'form.scantron_CODElist'};
 7358:     }
 7359:     if (!$cdom) {
 7360: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7361:     }
 7362:     if (!$cnum) {
 7363: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7364:     }
 7365:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7366: 				    $cdom,$cnum);
 7367:     my %allcodes;
 7368:     if ($result{"type\0$old_name"} eq 'number') {
 7369: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7370:     } else {
 7371: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7372:     }
 7373:     return %allcodes;
 7374: }
 7375: 
 7376: =pod
 7377: 
 7378: =item scantron_validate_CODE
 7379: 
 7380:    Validates all scanlines in the selected file to not have any
 7381:    invalid or underspecified CODEs and that none of the codes are
 7382:    duplicated if this was requested.
 7383: 
 7384: =cut
 7385: 
 7386: sub scantron_validate_CODE {
 7387:     my ($r,$currentphase) = @_;
 7388:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7389:     if ($scantron_config{'CODElocation'} &&
 7390: 	$scantron_config{'CODEstart'} &&
 7391: 	$scantron_config{'CODElength'}) {
 7392: 	if (!defined($env{'form.scantron_CODElist'})) {
 7393: 	    &FIXME_blow_up()
 7394: 	}
 7395:     } else {
 7396: 	return (0,$currentphase+1);
 7397:     }
 7398:     
 7399:     my %usedCODEs;
 7400: 
 7401:     my %allcodes=&get_codes();
 7402: 
 7403:     my $nav_error;
 7404:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7405:     if ($nav_error) {
 7406:         $r->print(&navmap_errormsg());
 7407:         return(1,$currentphase);
 7408:     }
 7409: 
 7410:     my ($scanlines,$scan_data)=&scantron_getfile();
 7411:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7412: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7413: 	if ($line=~/^[\s\cz]*$/) { next; }
 7414: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7415: 						 $scan_data);
 7416: 	my $CODE=$$scan_record{'scantron.CODE'};
 7417: 	my $error=0;
 7418: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7419: 	    &scantron_get_correction($r,$i,$scan_record,
 7420: 				     \%scantron_config,
 7421: 				     $line,'incorrectCODE',\%allcodes);
 7422: 	    return(1,$currentphase);
 7423: 	}
 7424: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7425: 	    && !$$scan_record{'scantron.useCODE'}) {
 7426: 	    &scantron_get_correction($r,$i,$scan_record,
 7427: 				     \%scantron_config,
 7428: 				     $line,'incorrectCODE',\%allcodes);
 7429: 	    return(1,$currentphase);
 7430: 	}
 7431: 	if (exists($usedCODEs{$CODE}) 
 7432: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7433: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7434: 	    &scantron_get_correction($r,$i,$scan_record,
 7435: 				     \%scantron_config,
 7436: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7437: 	    return(1,$currentphase);
 7438: 	}
 7439: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7440:     }
 7441:     return (0,$currentphase+1);
 7442: }
 7443: 
 7444: =pod
 7445: 
 7446: =item scantron_validate_doublebubble
 7447: 
 7448:    Validates all scanlines in the selected file to not have any
 7449:    bubble lines with multiple bubbles marked.
 7450: 
 7451: =cut
 7452: 
 7453: sub scantron_validate_doublebubble {
 7454:     my ($r,$currentphase) = @_;
 7455:     #get student info
 7456:     my $classlist=&Apache::loncoursedata::get_classlist();
 7457:     my %idmap=&username_to_idmap($classlist);
 7458: 
 7459:     #get scantron line setup
 7460:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7461:     my ($scanlines,$scan_data)=&scantron_getfile();
 7462:     my $nav_error;
 7463:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7464:     if ($nav_error) {
 7465:         $r->print(&navmap_errormsg());
 7466:         return(1,$currentphase);
 7467:     }
 7468: 
 7469:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7470: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7471: 	if ($line=~/^[\s\cz]*$/) { next; }
 7472: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7473: 						 $scan_data);
 7474: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7475: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7476: 				 'doublebubble',
 7477: 				 $$scan_record{'scantron.doubleerror'});
 7478:     	return (1,$currentphase);
 7479:     }
 7480:     return (0,$currentphase+1);
 7481: }
 7482: 
 7483: 
 7484: sub scantron_get_maxbubble {
 7485:     my ($nav_error) = @_;
 7486:     if (defined($env{'form.scantron_maxbubble'}) &&
 7487: 	$env{'form.scantron_maxbubble'}) {
 7488: 	&restore_bubble_lines();
 7489: 	return $env{'form.scantron_maxbubble'};
 7490:     }
 7491: 
 7492:     my (undef, undef, $sequence) =
 7493: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7494: 
 7495:     my $navmap=Apache::lonnavmaps::navmap->new();
 7496:     unless (ref($navmap)) {
 7497:         if (ref($nav_error)) {
 7498:             $$nav_error = 1;
 7499:         }
 7500:         return;
 7501:     }
 7502:     my $map=$navmap->getResourceByUrl($sequence);
 7503:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7504: 
 7505:     &Apache::lonxml::clear_problem_counter();
 7506: 
 7507:     my $uname       = $env{'user.name'};
 7508:     my $udom        = $env{'user.domain'};
 7509:     my $cid         = $env{'request.course.id'};
 7510:     my $total_lines = 0;
 7511:     %bubble_lines_per_response = ();
 7512:     %first_bubble_line         = ();
 7513:     %subdivided_bubble_lines   = ();
 7514:     %responsetype_per_response = ();
 7515: 
 7516:     my $response_number = 0;
 7517:     my $bubble_line     = 0;
 7518:     foreach my $resource (@resources) {
 7519:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7520:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7521: 	    foreach my $part_id (@{$parts}) {
 7522:                 my $lines;
 7523: 
 7524: 	        # TODO - make this a persistent hash not an array.
 7525: 
 7526:                 # optionresponse, matchresponse and rankresponse type items 
 7527:                 # render as separate sub-questions in exam mode.
 7528:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7529:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7530:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7531:                     my ($numbub,$numshown);
 7532:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7533:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7534:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7535:                         }
 7536:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7537:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7538:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7539:                         }
 7540:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7541:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7542:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7543:                         }
 7544:                     }
 7545:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7546:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7547:                     }
 7548:                     my $bubbles_per_line = 10;
 7549:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7550:                     if (($numbub % $bubbles_per_line) != 0) {
 7551:                         $inner_bubble_lines++;
 7552:                     }
 7553:                     for (my $i=0; $i<$numshown; $i++) {
 7554:                         $subdivided_bubble_lines{$response_number} .= 
 7555:                             $inner_bubble_lines.',';
 7556:                     }
 7557:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7558:                     $lines = $numshown * $inner_bubble_lines;
 7559:                 } else {
 7560:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7561:                 } 
 7562: 
 7563:                 $first_bubble_line{$response_number} = $bubble_line;
 7564: 	        $bubble_lines_per_response{$response_number} = $lines;
 7565:                 $responsetype_per_response{$response_number} = 
 7566:                     $analysis->{$part_id.'.type'};
 7567: 	        $response_number++;
 7568: 
 7569: 	        $bubble_line +=  $lines;
 7570: 	        $total_lines +=  $lines;
 7571: 	    }
 7572:         }
 7573:     }
 7574:     &Apache::lonnet::delenv('scantron.');
 7575: 
 7576:     &save_bubble_lines();
 7577:     $env{'form.scantron_maxbubble'} =
 7578: 	$total_lines;
 7579:     return $env{'form.scantron_maxbubble'};
 7580: }
 7581: 
 7582: sub scantron_validate_missingbubbles {
 7583:     my ($r,$currentphase) = @_;
 7584:     #get student info
 7585:     my $classlist=&Apache::loncoursedata::get_classlist();
 7586:     my %idmap=&username_to_idmap($classlist);
 7587: 
 7588:     #get scantron line setup
 7589:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7590:     my ($scanlines,$scan_data)=&scantron_getfile();
 7591:     my $nav_error;
 7592:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7593:     if ($nav_error) {
 7594:         return(1,$currentphase);
 7595:     }
 7596:     if (!$max_bubble) { $max_bubble=2**31; }
 7597:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7598: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7599: 	if ($line=~/^[\s\cz]*$/) { next; }
 7600: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7601: 						 $scan_data);
 7602: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7603: 	my @to_correct;
 7604: 	
 7605: 	# Probably here's where the error is...
 7606: 
 7607: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7608:             my $lastbubble;
 7609:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7610:                my $question = $1;
 7611:                my $subquestion = $2;
 7612:                if (!defined($first_bubble_line{$question -1})) { next; }
 7613:                my $first = $first_bubble_line{$question-1};
 7614:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7615:                my $subcount = 1;
 7616:                while ($subcount<$subquestion) {
 7617:                    $first += $subans[$subcount-1];
 7618:                    $subcount ++;
 7619:                }
 7620:                my $count = $subans[$subquestion-1];
 7621:                $lastbubble = $first + $count;
 7622:             } else {
 7623:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7624:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7625:             }
 7626:             if ($lastbubble > $max_bubble) { next; }
 7627: 	    push(@to_correct,$missing);
 7628: 	}
 7629: 	if (@to_correct) {
 7630: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7631: 				     $line,'missingbubble',\@to_correct);
 7632: 	    return (1,$currentphase);
 7633: 	}
 7634: 
 7635:     }
 7636:     return (0,$currentphase+1);
 7637: }
 7638: 
 7639: 
 7640: sub scantron_process_students {
 7641:     my ($r) = @_;
 7642: 
 7643:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7644:     my ($symb)=&get_symb($r);
 7645:     if (!$symb) {
 7646: 	return '';
 7647:     }
 7648:     my $default_form_data=&defaultFormData($symb);
 7649: 
 7650:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7651:     my ($scanlines,$scan_data)=&scantron_getfile();
 7652:     my $classlist=&Apache::loncoursedata::get_classlist();
 7653:     my %idmap=&username_to_idmap($classlist);
 7654:     my $navmap=Apache::lonnavmaps::navmap->new();
 7655:     unless (ref($navmap)) {
 7656:         $r->print(&navmap_errormsg());
 7657:         return '';
 7658:     }  
 7659:     my $map=$navmap->getResourceByUrl($sequence);
 7660:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7661:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7662:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7663:                             \%grader_randomlists_by_symb);
 7664:     my $resource_error;
 7665:     foreach my $resource (@resources) {
 7666:         my $ressymb;
 7667:         if (ref($resource)) {
 7668:             $ressymb = $resource->symb();
 7669:         } else {
 7670:             $resource_error = 1;
 7671:             last;
 7672:         }
 7673:         my ($analysis,$parts) =
 7674:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7675:                                       $env{'user.name'},$env{'user.domain'},1);
 7676:         $grader_partids_by_symb{$ressymb} = $parts;
 7677:         if (ref($analysis) eq 'HASH') {
 7678:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7679:                 $grader_randomlists_by_symb{$ressymb} = 
 7680:                     $analysis->{'parts_withrandomlist'};
 7681:             }
 7682:         }
 7683:     }
 7684:     if ($resource_error) {
 7685:         $r->print(&navmap_errormsg());
 7686:         return '';
 7687:     }
 7688: 
 7689:     my ($uname,$udom);
 7690:     my $result= <<SCANTRONFORM;
 7691: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7692:   <input type="hidden" name="command" value="scantron_configphase" />
 7693:   $default_form_data
 7694: SCANTRONFORM
 7695:     $r->print($result);
 7696: 
 7697:     my @delayqueue;
 7698:     my (%completedstudents,%scandata);
 7699:     
 7700:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7701:     my $count=&get_todo_count($scanlines,$scan_data);
 7702:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7703:  				    'Bubblesheet Progress',$count,
 7704: 				    'inline',undef,'scantronupload');
 7705:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7706: 					  'Processing first student');
 7707:     $r->print('<br />');
 7708:     my $start=&Time::HiRes::time();
 7709:     my $i=-1;
 7710:     my $started;
 7711: 
 7712:     my $nav_error;
 7713:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7714:     if ($nav_error) {
 7715:         $r->print(&navmap_errormsg());
 7716:         return '';
 7717:     }
 7718: 
 7719:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7720:     # the user and return.
 7721: 
 7722:     if ($ssi_error) {
 7723: 	$r->print("</form>");
 7724: 	&ssi_print_error($r);
 7725: 	$r->print(&show_grading_menu_form($symb));
 7726:         &Apache::lonnet::remove_lock($lock);
 7727: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7728:     }
 7729: 
 7730:     my %lettdig = &letter_to_digits();
 7731:     my $numletts = scalar(keys(%lettdig));
 7732: 
 7733:     while ($i<$scanlines->{'count'}) {
 7734:  	($uname,$udom)=('','');
 7735:  	$i++;
 7736:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7737:  	if ($line=~/^[\s\cz]*$/) { next; }
 7738: 	if ($started) {
 7739: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7740: 						     'last student');
 7741: 	}
 7742: 	$started=1;
 7743:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7744:  						 $scan_data);
 7745:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7746:  					      \%idmap,$i)) {
 7747:   	    &scantron_add_delay(\@delayqueue,$line,
 7748:  				'Unable to find a student that matches',1);
 7749:  	    next;
 7750:   	}
 7751:  	if (exists $completedstudents{$uname}) {
 7752:  	    &scantron_add_delay(\@delayqueue,$line,
 7753:  				'Student '.$uname.' has multiple sheets',2);
 7754:  	    next;
 7755:  	}
 7756:   	($uname,$udom)=split(/:/,$uname);
 7757: 
 7758:         my (%partids_by_symb,$res_error);
 7759:         foreach my $resource (@resources) {
 7760:             my $ressymb;
 7761:             if (ref($resource)) {
 7762:                 $ressymb = $resource->symb();
 7763:             } else {
 7764:                 $res_error = 1;
 7765:                 last;
 7766:             }
 7767:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7768:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7769:                 my ($analysis,$parts) =
 7770:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7771:                 $partids_by_symb{$ressymb} = $parts;
 7772:             } else {
 7773:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7774:             }
 7775:         }
 7776: 
 7777:         if ($res_error) {
 7778:             &scantron_add_delay(\@delayqueue,$line,
 7779:                                 'An error occurred while grading student '.$uname,2);
 7780:             next;
 7781:         }
 7782: 
 7783: 	&Apache::lonxml::clear_problem_counter();
 7784:   	&Apache::lonnet::appenv($scan_record);
 7785: 
 7786: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7787: 	    &scantron_putfile($scanlines,$scan_data);
 7788: 	}
 7789: 	
 7790:         my $scancode;
 7791:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7792:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7793:             $scancode = $scan_record->{'scantron.CODE'};
 7794:         } else {
 7795:             $scancode = '';
 7796:         }
 7797: 
 7798:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7799:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7800:             $ssi_error = 0; # So end of handler error message does not trigger.
 7801:             $r->print("</form>");
 7802:             &ssi_print_error($r);
 7803:             $r->print(&show_grading_menu_form($symb));
 7804:             &Apache::lonnet::remove_lock($lock);
 7805:             return '';      # Why return ''?  Beats me.
 7806:         }
 7807: 
 7808: 	$completedstudents{$uname}={'line'=>$line};
 7809:         if ($env{'form.verifyrecord'}) {
 7810:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7811:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7812:             chomp($studentdata);
 7813:             $studentdata =~ s/\r$//;
 7814:             my $studentrecord = '';
 7815:             my $counter = -1;
 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:                 &Apache::lonxml::clear_problem_counter();
 7826:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7827:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7828:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7829:                     $r->print("</form>");
 7830:                     &ssi_print_error($r);
 7831:                     $r->print(&show_grading_menu_form($symb));
 7832:                     &Apache::lonnet::remove_lock($lock);
 7833:                     delete($completedstudents{$uname});
 7834:                     return '';
 7835:                 }
 7836:                 $counter = -1;
 7837:                 $studentrecord = '';
 7838:                 foreach my $resource (@resources) {
 7839:                     my $ressymb = $resource->symb();
 7840:                     ($counter,my $recording) =
 7841:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7842:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7843:                                                  \%scantron_config,\%lettdig,$numletts);
 7844:                     $studentrecord .= $recording;
 7845:                 }
 7846:                 if ($studentrecord ne $studentdata) {
 7847:                     $r->print('<p><span class="LC_error">');
 7848:                     if ($scancode eq '') {
 7849:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7850:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7851:                     } else {
 7852:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7853:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7854:                     }
 7855:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7856:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7857:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7858:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7859:                               &Apache::loncommon::start_data_table_row().
 7860:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7861:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7862:                               &Apache::loncommon::end_data_table_row().
 7863:                               &Apache::loncommon::start_data_table_row().
 7864:                               '<td>Stored submissions</td>'.
 7865:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7866:                               &Apache::loncommon::end_data_table_row().
 7867:                               &Apache::loncommon::end_data_table().'</p>');
 7868:                 } else {
 7869:                     $r->print('<br /><span class="LC_warning">'.
 7870:                              &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 />'.
 7871:                              &mt("As a consequence, this user's submission history records two tries.").
 7872:                                  '</span><br />');
 7873:                 }
 7874:             }
 7875:         }
 7876:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7877:     } continue {
 7878: 	&Apache::lonxml::clear_problem_counter();
 7879: 	&Apache::lonnet::delenv('scantron.');
 7880:     }
 7881:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7882:     &Apache::lonnet::remove_lock($lock);
 7883: #    my $lasttime = &Time::HiRes::time()-$start;
 7884: #    $r->print("<p>took $lasttime</p>");
 7885: 
 7886:     $r->print("</form>");
 7887:     $r->print(&show_grading_menu_form($symb));
 7888:     return '';
 7889: }
 7890: 
 7891: sub graders_resources_pass {
 7892:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7893:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7894:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7895:         foreach my $resource (@{$resources}) {
 7896:             my $ressymb = $resource->symb();
 7897:             my ($analysis,$parts) =
 7898:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7899:                                           $env{'user.name'},$env{'user.domain'},1);
 7900:             $grader_partids_by_symb->{$ressymb} = $parts;
 7901:             if (ref($analysis) eq 'HASH') {
 7902:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7903:                     $grader_randomlists_by_symb->{$ressymb} =
 7904:                         $analysis->{'parts_withrandomlist'};
 7905:                 }
 7906:             }
 7907:         }
 7908:     }
 7909:     return;
 7910: }
 7911: 
 7912: sub grade_student_bubbles {
 7913:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7914:     if (ref($resources) eq 'ARRAY') {
 7915:         my $count = 0;
 7916:         foreach my $resource (@{$resources}) {
 7917:             my $ressymb = $resource->symb();
 7918:             my %form = ('submitted'      => 'scantron',
 7919:                         'grade_target'   => 'grade',
 7920:                         'grade_username' => $uname,
 7921:                         'grade_domain'   => $udom,
 7922:                         'grade_courseid' => $env{'request.course.id'},
 7923:                         'grade_symb'     => $ressymb,
 7924:                         'CODE'           => $scancode
 7925:                        );
 7926:             if (ref($parts) eq 'HASH') {
 7927:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7928:                     foreach my $part (@{$parts->{$ressymb}}) {
 7929:                         $form{'scantron_questnum_start.'.$part} =
 7930:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7931:                         $count++;
 7932:                     }
 7933:                 }
 7934:             }
 7935:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7936:             return 'ssi_error' if ($ssi_error);
 7937:             last if (&Apache::loncommon::connection_aborted($r));
 7938:         }
 7939:     }
 7940:     return;
 7941: }
 7942: 
 7943: sub scantron_upload_scantron_data {
 7944:     my ($r)=@_;
 7945:     my $dom = $env{'request.role.domain'};
 7946:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7947:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7948:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7949: 							  'domainid',
 7950: 							  'coursename',$dom);
 7951:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7952:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7953:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7954:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7955:     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.");
 7956:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7957:     function checkUpload(formname) {
 7958: 	if (formname.upfile.value == "") {
 7959: 	    alert("'.$nofile_alert.'");
 7960: 	    return false;
 7961: 	}
 7962:         if (formname.courseid.value == "") {
 7963:             alert("'.$nocourseid_alert.'");
 7964:             return false;
 7965:         }
 7966: 	formname.submit();
 7967:     }
 7968: 
 7969:     function ToSyllabus() {
 7970:         var cdom = '."'$dom'".';
 7971:         var cnum = document.rules.courseid.value;
 7972:         if (cdom == "" || cdom == null) {
 7973:             return;
 7974:         }
 7975:         if (cnum == "" || cnum == null) {
 7976:            return;
 7977:         }
 7978:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7979:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7980:         return;
 7981:     }
 7982: 
 7983: '));
 7984:     $r->print('
 7985: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7986: 
 7987: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7988: '.$default_form_data.
 7989:   &Apache::lonhtmlcommon::start_pick_box().
 7990:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7991:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7992:   &Apache::lonhtmlcommon::row_closure().
 7993:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7994:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7995:   &Apache::lonhtmlcommon::row_closure().
 7996:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7997:   '<input name="domainid" type="hidden" />'.$domdesc.
 7998:   &Apache::lonhtmlcommon::row_closure().
 7999:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8000:   '<input type="file" name="upfile" size="50" />'.
 8001:   &Apache::lonhtmlcommon::row_closure(1).
 8002:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8003: 
 8004: <input name="command" value="scantronupload_save" type="hidden" />
 8005: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8006: </form>
 8007: ');
 8008:     return '';
 8009: }
 8010: 
 8011: 
 8012: sub scantron_upload_scantron_data_save {
 8013:     my($r)=@_;
 8014:     my ($symb)=&get_symb($r,1);
 8015:     my $doanotherupload=
 8016: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8017: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8018: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8019: 	'</form>'."\n";
 8020:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8021: 	!&Apache::lonnet::allowed('usc',
 8022: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8023: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8024: 	if ($symb) {
 8025: 	    $r->print(&show_grading_menu_form($symb));
 8026: 	} else {
 8027: 	    $r->print($doanotherupload);
 8028: 	}
 8029: 	return '';
 8030:     }
 8031:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8032:     my $uploadedfile;
 8033:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8034:     if (length($env{'form.upfile'}) < 2) {
 8035:         $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>'));
 8036:     } else {
 8037:         my $result = 
 8038:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8039:                                             $env{'form.courseid'},$env{'form.domainid'});
 8040: 	if ($result =~ m{^/uploaded/}) {
 8041: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8042:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8043: 			  '<span class="LC_filename">'.$result.'</span>'));
 8044:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8045:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8046:                                                        $env{'form.courseid'},$uploadedfile));
 8047: 	} else {
 8048: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8049:                           '<span class="LC_error">','</span>',$result,
 8050: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8051: 	}
 8052:     }
 8053:     if ($symb) {
 8054: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8055:     } else {
 8056: 	$r->print($doanotherupload);
 8057:     }
 8058:     return '';
 8059: }
 8060: 
 8061: sub validate_uploaded_scantron_file {
 8062:     my ($cdom,$cname,$fname) = @_;
 8063:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8064:     my @lines;
 8065:     if ($scanlines ne '-1') {
 8066:         @lines=split("\n",$scanlines,-1);
 8067:     }
 8068:     my $output;
 8069:     if (@lines) {
 8070:         my (%counts,$max_match_format);
 8071:         my ($max_match_count,$max_match_pct) = (0,0);
 8072:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8073:         my %idmap = &username_to_idmap($classlist);
 8074:         foreach my $key (keys(%idmap)) {
 8075:             my $lckey = lc($key);
 8076:             $idmap{$lckey} = $idmap{$key};
 8077:         }
 8078:         my %unique_formats;
 8079:         my @formatlines = &get_scantronformat_file();
 8080:         foreach my $line (@formatlines) {
 8081:             chomp($line);
 8082:             my @config = split(/:/,$line);
 8083:             my $idstart = $config[5];
 8084:             my $idlength = $config[6];
 8085:             if (($idstart ne '') && ($idlength > 0)) {
 8086:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8087:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8088:                 } else {
 8089:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8090:                 }
 8091:             }
 8092:         }
 8093:         foreach my $key (keys(%unique_formats)) {
 8094:             my ($idstart,$idlength) = split(':',$key);
 8095:             %{$counts{$key}} = (
 8096:                                'found'   => 0,
 8097:                                'total'   => 0,
 8098:                               );
 8099:             foreach my $line (@lines) {
 8100:                 next if ($line =~ /^#/);
 8101:                 next if ($line =~ /^[\s\cz]*$/);
 8102:                 my $id = substr($line,$idstart-1,$idlength);
 8103:                 $id = lc($id);
 8104:                 if (exists($idmap{$id})) {
 8105:                     $counts{$key}{'found'} ++;
 8106:                 }
 8107:                 $counts{$key}{'total'} ++;
 8108:             }
 8109:             if ($counts{$key}{'total'}) {
 8110:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8111:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8112:                     $max_match_pct = $percent_match;
 8113:                     $max_match_format = $key;
 8114:                     $max_match_count = $counts{$key}{'total'};
 8115:                 }
 8116:             }
 8117:         }
 8118:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8119:             my $format_descs;
 8120:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8121:             for (my $i=0; $i<$numwithformat; $i++) {
 8122:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8123:                 if ($i<$numwithformat-2) {
 8124:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8125:                 } elsif ($i==$numwithformat-2) {
 8126:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8127:                 } elsif ($i==$numwithformat-1) {
 8128:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8129:                 }
 8130:             }
 8131:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8132:             $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).
 8133:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8134:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8135:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8136:                                   '<i>'.$cdom.'</i>').'</li>'.
 8137:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8138:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8139:                        '</ul>';
 8140:         }
 8141:     } else {
 8142:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8143:     }
 8144:     return $output;
 8145: }
 8146: 
 8147: sub valid_file {
 8148:     my ($requested_file)=@_;
 8149:     foreach my $filename (sort(&scantron_filenames())) {
 8150: 	if ($requested_file eq $filename) { return 1; }
 8151:     }
 8152:     return 0;
 8153: }
 8154: 
 8155: sub scantron_download_scantron_data {
 8156:     my ($r)=@_;
 8157:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8158:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8159:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8160:     my $file=$env{'form.scantron_selectfile'};
 8161:     if (! &valid_file($file)) {
 8162: 	$r->print('
 8163: 	<p>
 8164: 	    '.&mt('The requested file name was invalid.').'
 8165:         </p>
 8166: ');
 8167: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8168: 	return;
 8169:     }
 8170:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8171:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8172:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8173:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8174:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8175:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8176:     $r->print('
 8177:     <p>
 8178: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8179: 	      '<a href="'.$orig.'">','</a>').'
 8180:     </p>
 8181:     <p>
 8182: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8183: 	      '<a href="'.$corrected.'">','</a>').'
 8184:     </p>
 8185:     <p>
 8186: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8187: 	      '<a href="'.$skipped.'">','</a>').'
 8188:     </p>
 8189: ');
 8190:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8191:     return '';
 8192: }
 8193: 
 8194: sub checkscantron_results {
 8195:     my ($r) = @_;
 8196:     my ($symb)=&get_symb($r);
 8197:     if (!$symb) {return '';}
 8198:     my $grading_menu_button=&show_grading_menu_form($symb);
 8199:     my $cid = $env{'request.course.id'};
 8200:     my %lettdig = &letter_to_digits();
 8201:     my $numletts = scalar(keys(%lettdig));
 8202:     my $cnum = $env{'course.'.$cid.'.num'};
 8203:     my $cdom = $env{'course.'.$cid.'.domain'};
 8204:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8205:     my %record;
 8206:     my %scantron_config =
 8207:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8208:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8209:     my $classlist=&Apache::loncoursedata::get_classlist();
 8210:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8211:     my $navmap=Apache::lonnavmaps::navmap->new();
 8212:     unless (ref($navmap)) {
 8213:         $r->print(&navmap_errormsg());
 8214:         return '';
 8215:     }
 8216:     my $map=$navmap->getResourceByUrl($sequence);
 8217:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8218:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8219:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8220: 
 8221:     my ($uname,$udom);
 8222:     my (%scandata,%lastname,%bylast);
 8223:     $r->print('
 8224: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8225: 
 8226:     my @delayqueue;
 8227:     my %completedstudents;
 8228: 
 8229:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8230:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8231:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8232:                                     'inline',undef,'checkscantron');
 8233:     my ($username,$domain,$started);
 8234:     my $nav_error;
 8235:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8236:     if ($nav_error) {
 8237:         $r->print(&navmap_errormsg());
 8238:         return '';
 8239:     }
 8240: 
 8241:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8242:                                           'Processing first student');
 8243:     my $start=&Time::HiRes::time();
 8244:     my $i=-1;
 8245: 
 8246:     while ($i<$scanlines->{'count'}) {
 8247:         ($username,$domain,$uname)=('','','');
 8248:         $i++;
 8249:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8250:         if ($line=~/^[\s\cz]*$/) { next; }
 8251:         if ($started) {
 8252:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8253:                                                      'last student');
 8254:         }
 8255:         $started=1;
 8256:         my $scan_record=
 8257:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8258:                                                      $scan_data);
 8259:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8260:                                                               \%idmap,$i)) {
 8261:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8262:                                 'Unable to find a student that matches',1);
 8263:             next;
 8264:         }
 8265:         if (exists $completedstudents{$uname}) {
 8266:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8267:                                 'Student '.$uname.' has multiple sheets',2);
 8268:             next;
 8269:         }
 8270:         my $pid = $scan_record->{'scantron.ID'};
 8271:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8272:         push(@{$bylast{$lastname{$pid}}},$pid);
 8273:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8274:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8275:         chomp($scandata{$pid});
 8276:         $scandata{$pid} =~ s/\r$//;
 8277:         ($username,$domain)=split(/:/,$uname);
 8278:         my $counter = -1;
 8279:         foreach my $resource (@resources) {
 8280:             my $parts;
 8281:             my $ressymb = $resource->symb();
 8282:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8283:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8284:                 (my $analysis,$parts) =
 8285:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8286:             } else {
 8287:                 $parts = $grader_partids_by_symb{$ressymb};
 8288:             }
 8289:             ($counter,my $recording) =
 8290:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8291:                                          $scandata{$pid},$parts,
 8292:                                          \%scantron_config,\%lettdig,$numletts);
 8293:             $record{$pid} .= $recording;
 8294:         }
 8295:     }
 8296:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8297:     $r->print('<br />');
 8298:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8299:     $passed = 0;
 8300:     $failed = 0;
 8301:     $numstudents = 0;
 8302:     foreach my $last (sort(keys(%bylast))) {
 8303:         if (ref($bylast{$last}) eq 'ARRAY') {
 8304:             foreach my $pid (sort(@{$bylast{$last}})) {
 8305:                 my $showscandata = $scandata{$pid};
 8306:                 my $showrecord = $record{$pid};
 8307:                 $showscandata =~ s/\s/&nbsp;/g;
 8308:                 $showrecord =~ s/\s/&nbsp;/g;
 8309:                 if ($scandata{$pid} eq $record{$pid}) {
 8310:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8311:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8312: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8313: '</tr>'."\n".
 8314: '<tr class="'.$css_class.'">'."\n".
 8315: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8316:                     $passed ++;
 8317:                 } else {
 8318:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8319:                     $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".
 8320: '</tr>'."\n".
 8321: '<tr class="'.$css_class.'">'."\n".
 8322: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8323: '</tr>'."\n";
 8324:                     $failed ++;
 8325:                 }
 8326:                 $numstudents ++;
 8327:             }
 8328:         }
 8329:     }
 8330:     $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>');
 8331:     $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>');
 8332:     if ($passed) {
 8333:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8334:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8335:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8336:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8337:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8338:                  $okstudents."\n".
 8339:                  &Apache::loncommon::end_data_table().'<br />');
 8340:     }
 8341:     if ($failed) {
 8342:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8343:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8344:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8345:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8346:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8347:                  $badstudents."\n".
 8348:                  &Apache::loncommon::end_data_table()).'<br />'.
 8349:                  &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.');  
 8350:     }
 8351:     $r->print('</form><br />'.$grading_menu_button);
 8352:     return;
 8353: }
 8354: 
 8355: sub verify_scantron_grading {
 8356:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8357:         $scantron_config,$lettdig,$numletts) = @_;
 8358:     my ($record,%expected,%startpos);
 8359:     return ($counter,$record) if (!ref($resource));
 8360:     return ($counter,$record) if (!$resource->is_problem());
 8361:     my $symb = $resource->symb();
 8362:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8363:     foreach my $part_id (@{$partids}) {
 8364:         $counter ++;
 8365:         $expected{$part_id} = 0;
 8366:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8367:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8368:             foreach my $item (@sub_lines) {
 8369:                 $expected{$part_id} += $item;
 8370:             }
 8371:         } else {
 8372:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8373:         }
 8374:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8375:     }
 8376:     if ($symb) {
 8377:         my %recorded;
 8378:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8379:         if ($returnhash{'version'}) {
 8380:             my %lasthash=();
 8381:             my $version;
 8382:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8383:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8384:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8385:                 }
 8386:             }
 8387:             foreach my $key (keys(%lasthash)) {
 8388:                 if ($key =~ /\.scantron$/) {
 8389:                     my $value = &unescape($lasthash{$key});
 8390:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8391:                     if ($value eq '') {
 8392:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8393:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8394:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8395:                             }
 8396:                         }
 8397:                     } else {
 8398:                         my @tocheck;
 8399:                         my @items = split(//,$value);
 8400:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8401:                             ($scantron_config->{'Qon'} eq 'number')) {
 8402:                             if (@items < $expected{$part_id}) {
 8403:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8404:                                 my @singles = split(//,$fragment);
 8405:                                 foreach my $pos (@singles) {
 8406:                                     if ($pos eq ' ') {
 8407:                                         push(@tocheck,$pos);
 8408:                                     } else {
 8409:                                         my $next = shift(@items);
 8410:                                         push(@tocheck,$next);
 8411:                                     }
 8412:                                 }
 8413:                             } else {
 8414:                                 @tocheck = @items;
 8415:                             }
 8416:                             foreach my $letter (@tocheck) {
 8417:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8418:                                     if ($letter !~ /^[A-J]$/) {
 8419:                                         $letter = $scantron_config->{'Qoff'};
 8420:                                     }
 8421:                                     $recorded{$part_id} .= $letter;
 8422:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8423:                                     my $digit;
 8424:                                     if ($letter !~ /^[A-J]$/) {
 8425:                                         $digit = $scantron_config->{'Qoff'};
 8426:                                     } else {
 8427:                                         $digit = $lettdig->{$letter};
 8428:                                     }
 8429:                                     $recorded{$part_id} .= $digit;
 8430:                                 }
 8431:                             }
 8432:                         } else {
 8433:                             @tocheck = @items;
 8434:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8435:                                 my $curr_sub = shift(@tocheck);
 8436:                                 my $digit;
 8437:                                 if ($curr_sub =~ /^[A-J]$/) {
 8438:                                     $digit = $lettdig->{$curr_sub}-1;
 8439:                                 }
 8440:                                 if ($curr_sub eq 'J') {
 8441:                                     $digit += scalar($numletts);
 8442:                                 }
 8443:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8444:                                     if ($j == $digit) {
 8445:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8446:                                     } else {
 8447:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8448:                                     }
 8449:                                 }
 8450:                             }
 8451:                         }
 8452:                     }
 8453:                 }
 8454:             }
 8455:         }
 8456:         foreach my $part_id (@{$partids}) {
 8457:             if ($recorded{$part_id} eq '') {
 8458:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8459:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8460:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8461:                     }
 8462:                 }
 8463:             }
 8464:             $record .= $recorded{$part_id};
 8465:         }
 8466:     }
 8467:     return ($counter,$record);
 8468: }
 8469: 
 8470: sub letter_to_digits { 
 8471:     my %lettdig = (
 8472:                     A => 1,
 8473:                     B => 2,
 8474:                     C => 3,
 8475:                     D => 4,
 8476:                     E => 5,
 8477:                     F => 6,
 8478:                     G => 7,
 8479:                     H => 8,
 8480:                     I => 9,
 8481:                     J => 0,
 8482:                   );
 8483:     return %lettdig;
 8484: }
 8485: 
 8486: 
 8487: #-------- end of section for handling grading scantron forms -------
 8488: #
 8489: #-------------------------------------------------------------------
 8490: 
 8491: #-------------------------- Menu interface -------------------------
 8492: #
 8493: #--- Show a Grading Menu button - Calls the next routine ---
 8494: sub show_grading_menu_form {
 8495:     my ($symb)=@_;
 8496:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8497: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8498: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8499: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8500: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8501: 	'</form>'."\n";
 8502:     return $result;
 8503: }
 8504: 
 8505: # -- Retrieve choices for grading form
 8506: sub savedState {
 8507:     my %savedState = ();
 8508:     if ($env{'form.saveState'}) {
 8509: 	foreach (split(/:/,$env{'form.saveState'})) {
 8510: 	    my ($key,$value) = split(/=/,$_,2);
 8511: 	    $savedState{$key} = $value;
 8512: 	}
 8513:     }
 8514:     return \%savedState;
 8515: }
 8516: 
 8517: sub grading_menu {
 8518:     my ($request) = @_;
 8519:     my ($symb)=&get_symb($request);
 8520:     if (!$symb) {return '';}
 8521:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8522:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8523: 
 8524:     $request->print($table);
 8525:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8526:                   'handgrade'=>$hdgrade,
 8527:                   'probTitle'=>$probTitle,
 8528:                   'command'=>'submit_options',
 8529:                   'saveState'=>"",
 8530:                   'gradingMenu'=>1,
 8531:                   'showgrading'=>"yes");
 8532:     
 8533:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8534:     
 8535:     $fields{'command'} = 'csvform';
 8536:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8537:     
 8538:     $fields{'command'} = 'processclicker';
 8539:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8540:     
 8541:     $fields{'command'} = 'scantron_selectphase';
 8542:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8543:     
 8544:     my @menu = ({	categorytitle=>'Course Grading',
 8545:             items =>[
 8546:                         {	linktext => 'Manual Grading/View Submissions',
 8547:                     		url => $url1,
 8548:                     		permission => 'F',
 8549:                     		icon => 'edit-find-replace.png',
 8550:                     		linktitle => 'Start the process of hand grading submissions.'
 8551:                         },
 8552:                 	    {	linktext => 'Upload Scores',
 8553:                     		url => $url2,
 8554:                     		permission => 'F',
 8555:                     		icon => 'uploadscores.png',
 8556:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8557:                 	    },
 8558:                 	    {	linktext => 'Process Clicker',
 8559:                     		url => $url3,
 8560:                     		permission => 'F',
 8561:                     		icon => 'addClickerInfoFile.png',
 8562:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8563:                 	    },
 8564:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8565:                     		url => $url4,
 8566:                     		permission => 'F',
 8567:                     		icon => 'stat.png',
 8568:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8569:                 	    }
 8570:                     ]
 8571:             });
 8572: 
 8573:     #$fields{'command'} = 'verify';
 8574:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8575:     #
 8576:     # Create the menu
 8577:     my $Str;
 8578:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8579:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8580:     $Str .= '<input type="hidden" name="command" value="" />'.
 8581:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8582: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8583: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8584: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8585: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8586: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8587: 
 8588:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8589:     #$menudata->{'jscript'}
 8590:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 8591:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8592:         ' /> '.
 8593:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8594:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8595: 
 8596:     $Str .="</form>\n";
 8597:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8598:     $request->print(&Apache::lonhtmlcommon::scripttag(<<GRADINGMENUJS));
 8599:     function checkChoice(formname,val,cmdx) {
 8600: 	if (val <= 2) {
 8601: 	    var cmd = radioSelection(formname.radioChoice);
 8602: 	    var cmdsave = cmd;
 8603: 	} else {
 8604: 	    cmd = cmdx;
 8605: 	    cmdsave = 'submission';
 8606: 	}
 8607: 	formname.command.value = cmd;
 8608: 	if (val < 5) formname.submit();
 8609: 	if (val == 5) {
 8610: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8611: 	        return false;
 8612: 	    } else {
 8613: 	        formname.submit();
 8614: 	    }
 8615: 	}
 8616:     }
 8617: 
 8618:     function checkReceiptNo(formname,nospace) {
 8619: 	var receiptNo = formname.receipt.value;
 8620: 	var checkOpt = false;
 8621: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8622: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8623: 	if (checkOpt) {
 8624: 	    alert("$receiptalert");
 8625: 	    formname.receipt.value = "";
 8626: 	    formname.receipt.focus();
 8627: 	    return false;
 8628: 	}
 8629: 	return true;
 8630:     }
 8631: GRADINGMENUJS
 8632:     &commonJSfunctions($request);
 8633:     return $Str;    
 8634: }
 8635: 
 8636: 
 8637: #--- Displays the submissions first page -------
 8638: sub submit_options {
 8639:     my ($request) = @_;
 8640:     my ($symb)=&get_symb($request);
 8641:     if (!$symb) {return '';}
 8642:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8643: 
 8644:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8645:     $request->print(&Apache::lonhtmlcommon::scripttag(<<GRADINGMENUJS));
 8646:     function checkChoice(formname,val,cmdx) {
 8647: 	if (val <= 2) {
 8648: 	    var cmd = radioSelection(formname.radioChoice);
 8649: 	    var cmdsave = cmd;
 8650: 	} else {
 8651: 	    cmd = cmdx;
 8652: 	    cmdsave = 'submission';
 8653: 	}
 8654: 	formname.command.value = cmd;
 8655: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8656: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8657: 	if (val < 5) formname.submit();
 8658: 	if (val == 5) {
 8659: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8660: 	    formname.submit();
 8661: 	}
 8662: 	if (val < 7) formname.submit();
 8663:     }
 8664: 
 8665:     function checkReceiptNo(formname,nospace) {
 8666: 	var receiptNo = formname.receipt.value;
 8667: 	var checkOpt = false;
 8668: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8669: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8670: 	if (checkOpt) {
 8671: 	    alert("$receiptalert");
 8672: 	    formname.receipt.value = "";
 8673: 	    formname.receipt.focus();
 8674: 	    return false;
 8675: 	}
 8676: 	return true;
 8677:     }
 8678: GRADINGMENUJS
 8679:     &commonJSfunctions($request);
 8680:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8681:     my $result;
 8682:     my (undef,$sections) = &getclasslist('all','0');
 8683:     my $savedState = &savedState();
 8684:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8685:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8686:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8687:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8688: 
 8689:     # Preselect sections
 8690:     my $selsec="";
 8691:     if (ref($sections)) {
 8692:         foreach my $section (sort(@$sections)) {
 8693:             $selsec.='<option value="'.$section.'" '.
 8694:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8695:         }
 8696:     }
 8697: 
 8698:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8699: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8700: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8701: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8702: 	'<input type="hidden" name="command"     value="" />'."\n".
 8703: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8704: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8705: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8706: 
 8707:     $result.='
 8708: <h2>
 8709:   '.&mt('Grade Current Resource').'
 8710: </h2>
 8711: <div>
 8712:   '.$table.'
 8713: </div>
 8714: 
 8715: <div class="LC_columnSection">
 8716:   
 8717:     <fieldset>
 8718:       <legend>
 8719:        '.&mt('Sections').'
 8720:       </legend>
 8721:       <select name="section" multiple="multiple" size="5">'."\n";
 8722:     $result.= $selsec;
 8723:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8724:     $result.='
 8725:     </fieldset>
 8726:   
 8727:     <fieldset>
 8728:       <legend>
 8729:         '.&mt('Groups').'
 8730:       </legend>
 8731:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8732:     </fieldset>
 8733:   
 8734:     <fieldset>
 8735:       <legend>
 8736:         '.&mt('Access Status').'
 8737:       </legend>
 8738:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8739:     </fieldset>
 8740:   
 8741:     <fieldset>
 8742:       <legend>
 8743:         '.&mt('Submission Status').'
 8744:       </legend>
 8745:       <select name="submitonly" size="5">
 8746: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8747: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8748: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8749: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8750:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8751:       </select>
 8752:     </fieldset>
 8753:   
 8754: </div>
 8755: 
 8756: <br />
 8757:           <div>
 8758:             <div>
 8759:               <label>
 8760:                 <input type="radio" name="radioChoice" value="submission" '.
 8761:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8762:              &mt('Select individual students to grade and view submissions.').'
 8763: 	      </label> 
 8764:             </div>
 8765:             <div>
 8766: 	      <label>
 8767:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8768:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8769:                     &mt('Grade all selected students in a grading table.').'
 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: 
 8777: 
 8778:         <h2>
 8779:          '.&mt('Grade Complete Folder for One Student').'
 8780:         </h2>
 8781:         <div>
 8782:             <div>
 8783:               <label>
 8784:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8785: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8786:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8787:               </label>
 8788:             </div>
 8789:             <div>
 8790: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8791:             </div>
 8792:         </div>
 8793:   </form>';
 8794:     $result .= &show_grading_menu_form($symb);
 8795:     return $result;
 8796: }
 8797: 
 8798: sub reset_perm {
 8799:     undef(%perm);
 8800: }
 8801: 
 8802: sub init_perm {
 8803:     &reset_perm();
 8804:     foreach my $test_perm ('vgr','mgr','opa') {
 8805: 
 8806: 	my $scope = $env{'request.course.id'};
 8807: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8808: 
 8809: 	    $scope .= '/'.$env{'request.course.sec'};
 8810: 	    if ( $perm{$test_perm}=
 8811: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8812: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8813: 	    } else {
 8814: 		delete($perm{$test_perm});
 8815: 	    }
 8816: 	}
 8817:     }
 8818: }
 8819: 
 8820: sub gather_clicker_ids {
 8821:     my %clicker_ids;
 8822: 
 8823:     my $classlist = &Apache::loncoursedata::get_classlist();
 8824: 
 8825:     # Set up a couple variables.
 8826:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8827:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8828:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8829: 
 8830:     foreach my $student (keys(%$classlist)) {
 8831:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8832:         my $username = $classlist->{$student}->[$username_idx];
 8833:         my $domain   = $classlist->{$student}->[$domain_idx];
 8834:         my $clickers =
 8835: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8836:         foreach my $id (split(/\,/,$clickers)) {
 8837:             $id=~s/^[\#0]+//;
 8838:             $id=~s/[\-\:]//g;
 8839:             if (exists($clicker_ids{$id})) {
 8840: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8841:             } else {
 8842: 		$clicker_ids{$id}=$username.':'.$domain;
 8843:             }
 8844:         }
 8845:     }
 8846:     return %clicker_ids;
 8847: }
 8848: 
 8849: sub gather_adv_clicker_ids {
 8850:     my %clicker_ids;
 8851:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8852:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8853:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8854:     foreach my $element (sort(keys(%coursepersonnel))) {
 8855:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8856:             my ($puname,$pudom)=split(/\:/,$person);
 8857:             my $clickers =
 8858: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8859:             foreach my $id (split(/\,/,$clickers)) {
 8860: 		$id=~s/^[\#0]+//;
 8861:                 $id=~s/[\-\:]//g;
 8862: 		if (exists($clicker_ids{$id})) {
 8863: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8864: 		} else {
 8865: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8866: 		}
 8867:             }
 8868:         }
 8869:     }
 8870:     return %clicker_ids;
 8871: }
 8872: 
 8873: sub clicker_grading_parameters {
 8874:     return ('gradingmechanism' => 'scalar',
 8875:             'upfiletype' => 'scalar',
 8876:             'specificid' => 'scalar',
 8877:             'pcorrect' => 'scalar',
 8878:             'pincorrect' => 'scalar');
 8879: }
 8880: 
 8881: sub process_clicker {
 8882:     my ($r)=@_;
 8883:     my ($symb)=&get_symb($r);
 8884:     if (!$symb) {return '';}
 8885:     my $result=&checkforfile_js();
 8886:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8887:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8888:     $result.=$table;
 8889:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8890:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8891:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8892:         '</b></td></tr>'."\n";
 8893:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8894: # Attempt to restore parameters from last session, set defaults if not present
 8895:     my %Saveable_Parameters=&clicker_grading_parameters();
 8896:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8897:                                                  \%Saveable_Parameters);
 8898:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8899:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8900:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8901:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8902: 
 8903:     my %checked;
 8904:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8905:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8906:           $checked{$gradingmechanism}=' checked="checked"';
 8907:        }
 8908:     }
 8909: 
 8910:     my $upload=&mt("Upload File");
 8911:     my $type=&mt("Type");
 8912:     my $attendance=&mt("Award points just for participation");
 8913:     my $personnel=&mt("Correctness determined from response by course personnel");
 8914:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8915:     my $given=&mt("Correctness determined from given list of answers").' '.
 8916:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8917:     my $pcorrect=&mt("Percentage points for correct solution");
 8918:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8919:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8920: 						   ('iclicker' => 'i>clicker',
 8921:                                                     'interwrite' => 'interwrite PRS'));
 8922:     $symb = &Apache::lonenc::check_encrypt($symb);
 8923:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8924: function sanitycheck() {
 8925: // Accept only integer percentages
 8926:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8927:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8928: // Find out grading choice
 8929:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8930:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8931:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8932:       }
 8933:    }
 8934: // By default, new choice equals user selection
 8935:    newgradingchoice=gradingchoice;
 8936: // Not good to give more points for false answers than correct ones
 8937:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8938:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8939:    }
 8940: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8941:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8942:       document.forms.gradesupload.pcorrect.value=100;
 8943:       document.forms.gradesupload.pincorrect.value=100;
 8944:    }
 8945: // If the values are different, cannot be attendance only
 8946:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8947:        (gradingchoice=='attendance')) {
 8948:        newgradingchoice='personnel';
 8949:    }
 8950: // Change grading choice to new one
 8951:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8952:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8953:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8954:       } else {
 8955:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8956:       }
 8957:    }
 8958: // Remember the old state
 8959:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8960: }
 8961: ENDUPFORM
 8962:     $result.= <<ENDUPFORM;
 8963: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8964: <input type="hidden" name="symb" value="$symb" />
 8965: <input type="hidden" name="command" value="processclickerfile" />
 8966: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8967: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8968: <input type="file" name="upfile" size="50" />
 8969: <br /><label>$type: $selectform</label>
 8970: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8971: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8972: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8973: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8974: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8975: <br />&nbsp;&nbsp;&nbsp;
 8976: <input type="text" name="givenanswer" size="50" />
 8977: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8978: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8979: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8980: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8981: </form>'
 8982: ENDUPFORM
 8983:     $result.='</td></tr></table>'."\n".
 8984:              '</td></tr></table><br /><br />'."\n";
 8985:     $result.=&show_grading_menu_form($symb);
 8986:     return $result;
 8987: }
 8988: 
 8989: sub process_clicker_file {
 8990:     my ($r)=@_;
 8991:     my ($symb)=&get_symb($r);
 8992:     if (!$symb) {return '';}
 8993: 
 8994:     my %Saveable_Parameters=&clicker_grading_parameters();
 8995:     &Apache::loncommon::store_course_settings('grades_clicker',
 8996:                                               \%Saveable_Parameters);
 8997: 
 8998:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8999:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9000: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9001: 	return $result.&show_grading_menu_form($symb);
 9002:     }
 9003:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9004:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9005:         return $result.&show_grading_menu_form($symb);
 9006:     }
 9007:     my $foundgiven=0;
 9008:     if ($env{'form.gradingmechanism'} eq 'given') {
 9009:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9010:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9011:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 9012:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9013:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9014:         $foundgiven=$#answers+1;
 9015:     }
 9016:     my %clicker_ids=&gather_clicker_ids();
 9017:     my %correct_ids;
 9018:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9019: 	%correct_ids=&gather_adv_clicker_ids();
 9020:     }
 9021:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9022: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9023: 	   $correct_id=~tr/a-z/A-Z/;
 9024: 	   $correct_id=~s/\s//gs;
 9025: 	   $correct_id=~s/^[\#0]+//;
 9026:            $correct_id=~s/[\-\:]//g;
 9027:            if ($correct_id) {
 9028: 	      $correct_ids{$correct_id}='specified';
 9029:            }
 9030:         }
 9031:     }
 9032:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9033: 	$result.=&mt('Score based on attendance only');
 9034:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9035:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9036:     } else {
 9037: 	my $number=0;
 9038: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9039: 	foreach my $id (sort(keys(%correct_ids))) {
 9040: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9041: 	    if ($correct_ids{$id} eq 'specified') {
 9042: 		$result.=&mt('specified');
 9043: 	    } else {
 9044: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9045: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9046: 	    }
 9047: 	    $number++;
 9048: 	}
 9049:         $result.="</p>\n";
 9050: 	if ($number==0) {
 9051: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9052: 	    return $result.&show_grading_menu_form($symb);
 9053: 	}
 9054:     }
 9055:     if (length($env{'form.upfile'}) < 2) {
 9056:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9057: 		     '<span class="LC_error">',
 9058: 		     '</span>',
 9059: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9060:         return $result.&show_grading_menu_form($symb);
 9061:     }
 9062: 
 9063: # Were able to get all the info needed, now analyze the file
 9064: 
 9065:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9066:     $symb = &Apache::lonenc::check_encrypt($symb);
 9067:     my $heading=&mt('Scanning clicker file');
 9068:     $result.=(<<ENDHEADER);
 9069: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9070: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9071: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9072: <form method="post" action="/adm/grades" name="clickeranalysis">
 9073: <input type="hidden" name="symb" value="$symb" />
 9074: <input type="hidden" name="command" value="assignclickergrades" />
 9075: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9076: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9077: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9078: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9079: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9080: ENDHEADER
 9081:     if ($env{'form.gradingmechanism'} eq 'given') {
 9082:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9083:     } 
 9084:     my %responses;
 9085:     my @questiontitles;
 9086:     my $errormsg='';
 9087:     my $number=0;
 9088:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9089: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9090:     }
 9091:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9092:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9093:     }
 9094:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9095:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9096:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9097:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9098:              '<br />';
 9099:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9100:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9101:        return $result.&show_grading_menu_form($symb);
 9102:     } 
 9103: # Remember Question Titles
 9104: # FIXME: Possibly need delimiter other than ":"
 9105:     for (my $i=0;$i<$number;$i++) {
 9106:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9107:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9108:     }
 9109:     my $correct_count=0;
 9110:     my $student_count=0;
 9111:     my $unknown_count=0;
 9112: # Match answers with usernames
 9113: # FIXME: Possibly need delimiter other than ":"
 9114:     foreach my $id (keys(%responses)) {
 9115:        if ($correct_ids{$id}) {
 9116:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9117:           $correct_count++;
 9118:        } elsif ($clicker_ids{$id}) {
 9119:           if ($clicker_ids{$id}=~/\,/) {
 9120: # More than one user with the same clicker!
 9121:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9122:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9123:                            "<select name='multi".$id."'>";
 9124:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9125:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9126:              }
 9127:              $result.='</select>';
 9128:              $unknown_count++;
 9129:           } else {
 9130: # Good: found one and only one user with the right clicker
 9131:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9132:              $student_count++;
 9133:           }
 9134:        } else {
 9135:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9136:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9137:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9138:                    "\n".&mt("Domain").": ".
 9139:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9140:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9141:           $unknown_count++;
 9142:        }
 9143:     }
 9144:     $result.='<hr />'.
 9145:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9146:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9147:        if ($correct_count==0) {
 9148:           $errormsg.="Found no correct answers answers for grading!";
 9149:        } elsif ($correct_count>1) {
 9150:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9151:        }
 9152:     }
 9153:     if ($number<1) {
 9154:        $errormsg.="Found no questions.";
 9155:     }
 9156:     if ($errormsg) {
 9157:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9158:     } else {
 9159:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9160:     }
 9161:     $result.='</form></td></tr></table>'."\n".
 9162:              '</td></tr></table><br /><br />'."\n";
 9163:     return $result.&show_grading_menu_form($symb);
 9164: }
 9165: 
 9166: sub iclicker_eval {
 9167:     my ($questiontitles,$responses)=@_;
 9168:     my $number=0;
 9169:     my $errormsg='';
 9170:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9171:         my %components=&Apache::loncommon::record_sep($line);
 9172:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9173: 	if ($entries[0] eq 'Question') {
 9174: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9175: 		$$questiontitles[$number]=$entries[$i];
 9176: 		$number++;
 9177: 	    }
 9178: 	}
 9179: 	if ($entries[0]=~/^\#/) {
 9180: 	    my $id=$entries[0];
 9181: 	    my @idresponses;
 9182: 	    $id=~s/^[\#0]+//;
 9183: 	    for (my $i=0;$i<$number;$i++) {
 9184: 		my $idx=3+$i*6;
 9185: 		push(@idresponses,$entries[$idx]);
 9186: 	    }
 9187: 	    $$responses{$id}=join(',',@idresponses);
 9188: 	}
 9189:     }
 9190:     return ($errormsg,$number);
 9191: }
 9192: 
 9193: sub interwrite_eval {
 9194:     my ($questiontitles,$responses)=@_;
 9195:     my $number=0;
 9196:     my $errormsg='';
 9197:     my $skipline=1;
 9198:     my $questionnumber=0;
 9199:     my %idresponses=();
 9200:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9201:         my %components=&Apache::loncommon::record_sep($line);
 9202:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9203:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9204:         if ($entries[1] eq 'Response') { $skipline=1; }
 9205:         next if $skipline;
 9206:         if ($entries[0]!=$questionnumber) {
 9207:            $questionnumber=$entries[0];
 9208:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9209:            $number++;
 9210:         }
 9211:         my $id=$entries[4];
 9212:         $id=~s/^[\#0]+//;
 9213:         $id=~s/^v\d*\://i;
 9214:         $id=~s/[\-\:]//g;
 9215:         $idresponses{$id}[$number]=$entries[6];
 9216:     }
 9217:     foreach my $id (keys(%idresponses)) {
 9218:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9219:        $$responses{$id}=~s/^\s*\,//;
 9220:     }
 9221:     return ($errormsg,$number);
 9222: }
 9223: 
 9224: sub assign_clicker_grades {
 9225:     my ($r)=@_;
 9226:     my ($symb)=&get_symb($r);
 9227:     if (!$symb) {return '';}
 9228: # See which part we are saving to
 9229:     my $res_error;
 9230:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9231:     if ($res_error) {
 9232:         return &navmap_errormsg();
 9233:     }
 9234: # FIXME: This should probably look for the first handgradeable part
 9235:     my $part=$$partlist[0];
 9236: # Start screen output
 9237:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9238: 
 9239:     my $heading=&mt('Assigning grades based on clicker file');
 9240:     $result.=(<<ENDHEADER);
 9241: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9242: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9243: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9244: ENDHEADER
 9245: # Get correct result
 9246: # FIXME: Possibly need delimiter other than ":"
 9247:     my @correct=();
 9248:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9249:     my $number=$env{'form.number'};
 9250:     if ($gradingmechanism ne 'attendance') {
 9251:        foreach my $key (keys(%env)) {
 9252:           if ($key=~/^form\.correct\:/) {
 9253:              my @input=split(/\,/,$env{$key});
 9254:              for (my $i=0;$i<=$#input;$i++) {
 9255:                  if (($correct[$i]) && ($input[$i]) &&
 9256:                      ($correct[$i] ne $input[$i])) {
 9257:                     $result.='<br /><span class="LC_warning">'.
 9258:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9259:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9260:                  } elsif ($input[$i]) {
 9261:                     $correct[$i]=$input[$i];
 9262:                  }
 9263:              }
 9264:           }
 9265:        }
 9266:        for (my $i=0;$i<$number;$i++) {
 9267:           if (!$correct[$i]) {
 9268:              $result.='<br /><span class="LC_error">'.
 9269:                       &mt('No correct result given for question "[_1]"!',
 9270:                           $env{'form.question:'.$i}).'</span>';
 9271:           }
 9272:        }
 9273:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9274:     }
 9275: # Start grading
 9276:     my $pcorrect=$env{'form.pcorrect'};
 9277:     my $pincorrect=$env{'form.pincorrect'};
 9278:     my $storecount=0;
 9279:     foreach my $key (keys(%env)) {
 9280:        my $user='';
 9281:        if ($key=~/^form\.student\:(.*)$/) {
 9282:           $user=$1;
 9283:        }
 9284:        if ($key=~/^form\.unknown\:(.*)$/) {
 9285:           my $id=$1;
 9286:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9287:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9288:           } elsif ($env{'form.multi'.$id}) {
 9289:              $user=$env{'form.multi'.$id};
 9290:           }
 9291:        }
 9292:        if ($user) { 
 9293:           my @answer=split(/\,/,$env{$key});
 9294:           my $sum=0;
 9295:           my $realnumber=$number;
 9296:           for (my $i=0;$i<$number;$i++) {
 9297:              if  ($correct[$i] eq '-') {
 9298:                 $realnumber--;
 9299:              } elsif ($answer[$i]) {
 9300:                 if ($gradingmechanism eq 'attendance') {
 9301:                    $sum+=$pcorrect;
 9302:                 } elsif ($correct[$i] eq '*') {
 9303:                    $sum+=$pcorrect;
 9304:                 } else {
 9305:                    if ($answer[$i] eq $correct[$i]) {
 9306:                       $sum+=$pcorrect;
 9307:                    } else {
 9308:                       $sum+=$pincorrect;
 9309:                    }
 9310:                 }
 9311:              }
 9312:           }
 9313:           my $ave=$sum/(100*$realnumber);
 9314: # Store
 9315:           my ($username,$domain)=split(/\:/,$user);
 9316:           my %grades=();
 9317:           $grades{"resource.$part.solved"}='correct_by_override';
 9318:           $grades{"resource.$part.awarded"}=$ave;
 9319:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9320:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9321:                                                  $env{'request.course.id'},
 9322:                                                  $domain,$username);
 9323:           if ($returncode ne 'ok') {
 9324:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9325:           } else {
 9326:              $storecount++;
 9327:           }
 9328:        }
 9329:     }
 9330: # We are done
 9331:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9332:              '</td></tr></table>'."\n".
 9333:              '</td></tr></table><br /><br />'."\n";
 9334:     return $result.&show_grading_menu_form($symb);
 9335: }
 9336: 
 9337: sub navmap_errormsg {
 9338:     return '<div class="LC_error">'.
 9339:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9340:            &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>').
 9341:            '</div>';
 9342: }
 9343: 
 9344: sub handler {
 9345:     my $request=$_[0];
 9346:     &reset_caches();
 9347:     if ($env{'browser.mathml'}) {
 9348: 	&Apache::loncommon::content_type($request,'text/xml');
 9349:     } else {
 9350: 	&Apache::loncommon::content_type($request,'text/html');
 9351:     }
 9352:     $request->send_http_header;
 9353:     return '' if $request->header_only;
 9354:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9355:     my $symb=&get_symb($request,1);
 9356:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9357:     my $command=$commands[0];
 9358: 
 9359:     if ($#commands > 0) {
 9360: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9361:     }
 9362: 
 9363:     $ssi_error = 0;
 9364:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9365:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9366:                                           {'bread_crumbs' => $brcrum}));
 9367:     if ($symb eq '' && $command eq '') {
 9368: 	if ($env{'user.adv'}) {
 9369: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9370: 		($env{'form.codethree'})) {
 9371: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9372: 		    $env{'form.codethree'};
 9373: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9374: 		    &Apache::lonnet::checkin($token);
 9375: 		if ($tsymb) {
 9376: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9377: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9378: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9379: 					  ('grade_username' => $tuname,
 9380: 					   'grade_domain' => $tudom,
 9381: 					   'grade_courseid' => $tcrsid,
 9382: 					   'grade_symb' => $tsymb)));
 9383: 		    } else {
 9384: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9385: 		    }
 9386: 		} else {
 9387: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9388: 		}
 9389: 	    } else {
 9390: 		$request->print(&Apache::lonxml::tokeninputfield());
 9391: 	    }
 9392: 	}
 9393:     } else {
 9394: 	&init_perm();
 9395: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9396: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9397: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9398: 	    &pickStudentPage($request);
 9399: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9400: 	    &displayPage($request);
 9401: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9402: 	    &updateGradeByPage($request);
 9403: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9404: 	    &processGroup($request);
 9405: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9406: 	    $request->print(&grading_menu($request));
 9407: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9408: 	    $request->print(&submit_options($request));
 9409: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9410: 	    $request->print(&viewgrades($request));
 9411: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9412: 	    $request->print(&processHandGrade($request));
 9413: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9414: 	    $request->print(&editgrades($request));
 9415: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9416: 	    $request->print(&verifyreceipt($request));
 9417:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9418:             $request->print(&process_clicker($request));
 9419:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9420:             $request->print(&process_clicker_file($request));
 9421:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9422:             $request->print(&assign_clicker_grades($request));
 9423: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9424: 	    $request->print(&upcsvScores_form($request));
 9425: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9426: 	    $request->print(&csvupload($request));
 9427: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9428: 	    $request->print(&csvuploadmap($request));
 9429: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9430: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9431: 		$request->print(&csvuploadoptions($request));
 9432: 	    } else {
 9433: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9434: 		    $env{'form.upfile_associate'} = 'reverse';
 9435: 		} else {
 9436: 		    $env{'form.upfile_associate'} = 'forward';
 9437: 		}
 9438: 		$request->print(&csvuploadmap($request));
 9439: 	    }
 9440: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9441: 	    $request->print(&csvuploadassign($request));
 9442: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9443: 	    $request->print(&scantron_selectphase($request));
 9444:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9445:  	    $request->print(&scantron_do_warning($request));
 9446: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9447: 	    $request->print(&scantron_validate_file($request));
 9448: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9449: 	    $request->print(&scantron_process_students($request));
 9450:  	} elsif ($command eq 'scantronupload' && 
 9451:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9452: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9453:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9454:  	} elsif ($command eq 'scantronupload_save' &&
 9455:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9456: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9457:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9458:  	} elsif ($command eq 'scantron_download' &&
 9459: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9460:  	    $request->print(&scantron_download_scantron_data($request));
 9461:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9462:             $request->print(&checkscantron_results($request));     
 9463: 	} elsif ($command) {
 9464: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9465: 	}
 9466:     }
 9467:     if ($ssi_error) {
 9468: 	&ssi_print_error($request);
 9469:     }
 9470:     $request->print(&Apache::loncommon::end_page());
 9471:     &reset_caches();
 9472:     return '';
 9473: }
 9474: 
 9475: 1;
 9476: 
 9477: __END__;
 9478: 
 9479: 
 9480: =head1 NAME
 9481: 
 9482: Apache::grades
 9483: 
 9484: =head1 SYNOPSIS
 9485: 
 9486: Handles the viewing of grades.
 9487: 
 9488: This is part of the LearningOnline Network with CAPA project
 9489: described at http://www.lon-capa.org.
 9490: 
 9491: =head1 OVERVIEW
 9492: 
 9493: Do an ssi with retries:
 9494: While I'd love to factor out this with the vesrion in lonprintout,
 9495: 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
 9496: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9497: 
 9498: At least the logic that drives this has been pulled out into loncommon.
 9499: 
 9500: 
 9501: 
 9502: ssi_with_retries - Does the server side include of a resource.
 9503:                      if the ssi call returns an error we'll retry it up to
 9504:                      the number of times requested by the caller.
 9505:                      If we still have a proble, no text is appended to the
 9506:                      output and we set some global variables.
 9507:                      to indicate to the caller an SSI error occurred.  
 9508:                      All of this is supposed to deal with the issues described
 9509:                      in LonCAPA BZ 5631 see:
 9510:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9511:                      by informing the user that this happened.
 9512: 
 9513: Parameters:
 9514:   resource   - The resource to include.  This is passed directly, without
 9515:                interpretation to lonnet::ssi.
 9516:   form       - The form hash parameters that guide the interpretation of the resource
 9517:                
 9518:   retries    - Number of retries allowed before giving up completely.
 9519: Returns:
 9520:   On success, returns the rendered resource identified by the resource parameter.
 9521: Side Effects:
 9522:   The following global variables can be set:
 9523:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9524:                               It is up to the caller to initialize this to false
 9525:                               if desired.
 9526:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9527:                               of the resource that could not be rendered by the ssi
 9528:                               call.
 9529:    ssi_error_message   - The error string fetched from the ssi response
 9530:                               in the event of an error.
 9531: 
 9532: 
 9533: =head1 HANDLER SUBROUTINE
 9534: 
 9535: ssi_with_retries()
 9536: 
 9537: =head1 SUBROUTINES
 9538: 
 9539: =over
 9540: 
 9541: =item scantron_get_correction() : 
 9542: 
 9543:    Builds the interface screen to interact with the operator to fix a
 9544:    specific error condition in a specific scanline
 9545: 
 9546:  Arguments:
 9547:     $r           - Apache request object
 9548:     $i           - number of the current scanline
 9549:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9550:     $scan_config - hash ref as returned from &get_scantron_config()
 9551:     $line        - full contents of the current scanline
 9552:     $error       - error condition, valid values are
 9553:                    'incorrectCODE', 'duplicateCODE',
 9554:                    'doublebubble', 'missingbubble',
 9555:                    'duplicateID', 'incorrectID'
 9556:     $arg         - extra information needed
 9557:        For errors:
 9558:          - duplicateID   - paper number that this studentID was seen before on
 9559:          - duplicateCODE - array ref of the paper numbers this CODE was
 9560:                            seen on before
 9561:          - incorrectCODE - current incorrect CODE 
 9562:          - doublebubble  - array ref of the bubble lines that have double
 9563:                            bubble errors
 9564:          - missingbubble - array ref of the bubble lines that have missing
 9565:                            bubble errors
 9566: 
 9567: =item  scantron_get_maxbubble() : 
 9568: 
 9569:    Arguments:
 9570:        $nav_error  - Reference to scalar which is a flag to indicate a
 9571:                       failure to retrieve a navmap object.
 9572:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9573:        calling routine should trap the error condition and display the warning
 9574:        found in &navmap_errormsg().
 9575: 
 9576:    Returns the maximum number of bubble lines that are expected to
 9577:    occur. Does this by walking the selected sequence rendering the
 9578:    resource and then checking &Apache::lonxml::get_problem_counter()
 9579:    for what the current value of the problem counter is.
 9580: 
 9581:    Caches the results to $env{'form.scantron_maxbubble'},
 9582:    $env{'form.scantron.bubble_lines.n'}, 
 9583:    $env{'form.scantron.first_bubble_line.n'} and
 9584:    $env{"form.scantron.sub_bubblelines.n"}
 9585:    which are the total number of bubble, lines, the number of bubble
 9586:    lines for response n and number of the first bubble line for response n,
 9587:    and a comma separated list of numbers of bubble lines for sub-questions
 9588:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9589: 
 9590: 
 9591: =item  scantron_validate_missingbubbles() : 
 9592: 
 9593:    Validates all scanlines in the selected file to not have any
 9594:     answers that don't have bubbles that have not been verified
 9595:     to be bubble free.
 9596: 
 9597: =item  scantron_process_students() : 
 9598: 
 9599:    Routine that does the actual grading of the bubble sheet information.
 9600: 
 9601:    The parsed scanline hash is added to %env 
 9602: 
 9603:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9604:    foreach resource , with the form data of
 9605: 
 9606: 	'submitted'     =>'scantron' 
 9607: 	'grade_target'  =>'grade',
 9608: 	'grade_username'=> username of student
 9609: 	'grade_domain'  => domain of student
 9610: 	'grade_courseid'=> of course
 9611: 	'grade_symb'    => symb of resource to grade
 9612: 
 9613:     This triggers a grading pass. The problem grading code takes care
 9614:     of converting the bubbled letter information (now in %env) into a
 9615:     valid submission.
 9616: 
 9617: =item  scantron_upload_scantron_data() :
 9618: 
 9619:     Creates the screen for adding a new bubble sheet data file to a course.
 9620: 
 9621: =item  scantron_upload_scantron_data_save() : 
 9622: 
 9623:    Adds a provided bubble information data file to the course if user
 9624:    has the correct privileges to do so. 
 9625: 
 9626: =item  valid_file() :
 9627: 
 9628:    Validates that the requested bubble data file exists in the course.
 9629: 
 9630: =item  scantron_download_scantron_data() : 
 9631: 
 9632:    Shows a list of the three internal files (original, corrected,
 9633:    skipped) for a specific bubble sheet data file that exists in the
 9634:    course.
 9635: 
 9636: =item  scantron_validate_ID() : 
 9637: 
 9638:    Validates all scanlines in the selected file to not have any
 9639:    invalid or underspecified student/employee IDs
 9640: 
 9641: =item navmap_errormsg() :
 9642: 
 9643:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9644:    Should be called whenever the request to instantiate a navmap object fails.  
 9645: 
 9646: =back
 9647: 
 9648: =cut

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