File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.18: download - view: text, annotated - select for diffs
Wed Aug 14 03:33:54 2013 UTC (10 years, 8 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  - Backport 1.694, 1.695, 1.696, 1.697, 1.698.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.18 2013/08/14 03:33:54 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::bridgetask();
   47: use String::Similarity;
   48: use LONCAPA;
   49: 
   50: use POSIX qw(floor);
   51: 
   52: 
   53: 
   54: my %perm=();
   55: my %old_essays=();
   56: 
   57: #  These variables are used to recover from ssi errors
   58: 
   59: my $ssi_retries = 5;
   60: my $ssi_error;
   61: my $ssi_error_resource;
   62: my $ssi_error_message;
   63: 
   64: 
   65: sub ssi_with_retries {
   66:     my ($resource, $retries, %form) = @_;
   67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   68:     if ($response->is_error) {
   69: 	$ssi_error          = 1;
   70: 	$ssi_error_resource = $resource;
   71: 	$ssi_error_message  = $response->code . " " . $response->message;
   72:     }
   73: 
   74:     return $content;
   75: 
   76: }
   77: #
   78: #  Prodcuces an ssi retry failure error message to the user:
   79: #
   80: 
   81: sub ssi_print_error {
   82:     my ($r) = @_;
   83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   84:     $r->print('
   85: <br />
   86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   87: <p>
   88: '.&mt('Unable to retrieve a resource from a server:').'<br />
   89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   90: '.&mt('Error:').' '.$ssi_error_message.'
   91: </p>
   92: <p>'.
   93: &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 />'.
   94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   95: '</p>');
   96:     return;
   97: }
   98: 
   99: #
  100: # --- Retrieve the parts from the metadata file.---
  101: sub getpartlist {
  102:     my ($symb,$errorref) = @_;
  103: 
  104:     my $navmap   = Apache::lonnavmaps::navmap->new();
  105:     unless (ref($navmap)) {
  106:         if (ref($errorref)) { 
  107:             $$errorref = 'navmap';
  108:             return;
  109:         }
  110:     }
  111:     my $res      = $navmap->getBySymb($symb);
  112:     my $partlist = $res->parts();
  113:     my $url      = $res->src();
  114:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  115: 
  116:     my @stores;
  117:     foreach my $part (@{ $partlist }) {
  118: 	foreach my $key (@metakeys) {
  119: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  120: 	}
  121:     }
  122:     return @stores;
  123: }
  124: 
  125: # --- Get the symbolic name of a problem and the url
  126: sub get_symb {
  127:     my ($request,$silent) = @_;
  128:     my $symb=$env{'form.symb'};
  129:     unless ($symb) {
  130:         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  131:         $symb = &Apache::lonnet::symbread($url);
  132:         if ($symb eq '') { 
  133: 	    if (!$silent) {
  134:                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  135: 	        return ();
  136: 	    }
  137:         }
  138:     }
  139:     &Apache::lonenc::check_decrypt(\$symb);
  140:     return ($symb);
  141: }
  142: 
  143: #--- Format fullname, username:domain if different for display
  144: #--- Use anywhere where the student names are listed
  145: sub nameUserString {
  146:     my ($type,$fullname,$uname,$udom) = @_;
  147:     if ($type eq 'header') {
  148: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  149:     } else {
  150: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  151: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  152:     }
  153: }
  154: 
  155: #--- Get the partlist and the response type for a given problem. ---
  156: #--- Indicate if a response type is coded handgraded or not. ---
  157: sub response_type {
  158:     my ($symb,$response_error) = @_;
  159: 
  160:     my $navmap = Apache::lonnavmaps::navmap->new();
  161:     unless (ref($navmap)) {
  162:         if (ref($response_error)) {
  163:             $$response_error = 1;
  164:         }
  165:         return;
  166:     }
  167:     my $res = $navmap->getBySymb($symb);
  168:     unless (ref($res)) {
  169:         $$response_error = 1;
  170:         return;
  171:     }
  172:     my $partlist = $res->parts();
  173:     my %vPart = 
  174: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  175:     my (%response_types,%handgrade);
  176:     foreach my $part (@{ $partlist }) {
  177: 	next if (%vPart && !exists($vPart{$part}));
  178: 
  179: 	my @types = $res->responseType($part);
  180: 	my @ids = $res->responseIds($part);
  181: 	for (my $i=0; $i < scalar(@ids); $i++) {
  182: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  183: 	    $handgrade{$part.'_'.$ids[$i]} = 
  184: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  185: 				     '.handgrade',$symb);
  186: 	}
  187:     }
  188:     return ($partlist,\%handgrade,\%response_types);
  189: }
  190: 
  191: sub flatten_responseType {
  192:     my ($responseType) = @_;
  193:     my @part_response_id =
  194: 	map { 
  195: 	    my $part = $_;
  196: 	    map {
  197: 		[$part,$_]
  198: 		} sort(keys(%{ $responseType->{$part} }));
  199: 	} sort(keys(%$responseType));
  200:     return @part_response_id;
  201: }
  202: 
  203: sub get_display_part {
  204:     my ($partID,$symb)=@_;
  205:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  206:     if (defined($display) and $display ne '') {
  207:         $display.= ' (<span class="LC_internal_info">'
  208:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  209:     } else {
  210: 	$display=$partID;
  211:     }
  212:     return $display;
  213: }
  214: 
  215: #--- Show resource title
  216: #--- and parts and response type
  217: sub showResourceInfo {
  218:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  219:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  220:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  221:     if (ref($res_error)) {
  222:         if ($$res_error) {
  223:             return;
  224:         }
  225:     }
  226:     $result.=&Apache::loncommon::start_data_table()
  227:             .&Apache::loncommon::start_data_table_header_row();
  228:     if ($checkboxes) {
  229:         $result.='<th>&nbsp;</th>';
  230:     }
  231:     $result.='<th>'.&mt('Problem Part').'</th>'
  232:             .'<th>'.&mt('Res. ID').'</th>'
  233:             .'<th>'.&mt('Type').'</th>'
  234:             .&Apache::loncommon::end_data_table_header_row();
  235:     my %resptype = ();
  236:     my $hdgrade='no';
  237:     my %partsseen;
  238:     foreach my $partID (sort(keys(%$responseType))) {
  239:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  240:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  241:             my $responsetype = $responseType->{$partID}->{$resID};
  242:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  243:             $result.=&Apache::loncommon::start_data_table_row();
  244:             if ($checkboxes) {
  245:                 if (exists($partsseen{$partID})) {
  246:                     $result.="<td>&nbsp;</td>";
  247:                 } else {
  248:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  249:                 }
  250:                 $partsseen{$partID}=1;
  251:             }
  252:             my $display_part=&get_display_part($partID,$symb);
  253:             $result.='<td>'.$display_part.'</td>'
  254:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  255:                     .'<td>'.&mt($responsetype).'</td>'
  256: #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
  257:                     .&Apache::loncommon::end_data_table_row();
  258:         }
  259:     }
  260:     $result.=&Apache::loncommon::end_data_table();
  261:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  262: }
  263: 
  264: sub reset_caches {
  265:     &reset_analyze_cache();
  266:     &reset_perm();
  267:     &reset_old_essays();
  268: }
  269: 
  270: {
  271:     my %analyze_cache;
  272:     my %analyze_cache_formkeys;
  273: 
  274:     sub reset_analyze_cache {
  275: 	undef(%analyze_cache);
  276:         undef(%analyze_cache_formkeys);
  277:     }
  278: 
  279:     sub get_analyze {
  280: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  281: 	my $key = "$symb\0$uname\0$udom";
  282:         if ($type eq 'randomizetry') {
  283:             if ($trial ne '') {
  284:                 $key .= "\0".$trial;
  285:             }
  286:         }
  287: 	if (exists($analyze_cache{$key})) {
  288:             my $getupdate = 0;
  289:             if (ref($add_to_hash) eq 'HASH') {
  290:                 foreach my $item (keys(%{$add_to_hash})) {
  291:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  292:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  293:                             $getupdate = 1;
  294:                             last;
  295:                         }
  296:                     } else {
  297:                         $getupdate = 1;
  298:                     }
  299:                 }
  300:             }
  301:             if (!$getupdate) {
  302:                 return $analyze_cache{$key};
  303:             }
  304:         }
  305: 
  306: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  307: 	$url=&Apache::lonnet::clutter($url);
  308:         my %form = ('grade_target'      => 'analyze',
  309:                     'grade_domain'      => $udom,
  310:                     'grade_symb'        => $symb,
  311:                     'grade_courseid'    =>  $env{'request.course.id'},
  312:                     'grade_username'    => $uname,
  313:                     'grade_noincrement' => $no_increment);
  314:         if ($bubbles_per_row ne '') {
  315:             $form{'bubbles_per_row'} = $bubbles_per_row;
  316:         }
  317:         if ($type eq 'randomizetry') {
  318:             $form{'grade_questiontype'} = $type;
  319:             if ($rndseed ne '') {
  320:                 $form{'grade_rndseed'} = $rndseed;
  321:             }
  322:         }
  323:         if (ref($add_to_hash)) {
  324:             %form = (%form,%{$add_to_hash});
  325:         }
  326: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  327: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  328: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  329:         if (ref($add_to_hash) eq 'HASH') {
  330:             $analyze_cache_formkeys{$key} = $add_to_hash;
  331:         } else {
  332:             $analyze_cache_formkeys{$key} = {};
  333:         }
  334: 	return $analyze_cache{$key} = \%analyze;
  335:     }
  336: 
  337:     sub get_order {
  338: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  339: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  340: 	return $analyze->{"$partid.$respid.shown"};
  341:     }
  342: 
  343:     sub get_radiobutton_correct_foil {
  344: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  345: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  346:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  347:         if (ref($foils) eq 'ARRAY') {
  348: 	    foreach my $foil (@{$foils}) {
  349: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  350: 		    return $foil;
  351: 	        }
  352: 	    }
  353: 	}
  354:     }
  355: 
  356:     sub scantron_partids_tograde {
  357:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  358:         my (%analysis,@parts);
  359:         if (ref($resource)) {
  360:             my $symb = $resource->symb();
  361:             my $add_to_form;
  362:             if ($check_for_randomlist) {
  363:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  364:             }
  365:             my $analyze =
  366:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  367:                              undef,undef,undef,$bubbles_per_row);
  368:             if (ref($analyze) eq 'HASH') {
  369:                 %analysis = %{$analyze};
  370:             }
  371:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  372:                 foreach my $part (@{$analysis{'parts'}}) {
  373:                     my ($id,$respid) = split(/\./,$part);
  374:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  375:                         push(@parts,$part);
  376:                     }
  377:                 }
  378:             }
  379:         }
  380:         return (\%analysis,\@parts);
  381:     }
  382: 
  383: }
  384: 
  385: #--- Clean response type for display
  386: #--- Currently filters option/rank/radiobutton/match/essay/Task
  387: #        response types only.
  388: sub cleanRecord {
  389:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  390: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  391:     my $grayFont = '<span class="LC_internal_info">';
  392:     if ($response =~ /^(option|rank)$/) {
  393: 	my %answer=&Apache::lonnet::str2hash($answer);
  394: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  395: 	my ($toprow,$bottomrow);
  396: 	foreach my $foil (@$order) {
  397: 	    if ($grading{$foil} == 1) {
  398: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  399: 	    } else {
  400: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  401: 	    }
  402: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  403: 	}
  404: 	return '<blockquote><table border="1">'.
  405: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  406: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  407: 	    $bottomrow.'</tr></table></blockquote>';
  408:     } elsif ($response eq 'match') {
  409: 	my %answer=&Apache::lonnet::str2hash($answer);
  410: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  411: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  412: 	my ($toprow,$middlerow,$bottomrow);
  413: 	foreach my $foil (@$order) {
  414: 	    my $item=shift(@items);
  415: 	    if ($grading{$foil} == 1) {
  416: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  417: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  418: 	    } else {
  419: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  420: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  421: 	    }
  422: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  423: 	}
  424: 	return '<blockquote><table border="1">'.
  425: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  426: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  427: 	    $middlerow.'</tr>'.
  428: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  429: 	    $bottomrow.'</tr></table></blockquote>';
  430:     } elsif ($response eq 'radiobutton') {
  431: 	my %answer=&Apache::lonnet::str2hash($answer);
  432: 	my ($toprow,$bottomrow);
  433: 	my $correct = 
  434: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  435: 	foreach my $foil (@$order) {
  436: 	    if (exists($answer{$foil})) {
  437: 		if ($foil eq $correct) {
  438: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  439: 		} else {
  440: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  441: 		}
  442: 	    } else {
  443: 		$toprow.='<td>'.&mt('false').'</td>';
  444: 	    }
  445: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  446: 	}
  447: 	return '<blockquote><table border="1">'.
  448: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  449: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  450: 	    $bottomrow.'</tr></table></blockquote>';
  451:     } elsif ($response eq 'essay') {
  452: 	if (! exists ($env{'form.'.$symb})) {
  453: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  454: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  455: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  456: 
  457: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  458: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  459: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  460: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  461: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  462: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  463: 	}
  464: 	$answer =~ s-\n-<br />-g;
  465: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  466:     } elsif ( $response eq 'organic') {
  467: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  468: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  469: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  470: 	return $result;
  471:     } elsif ( $response eq 'Task') {
  472: 	if ( $answer eq 'SUBMITTED') {
  473: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  474: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  475: 	    return $result;
  476: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  477: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  478: 			       keys(%{$record}));
  479: 	    return join('<br />',($version,@matches));
  480: 			       
  481: 			       
  482: 	} else {
  483: 	    my $result =
  484: 		'<p>'
  485: 		.&mt('Overall result: [_1]',
  486: 		     $record->{$version."resource.$respid.$partid.status"})
  487: 		.'</p>';
  488: 	    
  489: 	    $result .= '<ul>';
  490: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  491: 			     keys(%{$record}));
  492: 	    foreach my $grade (sort(@grade)) {
  493: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  494: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  495: 				     $dim, $record->{$grade}).
  496: 			  '</li>';
  497: 	    }
  498: 	    $result.='</ul>';
  499: 	    return $result;
  500: 	}
  501:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  502: 	$answer = 
  503: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  504: 							      $answer);
  505:     }
  506:     return $answer;
  507: }
  508: 
  509: #-- A couple of common js functions
  510: sub commonJSfunctions {
  511:     my $request = shift;
  512:     $request->print(<<COMMONJSFUNCTIONS);
  513: <script type="text/javascript" language="javascript">
  514:     function radioSelection(radioButton) {
  515: 	var selection=null;
  516: 	if (radioButton.length > 1) {
  517: 	    for (var i=0; i<radioButton.length; i++) {
  518: 		if (radioButton[i].checked) {
  519: 		    return radioButton[i].value;
  520: 		}
  521: 	    }
  522: 	} else {
  523: 	    if (radioButton.checked) return radioButton.value;
  524: 	}
  525: 	return selection;
  526:     }
  527: 
  528:     function pullDownSelection(selectOne) {
  529: 	var selection="";
  530: 	if (selectOne.length > 1) {
  531: 	    for (var i=0; i<selectOne.length; i++) {
  532: 		if (selectOne[i].selected) {
  533: 		    return selectOne[i].value;
  534: 		}
  535: 	    }
  536: 	} else {
  537:             // only one value it must be the selected one
  538: 	    return selectOne.value;
  539: 	}
  540:     }
  541: </script>
  542: COMMONJSFUNCTIONS
  543: }
  544: 
  545: #--- Dumps the class list with usernames,list of sections,
  546: #--- section, ids and fullnames for each user.
  547: sub getclasslist {
  548:     my ($getsec,$filterlist,$getgroup) = @_;
  549:     my @getsec;
  550:     my @getgroup;
  551:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  552:     if (!ref($getsec)) {
  553: 	if ($getsec ne '' && $getsec ne 'all') {
  554: 	    @getsec=($getsec);
  555: 	}
  556:     } else {
  557: 	@getsec=@{$getsec};
  558:     }
  559:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  560:     if (!ref($getgroup)) {
  561: 	if ($getgroup ne '' && $getgroup ne 'all') {
  562: 	    @getgroup=($getgroup);
  563: 	}
  564:     } else {
  565: 	@getgroup=@{$getgroup};
  566:     }
  567:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  568: 
  569:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  570:     # Bail out if we were unable to get the classlist
  571:     return if (! defined($classlist));
  572:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  573:     #
  574:     my %sections;
  575:     my %fullnames;
  576:     foreach my $student (keys(%$classlist)) {
  577:         my $end      = 
  578:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  579:         my $start    = 
  580:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  581:         my $id       = 
  582:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  583:         my $section  = 
  584:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  585:         my $fullname = 
  586:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  587:         my $status   = 
  588:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  589:         my $group   = 
  590:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  591: 	# filter students according to status selected
  592: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  593: 	    if (!($stu_status =~ $status)) {
  594: 		delete($classlist->{$student});
  595: 		next;
  596: 	    }
  597: 	}
  598: 	# filter students according to groups selected
  599: 	my @stu_groups = split(/,/,$group);
  600: 	if (@getgroup) {
  601: 	    my $exclude = 1;
  602: 	    foreach my $grp (@getgroup) {
  603: 	        foreach my $stu_group (@stu_groups) {
  604: 	            if ($stu_group eq $grp) {
  605: 	                $exclude = 0;
  606:     	            } 
  607: 	        }
  608:     	        if (($grp eq 'none') && !$group) {
  609:         	        $exclude = 0;
  610:         	}
  611: 	    }
  612: 	    if ($exclude) {
  613: 	        delete($classlist->{$student});
  614: 	    }
  615: 	}
  616: 	$section = ($section ne '' ? $section : 'none');
  617: 	if (&canview($section)) {
  618: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  619: 		$sections{$section}++;
  620: 		if ($classlist->{$student}) {
  621: 		    $fullnames{$student}=$fullname;
  622: 		}
  623: 	    } else {
  624: 		delete($classlist->{$student});
  625: 	    }
  626: 	} else {
  627: 	    delete($classlist->{$student});
  628: 	}
  629:     }
  630:     my %seen = ();
  631:     my @sections = sort(keys(%sections));
  632:     return ($classlist,\@sections,\%fullnames);
  633: }
  634: 
  635: sub canmodify {
  636:     my ($sec)=@_;
  637:     if ($perm{'mgr'}) {
  638: 	if (!defined($perm{'mgr_section'})) {
  639: 	    # can modify whole class
  640: 	    return 1;
  641: 	} else {
  642: 	    if ($sec eq $perm{'mgr_section'}) {
  643: 		#can modify the requested section
  644: 		return 1;
  645: 	    } else {
  646: 		# can't modify the request section
  647: 		return 0;
  648: 	    }
  649: 	}
  650:     }
  651:     #can't modify
  652:     return 0;
  653: }
  654: 
  655: sub canview {
  656:     my ($sec)=@_;
  657:     if ($perm{'vgr'}) {
  658: 	if (!defined($perm{'vgr_section'})) {
  659: 	    # can modify whole class
  660: 	    return 1;
  661: 	} else {
  662: 	    if ($sec eq $perm{'vgr_section'}) {
  663: 		#can modify the requested section
  664: 		return 1;
  665: 	    } else {
  666: 		# can't modify the request section
  667: 		return 0;
  668: 	    }
  669: 	}
  670:     }
  671:     #can't modify
  672:     return 0;
  673: }
  674: 
  675: #--- Retrieve the grade status of a student for all the parts
  676: sub student_gradeStatus {
  677:     my ($symb,$udom,$uname,$partlist) = @_;
  678:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  679:     my %partstatus = ();
  680:     foreach (@$partlist) {
  681: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  682: 	$status              = 'nothing' if ($status eq '');
  683: 	$partstatus{$_}      = $status;
  684: 	my $subkey           = "resource.$_.submitted_by";
  685: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  686:     }
  687:     return %partstatus;
  688: }
  689: 
  690: # hidden form and javascript that calls the form
  691: # Use by verifyscript and viewgrades
  692: # Shows a student's view of problem and submission
  693: sub jscriptNform {
  694:     my ($symb) = @_;
  695:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  696:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  697: 	'    function viewOneStudent(user,domain) {'."\n".
  698: 	'	document.onestudent.student.value = user;'."\n".
  699: 	'	document.onestudent.userdom.value = domain;'."\n".
  700: 	'	document.onestudent.submit();'."\n".
  701: 	'    }'."\n".
  702: 	'</script>'."\n";
  703:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  704: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  705: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  706: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  707: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  708: 	'<input type="hidden" name="command" value="submission" />'."\n".
  709: 	'<input type="hidden" name="student" value="" />'."\n".
  710: 	'<input type="hidden" name="userdom" value="" />'."\n".
  711: 	'</form>'."\n";
  712:     return $jscript;
  713: }
  714: 
  715: 
  716: 
  717: # Given the score (as a number [0-1] and the weight) what is the final
  718: # point value? This function will round to the nearest tenth, third,
  719: # or quarter if one of those is within the tolerance of .00001.
  720: sub compute_points {
  721:     my ($score, $weight) = @_;
  722:     
  723:     my $tolerance = .00001;
  724:     my $points = $score * $weight;
  725: 
  726:     # Check for nearness to 1/x.
  727:     my $check_for_nearness = sub {
  728:         my ($factor) = @_;
  729:         my $num = ($points * $factor) + $tolerance;
  730:         my $floored_num = floor($num);
  731:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  732:             return $floored_num / $factor;
  733:         }
  734:         return $points;
  735:     };
  736: 
  737:     $points = $check_for_nearness->(10);
  738:     $points = $check_for_nearness->(3);
  739:     $points = $check_for_nearness->(4);
  740:     
  741:     return $points;
  742: }
  743: 
  744: #------------------ End of general use routines --------------------
  745: 
  746: #
  747: # Find most similar essay
  748: #
  749: 
  750: sub most_similar {
  751:     my ($uname,$udom,$symb,$uessay)=@_;
  752: 
  753:     unless ($symb) { return ''; }
  754: 
  755:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  756: 
  757: # ignore spaces and punctuation
  758: 
  759:     $uessay=~s/\W+/ /gs;
  760: 
  761: # ignore empty submissions (occuring when only files are sent)
  762: 
  763:     unless ($uessay=~/\w+/s) { return ''; }
  764: 
  765: # these will be returned. Do not care if not at least 50 percent similar
  766:     my $limit=0.6;
  767:     my $sname='';
  768:     my $sdom='';
  769:     my $scrsid='';
  770:     my $sessay='';
  771: # go through all essays ...
  772:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  773: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  774: # ... except the same student
  775:         next if (($tname eq $uname) && ($tdom eq $udom));
  776: 	my $tessay=$old_essays{$symb}{$tkey};
  777: 	$tessay=~s/\W+/ /gs;
  778: # String similarity gives up if not even limit
  779: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  780: # Found one
  781: 	if ($tsimilar>$limit) {
  782: 	    $limit=$tsimilar;
  783: 	    $sname=$tname;
  784: 	    $sdom=$tdom;
  785: 	    $scrsid=$tcrsid;
  786: 	    $sessay=$old_essays{$symb}{$tkey};
  787: 	}
  788:     }
  789:     if ($limit>0.6) {
  790:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  791:     } else {
  792:        return ('','','','',0);
  793:     }
  794: }
  795: 
  796: #-------------------------------------------------------------------
  797: 
  798: #------------------------------------ Receipt Verification Routines
  799: #
  800: #--- Check whether a receipt number is valid.---
  801: sub verifyreceipt {
  802:     my $request  = shift;
  803: 
  804:     my $courseid = $env{'request.course.id'};
  805:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  806: 	$env{'form.receipt'};
  807:     $receipt     =~ s/[^\-\d]//g;
  808:     my ($symb)   = &get_symb($request);
  809: 
  810:     my $title.=
  811: 	'<h3><span class="LC_info">'.
  812: 	&mt('Verifying Receipt No. [_1]',$receipt).
  813: 	'</span></h3>'."\n".
  814: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  815: 	'</h4>'."\n";
  816: 
  817:     my ($string,$contents,$matches) = ('','',0);
  818:     my (undef,undef,$fullname) = &getclasslist('all','0');
  819:     
  820:     my $receiptparts=0;
  821:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  822: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  823:     my $parts=['0'];
  824:     if ($receiptparts) {
  825:         my $res_error; 
  826:         ($parts)=&response_type($symb,\$res_error);
  827:         if ($res_error) {
  828:             return &navmap_errormsg();
  829:         } 
  830:     }
  831:     
  832:     my $header = 
  833: 	&Apache::loncommon::start_data_table().
  834: 	&Apache::loncommon::start_data_table_header_row().
  835: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  836: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  837: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  838:     if ($receiptparts) {
  839: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  840:     }
  841:     $header.=
  842: 	&Apache::loncommon::end_data_table_header_row();
  843: 
  844:     foreach (sort 
  845: 	     {
  846: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  847: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  848: 		 }
  849: 		 return $a cmp $b;
  850: 	     } (keys(%$fullname))) {
  851: 	my ($uname,$udom)=split(/\:/);
  852: 	foreach my $part (@$parts) {
  853: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  854: 		$contents.=
  855: 		    &Apache::loncommon::start_data_table_row().
  856: 		    '<td>&nbsp;'."\n".
  857: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  858: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  859: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  860: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  861: 		if ($receiptparts) {
  862: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  863: 		}
  864: 		$contents.= 
  865: 		    &Apache::loncommon::end_data_table_row()."\n";
  866: 		
  867: 		$matches++;
  868: 	    }
  869: 	}
  870:     }
  871:     if ($matches == 0) {
  872:         $string = $title
  873:                  .'<p class="LC_warning">'
  874:                  .&mt('No match found for the above receipt number.')
  875:                  .'</p>';
  876:     } else {
  877: 	$string = &jscriptNform($symb).$title.
  878: 	    '<p>'.
  879: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  880: 	    '</p>'.
  881: 	    $header.
  882: 	    $contents.
  883: 	    &Apache::loncommon::end_data_table()."\n";
  884:     }
  885:     return $string.&show_grading_menu_form($symb);
  886: }
  887: 
  888: #--- This is called by a number of programs.
  889: #--- Called from the Grading Menu - View/Grade an individual student
  890: #--- Also called directly when one clicks on the subm button 
  891: #    on the problem page.
  892: sub listStudents {
  893:     my ($request) = shift;
  894: 
  895:     my ($symb) = &get_symb($request);
  896:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  897:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  898:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  899:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  900:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  901:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  902:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  903: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  904: 
  905:     my $result='<h3><span class="LC_info">&nbsp;'
  906: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  907: 	.'</span></h3>';
  908: 
  909:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  910: 
  911:     my %lt = &Apache::lonlocal::texthash (
  912: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  913: 		'single'   => 'Please select the student before clicking on the Next button.',
  914: 	     );
  915:     $request->print(<<LISTJAVASCRIPT);
  916: <script type="text/javascript" language="javascript">
  917:     function checkSelect(checkBox) {
  918: 	var ctr=0;
  919: 	var sense="";
  920: 	if (checkBox.length > 1) {
  921: 	    for (var i=0; i<checkBox.length; i++) {
  922: 		if (checkBox[i].checked) {
  923: 		    ctr++;
  924: 		}
  925: 	    }
  926: 	    sense = '$lt{'multiple'}';
  927: 	} else {
  928: 	    if (checkBox.checked) {
  929: 		ctr = 1;
  930: 	    }
  931: 	    sense = '$lt{'single'}';
  932: 	}
  933: 	if (ctr == 0) {
  934: 	    alert(sense);
  935: 	    return false;
  936: 	}
  937: 	document.gradesub.submit();
  938:     }
  939: 
  940:     function reLoadList(formname) {
  941: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  942: 	formname.command.value = 'submission';
  943: 	formname.submit();
  944:     }
  945: </script>
  946: LISTJAVASCRIPT
  947: 
  948:     &commonJSfunctions($request);
  949:     $request->print($result);
  950: 
  951:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  952:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  953:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  954: 	"\n".$table;
  955: 	
  956:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  957:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  958:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  959:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  960:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  961:                   .&Apache::lonhtmlcommon::row_closure();
  962:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  963:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  964:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  965:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  966:                   .&Apache::lonhtmlcommon::row_closure();
  967: 
  968:     my $submission_options;
  969:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  970: 	$submission_options.=
  971: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  972:     }
  973:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  974:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  975:     $env{'form.Status'} = $saveStatus;
  976:     $submission_options.=
  977:         '<span class="LC_nobreak">'.
  978:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  979:         &mt('last submission only').' </label></span>'."\n".
  980:         '<span class="LC_nobreak">'.
  981:         '<label><input type="radio" name="lastSub" value="last" /> '.
  982:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  983:         '<span class="LC_nobreak">'.
  984:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  985:         &mt('by dates and submissions').'</label></span>'."\n".
  986:         '<span class="LC_nobreak">'.
  987:         '<label><input type="radio" name="lastSub" value="all" /> '.
  988:         &mt('all details').'</label></span>';
  989:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  990:                   .$submission_options
  991:                   .&Apache::lonhtmlcommon::row_closure();
  992: 
  993:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  994:                   .'<select name="increment">'
  995:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  996:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  997:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  998:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  999:                   .'</select>'
 1000:                   .&Apache::lonhtmlcommon::row_closure();
 1001: 
 1002:     $gradeTable .= 
 1003:         &build_section_inputs().
 1004: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1005: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1006: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1007: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1008: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1009: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1010: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1011: 
 1012:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1013: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1014:     } else {
 1015:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1016:                       .&Apache::lonhtmlcommon::StatusOptions(
 1017:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1018:                       .&Apache::lonhtmlcommon::row_closure();
 1019:     }
 1020: 
 1021:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1022:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1023:                   .&Apache::lonhtmlcommon::row_closure(1)
 1024:                   .&Apache::lonhtmlcommon::end_pick_box();
 1025: 
 1026:     $gradeTable .= '<p>'
 1027:                   .&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"
 1028:                   .'<input type="hidden" name="command" value="processGroup" />'
 1029:                   .'</p>';
 1030: 
 1031: # checkall buttons
 1032:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1033:     $gradeTable.='<input type="button" '."\n".
 1034:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1035:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1036:     $gradeTable.=&check_buttons();
 1037:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1038:     $gradeTable.= &Apache::loncommon::start_data_table().
 1039: 	&Apache::loncommon::start_data_table_header_row();
 1040:     my $loop = 0;
 1041:     while ($loop < 2) {
 1042: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1043: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1044: 	if ($env{'form.showgrading'} eq 'yes' 
 1045: 	    && $submitonly ne 'queued'
 1046: 	    && $submitonly ne 'all') {
 1047: 	    foreach my $part (sort(@$partlist)) {
 1048: 		my $display_part=
 1049: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1050: 		$gradeTable.=
 1051: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1052: 	    }
 1053: 	} elsif ($submitonly eq 'queued') {
 1054: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1055: 	}
 1056: 	$loop++;
 1057: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1058:     }
 1059:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1060: 
 1061:     my $ctr = 0;
 1062:     foreach my $student (sort 
 1063: 			 {
 1064: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1065: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1066: 			     }
 1067: 			     return $a cmp $b;
 1068: 			 }
 1069: 			 (keys(%$fullname))) {
 1070: 	my ($uname,$udom) = split(/:/,$student);
 1071: 
 1072: 	my %status = ();
 1073: 
 1074: 	if ($submitonly eq 'queued') {
 1075: 	    my %queue_status = 
 1076: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1077: 							$udom,$uname);
 1078: 	    next if (!defined($queue_status{'gradingqueue'}));
 1079: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1080: 	}
 1081: 
 1082: 	if ($env{'form.showgrading'} eq 'yes' 
 1083: 	    && $submitonly ne 'queued'
 1084: 	    && $submitonly ne 'all') {
 1085: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1086: 	    my $submitted = 0;
 1087: 	    my $graded = 0;
 1088: 	    my $incorrect = 0;
 1089: 	    foreach (keys(%status)) {
 1090: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1091: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1092: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1093: 		
 1094: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1095: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1096: 		    $submitted = 0;
 1097: 		    my ($part)=split(/\./,$partid);
 1098: 		    $gradeTable.='<input type="hidden" name="'.
 1099: 			$student.':'.$part.':submitted_by" value="'.
 1100: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1101: 		}
 1102: 	    }
 1103: 	    
 1104: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1105: 				     $submitonly eq 'incorrect' ||
 1106: 				     $submitonly eq 'graded'));
 1107: 	    next if (!$graded && ($submitonly eq 'graded'));
 1108: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1109: 	}
 1110: 
 1111: 	$ctr++;
 1112: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1113:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1114: 	if ( $perm{'vgr'} eq 'F' ) {
 1115: 	    if ($ctr%2 ==1) {
 1116: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1117: 	    }
 1118: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1119:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1120:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1121: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1122: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1123: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1124: 
 1125: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1126: 		foreach (sort(keys(%status))) {
 1127: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1128: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1129: 		}
 1130: 	    }
 1131: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1132: 	    if ($ctr%2 ==0) {
 1133: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1134: 	    }
 1135: 	}
 1136:     }
 1137:     if ($ctr%2 ==1) {
 1138: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1139: 	    if ($env{'form.showgrading'} eq 'yes' 
 1140: 		&& $submitonly ne 'queued'
 1141: 		&& $submitonly ne 'all') {
 1142: 		foreach (@$partlist) {
 1143: 		    $gradeTable.='<td>&nbsp;</td>';
 1144: 		}
 1145: 	    } elsif ($submitonly eq 'queued') {
 1146: 		$gradeTable.='<td>&nbsp;</td>';
 1147: 	    }
 1148: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1149:     }
 1150: 
 1151:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1152:         '<input type="button" '.
 1153:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1154:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1155:     if ($ctr == 0) {
 1156: 	my $num_students=(scalar(keys(%$fullname)));
 1157: 	if ($num_students eq 0) {
 1158: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1159: 	} else {
 1160: 	    my $submissions='submissions';
 1161: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1162: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1163: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1164: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1165: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1166: 		    $num_students).
 1167: 		'</span><br />';
 1168: 	}
 1169:     } elsif ($ctr == 1) {
 1170: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1171:     }
 1172:     $gradeTable.=&show_grading_menu_form($symb);
 1173:     $request->print($gradeTable);
 1174:     return '';
 1175: }
 1176: 
 1177: #---- Called from the listStudents routine
 1178: 
 1179: sub check_script {
 1180:     my ($form, $type)=@_;
 1181:     my $chkallscript='<script type="text/javascript">
 1182:     function checkall() {
 1183:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1184:             ele = document.forms.'.$form.'.elements[i];
 1185:             if (ele.name == "'.$type.'") {
 1186:             document.forms.'.$form.'.elements[i].checked=true;
 1187:                                        }
 1188:         }
 1189:     }
 1190: 
 1191:     function checksec() {
 1192:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1193:             ele = document.forms.'.$form.'.elements[i];
 1194:            string = document.forms.'.$form.'.chksec.value;
 1195:            if
 1196:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1197:               document.forms.'.$form.'.elements[i].checked=true;
 1198:             }
 1199:         }
 1200:     }
 1201: 
 1202: 
 1203:     function uncheckall() {
 1204:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1205:             ele = document.forms.'.$form.'.elements[i];
 1206:             if (ele.name == "'.$type.'") {
 1207:             document.forms.'.$form.'.elements[i].checked=false;
 1208:                                        }
 1209:         }
 1210:     }
 1211: 
 1212: </script>'."\n";
 1213:     return $chkallscript;
 1214: }
 1215: 
 1216: sub check_buttons {
 1217:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1218:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1219:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1220:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1221:     return $buttons;
 1222: }
 1223: 
 1224: #     Displays the submissions for one student or a group of students
 1225: sub processGroup {
 1226:     my ($request)  = shift;
 1227:     my $ctr        = 0;
 1228:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1229:     my $total      = scalar(@stuchecked)-1;
 1230: 
 1231:     foreach my $student (@stuchecked) {
 1232: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1233: 	$env{'form.student'}        = $uname;
 1234: 	$env{'form.userdom'}        = $udom;
 1235: 	$env{'form.fullname'}       = $fullname;
 1236: 	&submission($request,$ctr,$total);
 1237: 	$ctr++;
 1238:     }
 1239:     return '';
 1240: }
 1241: 
 1242: #------------------------------------------------------------------------------------
 1243: #
 1244: #-------------------------- Next few routines handles grading by student, essentially
 1245: #                           handles essay response type problem/part
 1246: #
 1247: #--- Javascript to handle the submission page functionality ---
 1248: sub sub_page_js {
 1249:     my $request = shift;
 1250: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1251:     $request->print(<<SUBJAVASCRIPT);
 1252: <script type="text/javascript" language="javascript">
 1253:     function updateRadio(formname,id,weight) {
 1254: 	var gradeBox = formname["GD_BOX"+id];
 1255: 	var radioButton = formname["RADVAL"+id];
 1256: 	var oldpts = formname["oldpts"+id].value;
 1257: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1258: 	gradeBox.value = pts;
 1259: 	var resetbox = false;
 1260: 	if (isNaN(pts) || pts < 0) {
 1261: 	    alert("$alertmsg"+pts);
 1262: 	    for (var i=0; i<radioButton.length; i++) {
 1263: 		if (radioButton[i].checked) {
 1264: 		    gradeBox.value = i;
 1265: 		    resetbox = true;
 1266: 		}
 1267: 	    }
 1268: 	    if (!resetbox) {
 1269: 		formtextbox.value = "";
 1270: 	    }
 1271: 	    return;
 1272: 	}
 1273: 
 1274: 	if (pts > weight) {
 1275: 	    var resp = confirm("You entered a value ("+pts+
 1276: 			       ") greater than the weight for the part. Accept?");
 1277: 	    if (resp == false) {
 1278: 		gradeBox.value = oldpts;
 1279: 		return;
 1280: 	    }
 1281: 	}
 1282: 
 1283: 	for (var i=0; i<radioButton.length; i++) {
 1284: 	    radioButton[i].checked=false;
 1285: 	    if (pts == i && pts != "") {
 1286: 		radioButton[i].checked=true;
 1287: 	    }
 1288: 	}
 1289: 	updateSelect(formname,id);
 1290: 	formname["stores"+id].value = "0";
 1291:     }
 1292: 
 1293:     function writeBox(formname,id,pts) {
 1294: 	var gradeBox = formname["GD_BOX"+id];
 1295: 	if (checkSolved(formname,id) == 'update') {
 1296: 	    gradeBox.value = pts;
 1297: 	} else {
 1298: 	    var oldpts = formname["oldpts"+id].value;
 1299: 	    gradeBox.value = oldpts;
 1300: 	    var radioButton = formname["RADVAL"+id];
 1301: 	    for (var i=0; i<radioButton.length; i++) {
 1302: 		radioButton[i].checked=false;
 1303: 		if (i == oldpts) {
 1304: 		    radioButton[i].checked=true;
 1305: 		}
 1306: 	    }
 1307: 	}
 1308: 	formname["stores"+id].value = "0";
 1309: 	updateSelect(formname,id);
 1310: 	return;
 1311:     }
 1312: 
 1313:     function clearRadBox(formname,id) {
 1314: 	if (checkSolved(formname,id) == 'noupdate') {
 1315: 	    updateSelect(formname,id);
 1316: 	    return;
 1317: 	}
 1318: 	gradeSelect = formname["GD_SEL"+id];
 1319: 	for (var i=0; i<gradeSelect.length; i++) {
 1320: 	    if (gradeSelect[i].selected) {
 1321: 		var selectx=i;
 1322: 	    }
 1323: 	}
 1324: 	var stores = formname["stores"+id];
 1325: 	if (selectx == stores.value) { return };
 1326: 	var gradeBox = formname["GD_BOX"+id];
 1327: 	gradeBox.value = "";
 1328: 	var radioButton = formname["RADVAL"+id];
 1329: 	for (var i=0; i<radioButton.length; i++) {
 1330: 	    radioButton[i].checked=false;
 1331: 	}
 1332: 	stores.value = selectx;
 1333:     }
 1334: 
 1335:     function checkSolved(formname,id) {
 1336: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1337: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1338: 	    if (!reply) {return "noupdate";}
 1339: 	    formname.overRideScore.value = 'yes';
 1340: 	}
 1341: 	return "update";
 1342:     }
 1343: 
 1344:     function updateSelect(formname,id) {
 1345: 	formname["GD_SEL"+id][0].selected = true;
 1346: 	return;
 1347:     }
 1348: 
 1349: //=========== Check that a point is assigned for all the parts  ============
 1350:     function checksubmit(formname,val,total,parttot) {
 1351: 	formname.gradeOpt.value = val;
 1352: 	if (val == "Save & Next") {
 1353: 	    for (i=0;i<=total;i++) {
 1354: 		for (j=0;j<parttot;j++) {
 1355: 		    var partid = formname["partid"+i+"_"+j].value;
 1356: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1357: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1358: 			if (points == "") {
 1359: 			    var name = formname["name"+i].value;
 1360: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1361: 			    var resp = confirm("You did not assign a score for "+studentID+
 1362: 					       ", part "+partid+". Continue?");
 1363: 			    if (resp == false) {
 1364: 				formname["GD_BOX"+i+"_"+partid].focus();
 1365: 				return false;
 1366: 			    }
 1367: 			}
 1368: 		    }
 1369: 		    
 1370: 		}
 1371: 	    }
 1372: 	    
 1373: 	}
 1374: 	if (val == "Grade Student") {
 1375: 	    formname.showgrading.value = "yes";
 1376: 	    if (formname.Status.value == "") {
 1377: 		formname.Status.value = "Active";
 1378: 	    }
 1379: 	    formname.studentNo.value = total;
 1380: 	}
 1381: 	formname.submit();
 1382:     }
 1383: 
 1384: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1385:     function checkSubmitPage(formname,total) {
 1386: 	noscore = new Array(100);
 1387: 	var ptr = 0;
 1388: 	for (i=1;i<total;i++) {
 1389: 	    var partid = formname["q_"+i].value;
 1390: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1391: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1392: 		var status = formname["solved"+i+"_"+partid].value;
 1393: 		if (points == "" && status != "correct_by_student") {
 1394: 		    noscore[ptr] = i;
 1395: 		    ptr++;
 1396: 		}
 1397: 	    }
 1398: 	}
 1399: 	if (ptr != 0) {
 1400: 	    var sense = ptr == 1 ? ": " : "s: ";
 1401: 	    var prolist = "";
 1402: 	    if (ptr == 1) {
 1403: 		prolist = noscore[0];
 1404: 	    } else {
 1405: 		var i = 0;
 1406: 		while (i < ptr-1) {
 1407: 		    prolist += noscore[i]+", ";
 1408: 		    i++;
 1409: 		}
 1410: 		prolist += "and "+noscore[i];
 1411: 	    }
 1412: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1413: 	    if (resp == false) {
 1414: 		return false;
 1415: 	    }
 1416: 	}
 1417: 
 1418: 	formname.submit();
 1419:     }
 1420: </script>
 1421: SUBJAVASCRIPT
 1422: }
 1423: 
 1424: #--- javascript for essay type problem --
 1425: sub sub_page_kw_js {
 1426:     my $request = shift;
 1427:     my $iconpath = $request->dir_config('lonIconsURL');
 1428:     &commonJSfunctions($request);
 1429: 
 1430:     my $inner_js_msg_central=<<INNERJS;
 1431:     <script text="text/javascript">
 1432:     function checkInput() {
 1433:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1434:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1435:       var usrctr = document.msgcenter.usrctr.value;
 1436:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1437:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1438: 
 1439:       var msgchk = "";
 1440:       if (document.msgcenter.subchk.checked) {
 1441:          msgchk = "msgsub,";
 1442:       }
 1443:       var includemsg = 0;
 1444:       for (var i=1; i<=nmsg; i++) {
 1445:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1446:           var frmmsg = document.msgcenter["msg"+i];
 1447:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1448:           var showflg = opener.document.SCORE["shownOnce"+i];
 1449:           showflg.value = "1";
 1450:           var chkbox = document.msgcenter["msgn"+i];
 1451:           if (chkbox.checked) {
 1452:              msgchk += "savemsg"+i+",";
 1453:              includemsg = 1;
 1454:           }
 1455:       }
 1456:       if (document.msgcenter.newmsgchk.checked) {
 1457:          msgchk += "newmsg"+usrctr;
 1458:          includemsg = 1;
 1459:       }
 1460:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1461:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1462:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1463:       includemsg.value = msgchk;
 1464: 
 1465:       self.close()
 1466: 
 1467:     }
 1468:     </script>
 1469: INNERJS
 1470: 
 1471:     my $inner_js_highlight_central=<<INNERJS;
 1472:  <script type="text/javascript">
 1473:     function updateChoice(flag) {
 1474:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1475:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1476:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1477:       opener.document.SCORE.refresh.value = "on";
 1478:       if (opener.document.SCORE.keywords.value!=""){
 1479:          opener.document.SCORE.submit();
 1480:       }
 1481:       self.close()
 1482:     }
 1483: </script>
 1484: INNERJS
 1485: 
 1486:     my $start_page_msg_central = 
 1487:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1488: 				       {'js_ready'  => 1,
 1489: 					'only_body' => 1,
 1490: 					'bgcolor'   =>'#FFFFFF',});
 1491:     my $end_page_msg_central = 
 1492: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1493: 
 1494: 
 1495:     my $start_page_highlight_central = 
 1496:         &Apache::loncommon::start_page('Highlight Central',
 1497: 				       $inner_js_highlight_central,
 1498: 				       {'js_ready'  => 1,
 1499: 					'only_body' => 1,
 1500: 					'bgcolor'   =>'#FFFFFF',});
 1501:     my $end_page_highlight_central = 
 1502: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1503: 
 1504:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1505:     $docopen=~s/^document\.//;
 1506:     my %lt = &Apache::lonlocal::texthash(
 1507:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1508:                 plse => 'Please select a word or group of words from document and then click this link.',
 1509:                 adds => 'Add selection to keyword list? Edit if desired.',
 1510:                 comp => 'Compose Message for: ',
 1511:                 incl => 'Include',
 1512:                 type => 'Type',
 1513:                 subj => 'Subject',
 1514:                 mesa => 'Message',
 1515:                 new  => 'New',
 1516:                 save => 'Save',
 1517:                 canc => 'Cancel',
 1518:                 kehi => 'Keyword Highlight Options',
 1519:                 txtc => 'Text Color',
 1520:                 font => 'Font Size',
 1521:                 fnst => 'Font Style',
 1522:              );
 1523:     $request->print(<<SUBJAVASCRIPT);
 1524: <script type="text/javascript" language="javascript">
 1525: 
 1526: //===================== Show list of keywords ====================
 1527:   function keywords(formname) {
 1528:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1529:     if (nret==null) return;
 1530:     formname.keywords.value = nret;
 1531: 
 1532:     if (formname.keywords.value != "") {
 1533: 	formname.refresh.value = "on";
 1534: 	formname.submit();
 1535:     }
 1536:     return;
 1537:   }
 1538: 
 1539: //===================== Script to view submitted by ==================
 1540:   function viewSubmitter(submitter) {
 1541:     document.SCORE.refresh.value = "on";
 1542:     document.SCORE.NCT.value = "1";
 1543:     document.SCORE.unamedom0.value = submitter;
 1544:     document.SCORE.submit();
 1545:     return;
 1546:   }
 1547: 
 1548: //===================== Script to add keyword(s) ==================
 1549:   function getSel() {
 1550:     if (document.getSelection) txt = document.getSelection();
 1551:     else if (document.selection) txt = document.selection.createRange().text;
 1552:     else return;
 1553:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1554:     if (cleantxt=="") {
 1555: 	alert("$lt{'plse'}");
 1556: 	return;
 1557:     }
 1558:     var nret = prompt("$lt{'adds'}",cleantxt);
 1559:     if (nret==null) return;
 1560:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1561:     if (document.SCORE.keywords.value != "") {
 1562: 	document.SCORE.refresh.value = "on";
 1563: 	document.SCORE.submit();
 1564:     }
 1565:     return;
 1566:   }
 1567: 
 1568: //====================== Script for composing message ==============
 1569:    // preload images
 1570:    img1 = new Image();
 1571:    img1.src = "$iconpath/mailbkgrd.gif";
 1572:    img2 = new Image();
 1573:    img2.src = "$iconpath/mailto.gif";
 1574: 
 1575:   function msgCenter(msgform,usrctr,fullname) {
 1576:     var Nmsg  = msgform.savemsgN.value;
 1577:     savedMsgHeader(Nmsg,usrctr,fullname);
 1578:     var subject = msgform.msgsub.value;
 1579:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1580:     re = /msgsub/;
 1581:     var shwsel = "";
 1582:     if (re.test(msgchk)) { shwsel = "checked" }
 1583:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1584:     displaySubject(checkEntities(subject),shwsel);
 1585:     for (var i=1; i<=Nmsg; i++) {
 1586: 	var testmsg = "savemsg"+i+",";
 1587: 	re = new RegExp(testmsg,"g");
 1588: 	shwsel = "";
 1589: 	if (re.test(msgchk)) { shwsel = "checked" }
 1590: 	var message = document.SCORE["savemsg"+i].value;
 1591: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1592: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1593: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1594:     }
 1595:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1596:     shwsel = "";
 1597:     re = /newmsg/;
 1598:     if (re.test(msgchk)) { shwsel = "checked" }
 1599:     newMsg(newmsg,shwsel);
 1600:     msgTail(); 
 1601:     return;
 1602:   }
 1603: 
 1604:   function checkEntities(strx) {
 1605:     if (strx.length == 0) return strx;
 1606:     var orgStr = ["&", "<", ">", '"']; 
 1607:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1608:     var counter = 0;
 1609:     while (counter < 4) {
 1610: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1611: 	counter++;
 1612:     }
 1613:     return strx;
 1614:   }
 1615: 
 1616:   function strReplace(strx, orgStr, newStr) {
 1617:     return strx.split(orgStr).join(newStr);
 1618:   }
 1619: 
 1620:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1621:     var height = 70*Nmsg+250;
 1622:     if (height > 600) {
 1623: 	height = 600;
 1624:     }
 1625:     var xpos = (screen.width-600)/2;
 1626:     xpos = (xpos < 0) ? '0' : xpos;
 1627:     var ypos = (screen.height-height)/2-30;
 1628:     ypos = (ypos < 0) ? '0' : ypos;
 1629: 
 1630:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1631:     pWin.focus();
 1632:     pDoc = pWin.document;
 1633:     pDoc.$docopen;
 1634:     pDoc.write('$start_page_msg_central');
 1635: 
 1636:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1637:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1638:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1639: 
 1640:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1641:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1642:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1643: }
 1644:     function displaySubject(msg,shwsel) {
 1645:     pDoc = pWin.document;
 1646:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1647:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1648:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1649:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1650: }
 1651: 
 1652:   function displaySavedMsg(ctr,msg,shwsel) {
 1653:     pDoc = pWin.document;
 1654:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1655:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1656:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1657:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1658: }
 1659: 
 1660:   function newMsg(newmsg,shwsel) {
 1661:     pDoc = pWin.document;
 1662:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1663:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1664:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1665:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1666: }
 1667: 
 1668:   function msgTail() {
 1669:     pDoc = pWin.document;
 1670:     pDoc.write("<\\/table>");
 1671:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1672:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1673:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1674:     pDoc.write("<\\/form>");
 1675:     pDoc.write('$end_page_msg_central');
 1676:     pDoc.close();
 1677: }
 1678: 
 1679: //====================== Script for keyword highlight options ==============
 1680:   function kwhighlight() {
 1681:     var kwclr    = document.SCORE.kwclr.value;
 1682:     var kwsize   = document.SCORE.kwsize.value;
 1683:     var kwstyle  = document.SCORE.kwstyle.value;
 1684:     var redsel = "";
 1685:     var grnsel = "";
 1686:     var blusel = "";
 1687:     if (kwclr=="red")   {var redsel="checked"};
 1688:     if (kwclr=="green") {var grnsel="checked"};
 1689:     if (kwclr=="blue")  {var blusel="checked"};
 1690:     var sznsel = "";
 1691:     var sz1sel = "";
 1692:     var sz2sel = "";
 1693:     if (kwsize=="0")  {var sznsel="checked"};
 1694:     if (kwsize=="+1") {var sz1sel="checked"};
 1695:     if (kwsize=="+2") {var sz2sel="checked"};
 1696:     var synsel = "";
 1697:     var syisel = "";
 1698:     var sybsel = "";
 1699:     if (kwstyle=="")    {var synsel="checked"};
 1700:     if (kwstyle=="<i>") {var syisel="checked"};
 1701:     if (kwstyle=="<b>") {var sybsel="checked"};
 1702:     highlightCentral();
 1703:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1704:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1705:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1706:     highlightend();
 1707:     return;
 1708:   }
 1709: 
 1710:   function highlightCentral() {
 1711: //    if (window.hwdWin) window.hwdWin.close();
 1712:     var xpos = (screen.width-400)/2;
 1713:     xpos = (xpos < 0) ? '0' : xpos;
 1714:     var ypos = (screen.height-330)/2-30;
 1715:     ypos = (ypos < 0) ? '0' : ypos;
 1716: 
 1717:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1718:     hwdWin.focus();
 1719:     var hDoc = hwdWin.document;
 1720:     hDoc.$docopen;
 1721:     hDoc.write('$start_page_highlight_central');
 1722:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1723:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1724: 
 1725:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1726:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1727:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
 1728:   }
 1729: 
 1730:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1731:     var hDoc = hwdWin.document;
 1732:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1733:     hDoc.write("<td align=\\"left\\">");
 1734:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1735:     hDoc.write("<td align=\\"left\\">");
 1736:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1737:     hDoc.write("<td align=\\"left\\">");
 1738:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1739:     hDoc.write("<\\/tr>");
 1740:   }
 1741: 
 1742:   function highlightend() { 
 1743:     var hDoc = hwdWin.document;
 1744:     hDoc.write("<\\/table>");
 1745:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1746:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1747:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1748:     hDoc.write("<\\/form>");
 1749:     hDoc.write('$end_page_highlight_central');
 1750:     hDoc.close();
 1751:   }
 1752: 
 1753: </script>
 1754: SUBJAVASCRIPT
 1755: }
 1756: 
 1757: sub get_increment {
 1758:     my $increment = $env{'form.increment'};
 1759:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1760:         $increment != .1) {
 1761:         $increment = 1;
 1762:     }
 1763:     return $increment;
 1764: }
 1765: 
 1766: sub gradeBox_start {
 1767:     return (
 1768:         &Apache::loncommon::start_data_table()
 1769:        .&Apache::loncommon::start_data_table_header_row()
 1770:        .'<th>'.&mt('Part').'</th>'
 1771:        .'<th>'.&mt('Points').'</th>'
 1772:        .'<th>&nbsp;</th>'
 1773:        .'<th>'.&mt('Assign Grade').'</th>'
 1774:        .'<th>'.&mt('Weight').'</th>'
 1775:        .'<th>'.&mt('Grade Status').'</th>'
 1776:        .&Apache::loncommon::end_data_table_header_row()
 1777:     );
 1778: }
 1779: 
 1780: sub gradeBox_end {
 1781:     return (
 1782:         &Apache::loncommon::end_data_table()
 1783:     );
 1784: }
 1785: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1786: sub gradeBox {
 1787:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1788:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1789: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1790:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1791:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1792:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1793:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1794:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1795: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1796:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1797:     my $display_part= &get_display_part($partid,$symb);
 1798:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1799: 				       [$partid]);
 1800:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1801:     if ($last_resets{$partid}) {
 1802:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1803:     }
 1804:     my $result=&Apache::loncommon::start_data_table_row();
 1805:     my $ctr = 0;
 1806:     my $thisweight = 0;
 1807:     my $increment = &get_increment();
 1808: 
 1809:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1810:     while ($thisweight<=$wgt) {
 1811: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1812:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1813: 	    $thisweight.')" value="'.$thisweight.'" '.
 1814: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1815: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1816:         $thisweight += $increment;
 1817: 	$ctr++;
 1818:     }
 1819:     $radio.='</tr></table>';
 1820: 
 1821:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1822: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1823: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1824: 	$wgt.')" /></td>'."\n";
 1825:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1826: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1827: 	' </td>'."\n";
 1828:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1829: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1830:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1831: 	$line.='<option></option>'.
 1832: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1833:     } else {
 1834: 	$line.='<option selected="selected"></option>'.
 1835: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1836:     }
 1837:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1838: 
 1839: 
 1840:     $result .= 
 1841: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1842:     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
 1843:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1844: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1845: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1846: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1847:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1848:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1849:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1850:         $aggtries.'" />'."\n";
 1851:     my $res_error;
 1852:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1853:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1854:     if ($res_error) {
 1855:         return &navmap_errormsg();
 1856:     }
 1857:     return $result;
 1858: }
 1859: 
 1860: sub handback_box {
 1861:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1862:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1863:     my (@respids);
 1864:     my @part_response_id = &flatten_responseType($responseType);
 1865:     foreach my $part_response_id (@part_response_id) {
 1866:     	my ($part,$resp) = @{ $part_response_id };
 1867:         if ($part eq $partid) {
 1868:             push(@respids,$resp);
 1869:         }
 1870:     }
 1871:     my $result;
 1872:     foreach my $respid (@respids) {
 1873: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1874: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1875: 	next if (!@$files);
 1876: 	my $file_counter = 0;
 1877: 	foreach my $file (@$files) {
 1878: 	    if ($file =~ /\/portfolio\//) {
 1879:                 $file_counter++;
 1880:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1881:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1882:     	        $file_disp = "$name.$ext";
 1883:     	        $file = $file_path.$file_disp;
 1884:     	        $result.=&mt('Return commented version of [_1] to student.',
 1885:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1886:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1887:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1888: 	    }
 1889: 	}
 1890:         if ($file_counter) {
 1891:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1892:                        '<span class="LC_info">'.
 1893:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1894:         }
 1895:     }
 1896:     return $result;    
 1897: }
 1898: 
 1899: sub show_problem {
 1900:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1901:     my $rendered;
 1902:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1903:     &Apache::lonxml::remember_problem_counter();
 1904:     if ($mode eq 'both' or $mode eq 'text') {
 1905: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1906: 						       $env{'request.course.id'},
 1907: 						       undef,\%form);
 1908:     }
 1909:     if ($removeform) {
 1910: 	$rendered=~s|<form(.*?)>||g;
 1911: 	$rendered=~s|</form>||g;
 1912: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1913:     }
 1914:     my $companswer;
 1915:     if ($mode eq 'both' or $mode eq 'answer') {
 1916: 	&Apache::lonxml::restore_problem_counter();
 1917: 	$companswer=
 1918: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1919: 						    $env{'request.course.id'},
 1920: 						    %form);
 1921:     }
 1922:     if ($removeform) {
 1923: 	$companswer=~s|<form(.*?)>||g;
 1924: 	$companswer=~s|</form>||g;
 1925: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1926:     }
 1927:     my $renderheading = &mt('View of the problem');
 1928:     my $answerheading = &mt('Correct answer');
 1929:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1930:         my $stu_fullname = $env{'form.fullname'};
 1931:         if ($stu_fullname eq '') {
 1932:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1933:         }
 1934:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1935:         if ($forwhom ne '') {
 1936:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1937:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1938:         }
 1939:     }
 1940:     $rendered=
 1941:         '<div class="LC_Box">'
 1942:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1943:        .$rendered
 1944:        .'</div>';
 1945:     $companswer=
 1946:         '<div class="LC_Box">'
 1947:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1948:        .$companswer
 1949:        .'</div>';
 1950:     my $result;
 1951:     if ($mode eq 'both') {
 1952:         $result=$rendered.$companswer;
 1953:     } elsif ($mode eq 'text') {
 1954:         $result=$rendered;
 1955:     } elsif ($mode eq 'answer') {
 1956:         $result=$companswer;
 1957:     }
 1958:     return $result;
 1959: }
 1960: 
 1961: sub files_exist {
 1962:     my ($r, $symb) = @_;
 1963:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1964: 
 1965:     foreach my $student (@students) {
 1966:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1967:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1968: 					      $udom,$uname);
 1969:         my ($string,$timestamp)= &get_last_submission(\%record);
 1970:         foreach my $submission (@$string) {
 1971:             my ($partid,$respid) =
 1972: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1973:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1974: 					   \%record);
 1975:             return 1 if (@$files);
 1976:         }
 1977:     }
 1978:     return 0;
 1979: }
 1980: 
 1981: sub download_all_link {
 1982:     my ($r,$symb) = @_;
 1983:     my $all_students = 
 1984: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1985: 
 1986:     my $parts =
 1987: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1988: 
 1989:     my $identifier = &Apache::loncommon::get_cgi_id();
 1990:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1991:                              'cgi.'.$identifier.'.symb' => $symb,
 1992:                              'cgi.'.$identifier.'.parts' => $parts,});
 1993:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1994: 	      &mt('Download All Submitted Documents').'</a>');
 1995:     return
 1996: }
 1997: 
 1998: sub build_section_inputs {
 1999:     my $section_inputs;
 2000:     if ($env{'form.section'} eq '') {
 2001:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2002:     } else {
 2003:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2004:         foreach my $section (@sections) {
 2005:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2006:         }
 2007:     }
 2008:     return $section_inputs;
 2009: }
 2010: 
 2011: # --------------------------- show submissions of a student, option to grade 
 2012: sub submission {
 2013:     my ($request,$counter,$total) = @_;
 2014:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2015:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2016:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2017:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2018:     my ($symb) = &get_symb($request); 
 2019:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2020: 
 2021:     if (!&canview($usec)) {
 2022: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 2023: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 2024: 			$env{'request.course.id'}.')</span>');
 2025: 	$request->print(&show_grading_menu_form($symb));
 2026: 	return;
 2027:     }
 2028: 
 2029:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2030:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2031:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2032:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2033:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2034: 	'" src="'.$request->dir_config('lonIconsURL').
 2035: 	'/check.gif" height="16" border="0" />';
 2036: 
 2037:     # header info
 2038:     if ($counter == 0) {
 2039: 	&sub_page_js($request);
 2040: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2041: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2042: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2043: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2044: 	    &download_all_link($request, $symb);
 2045: 	}
 2046: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2047: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 2048: 
 2049: 	# option to display problem, only once else it cause problems 
 2050:         # with the form later since the problem has a form.
 2051: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2052: 	    my $mode;
 2053: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2054: 		$mode='both';
 2055: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2056: 		$mode='text';
 2057: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2058: 		$mode='answer';
 2059: 	    }
 2060: 	    &Apache::lonxml::clear_problem_counter();
 2061: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2062: 	}
 2063: 
 2064: 	# kwclr is the only variable that is guaranteed to be non blank 
 2065:         # if this subroutine has been called once.
 2066: 	my %keyhash = ();
 2067: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2068: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2069: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2070: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2071: 
 2072: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2073: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2074: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2075: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2076: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2077: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2078: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2079: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2080: 	}
 2081: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2082: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2083: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2084: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2085: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2086: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2087: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2088: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2089: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2090: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2091: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2092: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2093: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2094: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2095: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2096: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2097: 			&build_section_inputs().
 2098: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2099: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2100: 			'<input type="hidden" name="NCT"'.
 2101: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2102: 	if ($env{'form.handgrade'} eq 'yes') {
 2103: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2104: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2105: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2106: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2107: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2108: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2109: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2110: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2111: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2112: 	    }
 2113: 	}
 2114: 	
 2115: 	my ($cts,$prnmsg) = (1,'');
 2116: 	while ($cts <= $env{'form.savemsgN'}) {
 2117: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2118: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2119: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2120: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2121: 		'" />'."\n".
 2122: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2123: 	    $cts++;
 2124: 	}
 2125: 	$request->print($prnmsg);
 2126: 
 2127: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2128: 
 2129:             my %lt = &Apache::lonlocal::texthash(
 2130:                           keyw => 'Keyword Options',
 2131:                           list => 'List',
 2132:                           past => 'Paste Selection to List',
 2133:                           high => 'Highlight Attribute',
 2134:                      );
 2135: #
 2136: # Print out the keyword options line
 2137: #
 2138: 	    $request->print(<<KEYWORDS);
 2139: &nbsp;<b>$lt{'keyw'}:</b>&nbsp;
 2140: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2141: <a href="#" onmousedown="javascript:getSel(); return false"
 2142:  class="page">$lt{'past'}</a>&nbsp; &nbsp;
 2143: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2144: KEYWORDS
 2145: #
 2146: # Load the other essays for similarity check
 2147: #
 2148:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2149: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2150: 	    $apath=&escape($apath);
 2151: 	    $apath=~s/\W/\_/gs;
 2152:             &init_old_essays($symb,$apath,$adom,$aname);
 2153:         }
 2154:     }
 2155: 
 2156: # This is where output for one specific student would start
 2157:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2158:     $request->print(
 2159:         "\n\n"
 2160:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2161:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2162:        ."\n"
 2163:     );
 2164: 
 2165:     # Show additional functions if allowed
 2166:     if ($perm{'vgr'}) {
 2167:         $request->print(
 2168:             &Apache::loncommon::track_student_link(
 2169:                 &mt('View recent activity'),
 2170:                 $uname,$udom,'check')
 2171:            .' '
 2172:         );
 2173:     }
 2174:     if ($perm{'opa'}) {
 2175:         $request->print(
 2176:             &Apache::loncommon::pprmlink(
 2177:                 &mt('Set/Change parameters'),
 2178:                 $uname,$udom,$symb,'check'));
 2179:     }
 2180: 
 2181:     # Show Problem
 2182:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2183: 	my $mode;
 2184: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2185: 	    $mode='both';
 2186: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2187: 	    $mode='text';
 2188: 	} elsif ($env{'form.vAns'} eq 'all') {
 2189: 	    $mode='answer';
 2190: 	}
 2191: 	&Apache::lonxml::clear_problem_counter();
 2192: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2193:     }
 2194: 
 2195:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2196:     my $res_error;
 2197:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2198:     if ($res_error) {
 2199:         $request->print(&navmap_errormsg());
 2200:         return;
 2201:     }
 2202: 
 2203:     # Display student info
 2204:     $request->print(($counter == 0 ? '' : '<br />'));
 2205: 
 2206:     my $result='<div class="LC_Box">'
 2207:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2208:     $result.='<input type="hidden" name="name'.$counter.
 2209:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2210:     if ($env{'form.handgrade'} eq 'no') {
 2211:         $result.='<p class="LC_info">'
 2212:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2213:                 ."</p>\n";
 2214:     }
 2215: 
 2216:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2217:     my $fullname;
 2218:     my $col_fullnames = [];
 2219:     if ($env{'form.handgrade'} eq 'yes') {
 2220: 	(my $sub_result,$fullname,$col_fullnames)=
 2221: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2222: 				 $counter);
 2223: 	$result.=$sub_result;
 2224:     }
 2225:     $request->print($result."\n");
 2226: 
 2227:     # print student answer/submission
 2228:     # Options are (1) Handgraded submission only
 2229:     #             (2) Last submission, includes submission that is not handgraded 
 2230:     #                  (for multi-response type part)
 2231:     #             (3) Last submission plus the parts info
 2232:     #             (4) The whole record for this student
 2233:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2234: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2235: 	
 2236: 	my $lastsubonly;
 2237: 
 2238:         if ($$timestamp eq '') {
 2239:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2240:         } else {
 2241:             $lastsubonly =
 2242:                 '<div class="LC_grade_submissions_body">'
 2243:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2244: 
 2245: 	    my %seenparts;
 2246: 	    my @part_response_id = &flatten_responseType($responseType);
 2247: 	    foreach my $part (@part_response_id) {
 2248: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2249: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2250: 
 2251: 		my ($partid,$respid) = @{ $part };
 2252: 		my $display_part=&get_display_part($partid,$symb);
 2253: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2254: 		    if (exists($seenparts{$partid})) { next; }
 2255: 		    $seenparts{$partid}=1;
 2256:                     $request->print(
 2257:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2258:                         ' <b>'.&mt('Collaborative submission by: [_1]',
 2259:                                    '<a href="javascript:viewSubmitter(\''.
 2260:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
 2261:                                    '\');" target="_self">'.
 2262:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2263:                         '<br />');
 2264: 		    next;
 2265: 		}
 2266: 		my $responsetype = $responseType->{$partid}->{$respid};
 2267: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2268:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2269:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2270:                         ' <span class="LC_internal_info">'.
 2271:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2272:                         '</span>&nbsp; &nbsp;'.
 2273: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2274: 		    next;
 2275: 		}
 2276: 		foreach my $submission (@$string) {
 2277: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2278: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2279: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2280: 		    # Similarity check
 2281: 		    my $similar='';
 2282:                     my ($type,$trial,$rndseed);
 2283:                     if ($hide eq 'rand') {
 2284:                         $type = 'randomizetry';
 2285:                         $trial = $record{"resource.$partid.tries"};
 2286:                         $rndseed = $record{"resource.$partid.rndseed"};
 2287:                     }
 2288: 		    if($env{'form.checkPlag'}){
 2289: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2290: 			    &most_similar($uname,$udom,$symb,$subval);
 2291: 			if ($osim) {
 2292: 			    $osim=int($osim*100.0);
 2293: 			    my %old_course_desc = 
 2294: 				&Apache::lonnet::coursedescription($ocrsid,
 2295: 								   {'one_time' => 1});
 2296: 
 2297:                             if ($hide eq 'anon') {
 2298:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2299:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2300:                             } else {
 2301: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2302: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2303: 				        $osim,
 2304: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2305: 				        $old_course_desc{'description'},
 2306: 				        $old_course_desc{'num'},
 2307: 				        $old_course_desc{'domain'}).
 2308: 				    '</span></h3><blockquote><i>'.
 2309: 				    &keywords_highlight($oessay).
 2310: 				    '</i></blockquote><hr />';
 2311:                             }
 2312: 			}
 2313: 		    }
 2314: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2315:                                          undef,$type,$trial,$rndseed);
 2316: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2317: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2318: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2319: 			my $display_part=&get_display_part($partid,$symb);
 2320:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2321:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2322:                             ' <span class="LC_internal_info">'.
 2323:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2324:                             '</span>&nbsp; &nbsp;';
 2325: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2326: 			if (@$files) {
 2327:                             if ($hide eq 'anon') {
 2328:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2329:                             } else {
 2330:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2331:                                             .'<br /><span class="LC_warning">';
 2332:                                 if(@$files == 1) {
 2333:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2334:                                 } else {
 2335:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2336:                                 }
 2337:                                 $lastsubonly .= '</span>';
 2338: 
 2339:                                 foreach my $file (@$files) {
 2340:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2341:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2342:                                 }
 2343:                             }
 2344: 			    $lastsubonly.='<br />';
 2345: 			}
 2346:                         if ($hide eq 'anon') {
 2347:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2348:                         } else {
 2349: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
 2350: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2351: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2352:                         }
 2353: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2354: 			$lastsubonly.='</div>';
 2355: 		    }
 2356: 		}
 2357: 	    }
 2358: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2359: 	}
 2360: 	$request->print($lastsubonly);
 2361:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2362: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2363: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2364:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2365: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2366: 								 $env{'request.course.id'},
 2367: 								 $last,'.submission',
 2368: 								 'Apache::grades::keywords_highlight'));
 2369:     }
 2370: 
 2371:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2372: 	.$udom.'" />'."\n");
 2373:     # return if view submission with no grading option
 2374:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2375: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2376: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2377: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2378: 	$toGrade.='</div>'."\n";
 2379: 	if (($env{'form.command'} eq 'submission') || 
 2380: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2381: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2382: 	}
 2383: 	$request->print($toGrade);
 2384: 	return;
 2385:     } else {
 2386: 	$request->print('</div>'."\n");
 2387:     }
 2388: 
 2389:     # essay grading message center
 2390:     if ($env{'form.handgrade'} eq 'yes') {
 2391: 	my $result='<div class="LC_grade_message_center">';
 2392:     
 2393: 	$result.='<div class="LC_grade_message_center_header">'.
 2394: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2395: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2396: 	my $msgfor = $givenn.' '.$lastname;
 2397: 	if (scalar(@$col_fullnames) > 0) {
 2398: 	    my $lastone = pop(@$col_fullnames);
 2399: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2400: 	}
 2401: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2402: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2403: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2404: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2405: 	    ',\''.$msgfor.'\');" target="_self">'.
 2406: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2407: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2408: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2409: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2410: 	    '<br />&nbsp;('.
 2411: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2412: 	$result.='</div></div>';
 2413: 	$request->print($result);
 2414:     }
 2415: 
 2416:     my %seen = ();
 2417:     my @partlist;
 2418:     my @gradePartRespid;
 2419:     my @part_response_id = &flatten_responseType($responseType);
 2420:     $request->print(
 2421:         '<div class="LC_Box">'
 2422:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2423:     );
 2424:     $request->print(&gradeBox_start());
 2425:     foreach my $part_response_id (@part_response_id) {
 2426:     	my ($partid,$respid) = @{ $part_response_id };
 2427: 	my $part_resp = join('_',@{ $part_response_id });
 2428: 	next if ($seen{$partid} > 0);
 2429: 	$seen{$partid}++;
 2430: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2431: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2432: 	push(@partlist,$partid);
 2433: 	push(@gradePartRespid,$partid.'.'.$respid);
 2434: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2435:     }
 2436:     $request->print(&gradeBox_end()); # </div>
 2437:     $request->print('</div>');
 2438: 
 2439:     $request->print('<div class="LC_grade_info_links">');
 2440:     $request->print('</div>');
 2441: 
 2442:     $result='<input type="hidden" name="partlist'.$counter.
 2443: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2444:     $result.='<input type="hidden" name="gradePartRespid'.
 2445: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2446:     my $ctr = 0;
 2447:     while ($ctr < scalar(@partlist)) {
 2448: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2449: 	    $partlist[$ctr].'" />'."\n";
 2450: 	$ctr++;
 2451:     }
 2452:     $request->print($result.''."\n");
 2453: 
 2454: # Done with printing info for one student
 2455: 
 2456:     $request->print('</div>');#LC_grade_show_user
 2457: 
 2458: 
 2459:     # print end of form
 2460:     if ($counter == $total) {
 2461:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2462: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2463: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2464: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2465: 	my $ntstu ='<select name="NTSTU">'.
 2466: 	    '<option>1</option><option>2</option>'.
 2467: 	    '<option>3</option><option>5</option>'.
 2468: 	    '<option>7</option><option>10</option></select>'."\n";
 2469: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2470: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2471:         $endform.=&mt('[_1]student(s)',$ntstu);
 2472: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2473: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2474: 	    '<input type="button" value="'.&mt('Next').'" '.
 2475: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2476:         $endform.='<span class="LC_warning">'.
 2477:                   &mt('(Next and Previous (student) do not save the scores.)').
 2478:                   '</span>'."\n" ;
 2479:         $endform.="<input type='hidden' value='".&get_increment().
 2480:             "' name='increment' />";
 2481: 	$endform.='</td></tr></table></form>';
 2482: 	$endform.=&show_grading_menu_form($symb);
 2483: 	$request->print($endform);
 2484:     }
 2485:     return '';
 2486: }
 2487: 
 2488: sub check_collaborators {
 2489:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2490:     my ($result,@col_fullnames);
 2491:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2492:     foreach my $part (keys(%$handgrade)) {
 2493: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2494: 					'.maxcollaborators',
 2495: 					$symb,$udom,$uname);
 2496: 	next if ($ncol <= 0);
 2497: 	$part =~ s/\_/\./g;
 2498: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2499: 	my (@good_collaborators, @bad_collaborators);
 2500: 	foreach my $possible_collaborator
 2501: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2502: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2503: 	    next if ($possible_collaborator eq '');
 2504: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2505: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2506: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2507: 	    # Doing this grep allows 'fuzzy' specification
 2508: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2509: 			       keys(%$classlist));
 2510: 	    if (! scalar(@matches)) {
 2511: 		push(@bad_collaborators, $possible_collaborator);
 2512: 	    } else {
 2513: 		push(@good_collaborators, @matches);
 2514: 	    }
 2515: 	}
 2516: 	if (scalar(@good_collaborators) != 0) {
 2517: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2518: 	    foreach my $name (@good_collaborators) {
 2519: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2520: 		push(@col_fullnames, $givenn.' '.$lastname);
 2521: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2522: 	    }
 2523: 	    $result.='</ol><br />'."\n";
 2524: 	    my ($part)=split(/\./,$part);
 2525: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2526: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2527: 		"\n";
 2528: 	}
 2529: 	if (scalar(@bad_collaborators) > 0) {
 2530: 	    $result.='<div class="LC_warning">';
 2531: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2532: 	    $result .= '</div>';
 2533: 	}         
 2534: 	if (scalar(@bad_collaborators > $ncol)) {
 2535: 	    $result .= '<div class="LC_warning">';
 2536: 	    $result .= &mt('This student has submitted too many '.
 2537: 		'collaborators.  Maximum is [_1].',$ncol);
 2538: 	    $result .= '</div>';
 2539: 	}
 2540:     }
 2541:     return ($result,$fullname,\@col_fullnames);
 2542: }
 2543: 
 2544: #--- Retrieve the last submission for all the parts
 2545: sub get_last_submission {
 2546:     my ($returnhash)=@_;
 2547:     my (@string,$timestamp,%lasthidden);
 2548:     if ($$returnhash{'version'}) {
 2549: 	my %lasthash=();
 2550: 	my ($version);
 2551: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2552: 	    foreach my $key (sort(split(/\:/,
 2553: 					$$returnhash{$version.':keys'}))) {
 2554: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2555: 		$timestamp = 
 2556: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2557: 	    }
 2558: 	}
 2559:         my (%typeparts,%randombytry);
 2560:         my $showsurv = 
 2561:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2562:         foreach my $key (sort(keys(%lasthash))) {
 2563:             if ($key =~ /\.type$/) {
 2564:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2565:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2566:                     ($lasthash{$key} eq 'randomizetry')) {
 2567:                     my ($ign,@parts) = split(/\./,$key);
 2568:                     pop(@parts);
 2569:                     my $id = join('.',@parts);
 2570:                     if ($lasthash{$key} eq 'randomizetry') {
 2571:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2572:                     } else {
 2573:                         unless ($showsurv) {
 2574:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2575:                         }
 2576:                     }
 2577:                     delete($lasthash{$key});
 2578:                 }
 2579:             }
 2580:         }
 2581:         my @hidden = keys(%typeparts);
 2582:         my @randomize = keys(%randombytry);
 2583: 	foreach my $key (keys(%lasthash)) {
 2584: 	    next if ($key !~ /\.submission$/);
 2585:             my $hide;
 2586:             if (@hidden) {
 2587:                 foreach my $id (@hidden) {
 2588:                     if ($key =~ /^\Q$id\E/) {
 2589:                         $hide = 'anon';
 2590:                         last;
 2591:                     }
 2592:                 }
 2593:             }
 2594:             unless ($hide) {
 2595:                 if (@randomize) {
 2596:                     foreach my $id (@hidden) {
 2597:                         if ($key =~ /^\Q$id\E/) {
 2598:                             $hide = 'rand';
 2599:                             last;
 2600:                         }
 2601:                     }
 2602:                 }
 2603:             }
 2604: 	    my ($partid,$foo) = split(/submission$/,$key);
 2605: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2606: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2607: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2608: 	}
 2609:     }
 2610:     if (!@string) {
 2611: 	$string[0] =
 2612: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2613:     }
 2614:     return (\@string,\$timestamp);
 2615: }
 2616: 
 2617: #--- High light keywords, with style choosen by user.
 2618: sub keywords_highlight {
 2619:     my $string    = shift;
 2620:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2621:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2622:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2623:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2624:     foreach my $keyword (@keylist) {
 2625: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2626:     }
 2627:     return $string;
 2628: }
 2629: 
 2630: # For Tasks provide a mechanism to display previous version for one specific student
 2631: 
 2632: sub show_previous_task_version {
 2633:     my ($request,$symb) = @_;
 2634:     if ($symb eq '') {
 2635:         $request->print("Unable to handle ambiguous references.");
 2636: 
 2637:         return '';
 2638:     }
 2639:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2640:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2641:     if (!&canview($usec)) {
 2642:         $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
 2643:                         $uname.':'.$udom.' in section '.$usec.' in course id '.
 2644:                         $env{'request.course.id'}.')</span>');
 2645:         return;
 2646:     }
 2647:     my $mode = 'both';
 2648:     my $isTask = ($symb =~/\.task$/);
 2649:     if ($isTask) {
 2650:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2651:             if ($env{'form.fullname'} eq '') {
 2652:                 $env{'form.fullname'} =
 2653:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2654:             }
 2655:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2656:             $request->print("\n\n".
 2657:                             '<div class="LC_grade_show_user">'.
 2658:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2659:                             '</h2>'."\n");
 2660:             &Apache::lonxml::clear_problem_counter();
 2661:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2662:                             {'previousversion' => $env{'form.previousversion'} }));
 2663:             $request->print("\n</div>");
 2664:         }
 2665:     }
 2666:     return;
 2667: }
 2668: 
 2669: sub choose_task_version_form {
 2670:     my ($symb,$uname,$udom,$nomenu) = @_;
 2671:     my $isTask = ($symb =~/\.task$/);
 2672:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2673:     if ($isTask) {
 2674:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2675:                                               $udom,$uname);
 2676:         if (($record{'resource.0.version'} eq '') ||
 2677:             ($record{'resource.0.version'} < 2)) {
 2678:             return ($record{'resource.0.version'},
 2679:                     $record{'resource.0.version'},$result,$js);
 2680:         } else {
 2681:             $current = $record{'resource.0.version'};
 2682:         }
 2683:         if ($env{'form.previousversion'}) {
 2684:             $displayed = $env{'form.previousversion'};
 2685:             $rowtitle = &mt('Choose another version:')
 2686:         } else {
 2687:             $displayed = $current;
 2688:             $rowtitle = &mt('Show earlier version:');
 2689:         }
 2690:         $result = '<div class="LC_left_float">';
 2691:         my $list;
 2692:         my $numversions = 0;
 2693:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2694:             if ($i == $current) {
 2695:                 if (!$env{'form.previousversion'} || $nomenu) {
 2696:                     next;
 2697:                 } else {
 2698:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2699:                     $numversions ++;
 2700:                 }
 2701:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2702:                 unless ($i == $env{'form.previousversion'}) {
 2703:                     $numversions ++;
 2704:                 }
 2705:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2706:             }
 2707:         }
 2708:         if ($numversions) {
 2709:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2710:             $result .=
 2711:                 '<form name="getprev" method="post" action=""'.
 2712:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2713:                 &Apache::loncommon::start_data_table().
 2714:                 &Apache::loncommon::start_data_table_row().
 2715:                 '<th align="left">'.$rowtitle.'</th>'.
 2716:                 '<td><select name="version">'.
 2717:                 '<option>'.&mt('Select').'</option>'.
 2718:                 $list.
 2719:                 '</select></td>'.
 2720:                 &Apache::loncommon::end_data_table_row();
 2721:             unless ($nomenu) {
 2722:                 $result .= &Apache::loncommon::start_data_table_row().
 2723:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2724:                 '<td><span class="LC_nobreak">'.
 2725:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2726:                 &mt('Yes').'</label>'.
 2727:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2728:                 '</span></td>'.
 2729:                 &Apache::loncommon::end_data_table_row();
 2730:             }
 2731:             $result .=
 2732:                 &Apache::loncommon::start_data_table_row().
 2733:                 '<th align="left">&nbsp;</th>'.
 2734:                 '<td>'.
 2735:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2736:                 '</td>'.
 2737:                 &Apache::loncommon::end_data_table_row().
 2738:                 &Apache::loncommon::end_data_table().
 2739:                 '</form>';
 2740:             $js = &previous_display_javascript($nomenu,$current);
 2741:         } elsif ($displayed && $nomenu) {
 2742:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2743:         } else {
 2744:             $result .= &mt('No previous versions to show for this student');
 2745:         }
 2746:         $result .= '</div>';
 2747:     }
 2748:     return ($current,$displayed,$result,$js);
 2749: }
 2750: 
 2751: sub previous_display_javascript {
 2752:     my ($nomenu,$current) = @_;
 2753:     my $js = <<"JSONE";
 2754: <script type="text/javascript">
 2755: // <![CDATA[
 2756: function previousVersion(uname,udom,symb) {
 2757:     var current = '$current';
 2758:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2759:     var prevstr = new RegExp("^\\\\d+\$");
 2760:     if (!prevstr.test(version)) {
 2761:         return false;
 2762:     }
 2763:     var url = '';
 2764:     if (version == current) {
 2765:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2766:     } else {
 2767:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2768:     }
 2769: JSONE
 2770:     if ($nomenu) {
 2771:         $js .= <<"JSTWO";
 2772:     document.location.href = url;
 2773: JSTWO
 2774:     } else {
 2775:         $js .= <<"JSTHREE";
 2776:     var newwin = 0;
 2777:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2778:         if (document.getprev.prevwin[i].checked == true) {
 2779:             newwin = document.getprev.prevwin[i].value;
 2780:         }
 2781:     }
 2782:     if (newwin == 1) {
 2783:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2784:         url = url+'&inhibitmenu=yes';
 2785:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2786:             previousWin = window.open(url,'',options,1);
 2787:         } else {
 2788:             previousWin.location.href = url;
 2789:         }
 2790:         previousWin.focus();
 2791:         return false;
 2792:     } else {
 2793:         document.location.href = url;
 2794:         return false;
 2795:     }
 2796: JSTHREE
 2797:     }
 2798:     $js .= <<"ENDJS";
 2799:     return false;
 2800: }
 2801: // ]]>
 2802: </script>
 2803: ENDJS
 2804: 
 2805: }
 2806: 
 2807: #--- Called from submission routine
 2808: sub processHandGrade {
 2809:     my ($request) = shift;
 2810:     my ($symb)   = &get_symb($request);
 2811:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2812:     my $button = $env{'form.gradeOpt'};
 2813:     my $ngrade = $env{'form.NCT'};
 2814:     my $ntstu  = $env{'form.NTSTU'};
 2815:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2816:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2817: 
 2818:     if ($button eq 'Save & Next') {
 2819: 	my $ctr = 0;
 2820: 	while ($ctr < $ngrade) {
 2821: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2822: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2823: 	    if ($errorflag eq 'no_score') {
 2824: 		$ctr++;
 2825: 		next;
 2826: 	    }
 2827: 	    if ($errorflag eq 'not_allowed') {
 2828: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2829: 		$ctr++;
 2830: 		next;
 2831: 	    }
 2832: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2833: 	    my ($subject,$message,$msgstatus) = ('','','');
 2834: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2835:             my ($feedurl,$showsymb) =
 2836: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2837: 	    my $messagetail;
 2838: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2839: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2840: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2841: 		$subject.=' ['.$restitle.']';
 2842: 		my (@msgnum) = split(/,/,$includemsg);
 2843: 		foreach (@msgnum) {
 2844: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2845: 		}
 2846: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2847: 		if ($env{'form.withgrades'.$ctr}) {
 2848: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2849: 		    $messagetail = " for <a href=\"".
 2850: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2851: 		}
 2852: 		$msgstatus = 
 2853:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2854: 						     $message.$messagetail,
 2855:                                                      undef,$feedurl,undef,
 2856:                                                      undef,undef,$showsymb,
 2857:                                                      $restitle);
 2858: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2859: 				$msgstatus.'<br />');
 2860: 	    }
 2861: 	    if ($env{'form.collaborator'.$ctr}) {
 2862: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2863: 		foreach my $collabstr (@collabstrs) {
 2864: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2865: 		    foreach my $collaborator (@collaborators) {
 2866: 			my ($errorflag,$pts,$wgt) = 
 2867: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2868: 					   $env{'form.unamedom'.$ctr},$part);
 2869: 			if ($errorflag eq 'not_allowed') {
 2870: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2871: 			    next;
 2872: 			} elsif ($message ne '') {
 2873: 			    my ($baseurl,$showsymb) = 
 2874: 				&get_feedurl_and_symb($symb,$collaborator,
 2875: 						      $udom);
 2876: 			    if ($env{'form.withgrades'.$ctr}) {
 2877: 				$messagetail = " for <a href=\"".
 2878:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2879: 			    }
 2880: 			    $msgstatus = 
 2881: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2882: 			}
 2883: 		    }
 2884: 		}
 2885: 	    }
 2886: 	    $ctr++;
 2887: 	}
 2888:     }
 2889: 
 2890:     if ($env{'form.handgrade'} eq 'yes') {
 2891: 	# Keywords sorted in alphabatical order
 2892: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2893: 	my %keyhash = ();
 2894: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2895: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2896: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2897: 	$env{'form.keywords'} = join(' ',@keywords);
 2898: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2899: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2900: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2901: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2902: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2903: 
 2904: 	# message center - Order of message gets changed. Blank line is eliminated.
 2905: 	# New messages are saved in env for the next student.
 2906: 	# All messages are saved in nohist_handgrade.db
 2907: 	my ($ctr,$idx) = (1,1);
 2908: 	while ($ctr <= $env{'form.savemsgN'}) {
 2909: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2910: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2911: 		$idx++;
 2912: 	    }
 2913: 	    $ctr++;
 2914: 	}
 2915: 	$ctr = 0;
 2916: 	while ($ctr < $ngrade) {
 2917: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2918: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2919: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2920: 		$idx++;
 2921: 	    }
 2922: 	    $ctr++;
 2923: 	}
 2924: 	$env{'form.savemsgN'} = --$idx;
 2925: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2926: 	my $putresult = &Apache::lonnet::put
 2927: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2928:     }
 2929:     # Called by Save & Refresh from Highlight Attribute Window
 2930:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2931:     if ($env{'form.refresh'} eq 'on') {
 2932: 	my ($ctr,$total) = (0,0);
 2933: 	while ($ctr < $ngrade) {
 2934: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2935: 	    $ctr++;
 2936: 	}
 2937: 	$env{'form.NTSTU'}=$ngrade;
 2938: 	$ctr = 0;
 2939: 	while ($ctr < $total) {
 2940: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2941: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2942: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2943: 	    &submission($request,$ctr,$total-1);
 2944: 	    $ctr++;
 2945: 	}
 2946: 	return '';
 2947:     }
 2948: 
 2949: # Go directly to grade student - from submission or link from chart page
 2950:     if ($button eq 'Grade Student') {
 2951: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2952: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2953: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2954: 	$env{'form.fullname'} = $$fullname{$processUser};
 2955: 	&submission($request,0,0);
 2956: 	return '';
 2957:     }
 2958: 
 2959:     # Get the next/previous one or group of students
 2960:     my $firststu = $env{'form.unamedom0'};
 2961:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2962:     my $ctr = 2;
 2963:     while ($laststu eq '') {
 2964: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2965: 	$ctr++;
 2966: 	$laststu = $firststu if ($ctr > $ngrade);
 2967:     }
 2968: 
 2969:     my (@parsedlist,@nextlist);
 2970:     my ($nextflg) = 0;
 2971:     foreach my $item (sort 
 2972: 	     {
 2973: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2974: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2975: 		 }
 2976: 		 return $a cmp $b;
 2977: 	     } (keys(%$fullname))) {
 2978: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2979: 	    push(@parsedlist,$item);
 2980: 	}
 2981: 	$nextflg = 1 if ($item eq $laststu);
 2982: 	if ($button eq 'Previous') {
 2983: 	    last if ($item eq $firststu);
 2984: 	    push(@parsedlist,$item);
 2985: 	}
 2986:     }
 2987:     $ctr = 0;
 2988:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2989:     my $res_error;
 2990:     my ($partlist) = &response_type($symb,\$res_error);
 2991:     if ($res_error) {
 2992:         $request->print(&navmap_errormsg());
 2993:         return;
 2994:     }
 2995:     foreach my $student (@parsedlist) {
 2996: 	my $submitonly=$env{'form.submitonly'};
 2997: 	my ($uname,$udom) = split(/:/,$student);
 2998: 	
 2999: 	if ($submitonly eq 'queued') {
 3000: 	    my %queue_status = 
 3001: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3002: 							$udom,$uname);
 3003: 	    next if (!defined($queue_status{'gradingqueue'}));
 3004: 	}
 3005: 
 3006: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3007: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3008: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3009: 	    my $submitted = 0;
 3010: 	    my $ungraded = 0;
 3011: 	    my $incorrect = 0;
 3012: 	    foreach my $item (keys(%status)) {
 3013: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3014: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3015: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3016: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3017: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3018: 		    $submitted = 0;
 3019: 		}
 3020: 	    }
 3021: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3022: 				     $submitonly eq 'incorrect' ||
 3023: 				     $submitonly eq 'graded'));
 3024: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3025: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3026: 	}
 3027: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3028: 	last if ($ctr == $ntstu);
 3029: 	$ctr++;
 3030:     }
 3031: 
 3032:     $ctr = 0;
 3033:     my $total = scalar(@nextlist)-1;
 3034: 
 3035:     foreach (sort(@nextlist)) {
 3036: 	my ($uname,$udom,$submitter) = split(/:/);
 3037: 	$env{'form.student'}  = $uname;
 3038: 	$env{'form.userdom'}  = $udom;
 3039: 	$env{'form.fullname'} = $$fullname{$_};
 3040: 	&submission($request,$ctr,$total);
 3041: 	$ctr++;
 3042:     }
 3043:     if ($total < 0) {
 3044: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3045: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3046: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3047: 	$the_end.=&show_grading_menu_form($symb);
 3048: 	$request->print($the_end);
 3049:     }
 3050:     return '';
 3051: }
 3052: 
 3053: #---- Save the score and award for each student, if changed
 3054: sub saveHandGrade {
 3055:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3056:     my @version_parts;
 3057:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3058: 					   $env{'request.course.id'});
 3059:     if (!&canmodify($usec)) { return('not_allowed'); }
 3060:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3061:     my @parts_graded;
 3062:     my %newrecord  = ();
 3063:     my ($pts,$wgt) = ('','');
 3064:     my %aggregate = ();
 3065:     my $aggregateflag = 0;
 3066:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3067:     foreach my $new_part (@parts) {
 3068: 	#collaborator ($submi may vary for different parts
 3069: 	if ($submitter && $new_part ne $part) { next; }
 3070: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3071: 	if ($dropMenu eq 'excused') {
 3072: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3073: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3074: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3075: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3076: 		}
 3077: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3078: 	    }
 3079: 	} elsif ($dropMenu eq 'reset status'
 3080: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3081: 	    foreach my $key (keys(%record)) {
 3082: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3083: 	    }
 3084: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3085: 		"$env{'user.name'}:$env{'user.domain'}";
 3086:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3087: 
 3088:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3089: 					       [$new_part]);
 3090:             my $aggtries =$totaltries;
 3091:             if ($last_resets{$new_part}) {
 3092:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3093: 					   $new_part);
 3094:             }
 3095: 
 3096:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3097:             if ($aggtries > 0) {
 3098:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3099:                 $aggregateflag = 1;
 3100:             }
 3101: 	} elsif ($dropMenu eq '') {
 3102: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3103: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3104: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3105: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3106: 		next;
 3107: 	    }
 3108: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3109: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3110: 	    my $partial= $pts/$wgt;
 3111: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3112: 		#do not update score for part if not changed.
 3113:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3114: 		next;
 3115: 	    } else {
 3116: 	        push(@parts_graded,$new_part);
 3117: 	    }
 3118: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3119: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3120: 	    }
 3121: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3122: 	    if ($partial == 0) {
 3123: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3124: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3125: 		}
 3126: 	    } else {
 3127: 		if ($record{$reckey} ne 'correct_by_override') {
 3128: 		    $newrecord{$reckey} = 'correct_by_override';
 3129: 		}
 3130: 	    }	    
 3131: 	    if ($submitter && 
 3132: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3133: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3134: 	    }
 3135: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3136: 		"$env{'user.name'}:$env{'user.domain'}";
 3137: 	}
 3138: 	# unless problem has been graded, set flag to version the submitted files
 3139: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3140: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3141: 	        $dropMenu eq 'reset status')
 3142: 	   {
 3143: 	    push(@version_parts,$new_part);
 3144: 	}
 3145:     }
 3146:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3147:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3148: 
 3149:     if (%newrecord) {
 3150:         if (@version_parts) {
 3151:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3152:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3153: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3154: 	    foreach my $new_part (@version_parts) {
 3155: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3156: 				$new_part,\%newrecord);
 3157: 	    }
 3158:         }
 3159: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3160: 				$env{'request.course.id'},$domain,$stuname);
 3161: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3162: 				     $cdom,$cnum,$domain,$stuname);
 3163:     }
 3164:     if ($aggregateflag) {
 3165:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3166: 			      $cdom,$cnum);
 3167:     }
 3168:     return ('',$pts,$wgt);
 3169: }
 3170: 
 3171: sub check_and_remove_from_queue {
 3172:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3173:     my @ungraded_parts;
 3174:     foreach my $part (@{$parts}) {
 3175: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3176: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3177: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3178: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3179: 		) {
 3180: 	    push(@ungraded_parts, $part);
 3181: 	}
 3182:     }
 3183:     if ( !@ungraded_parts ) {
 3184: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3185: 					       $cnum,$domain,$stuname);
 3186:     }
 3187: }
 3188: 
 3189: sub handback_files {
 3190:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3191:     my $portfolio_root = '/userfiles/portfolio';
 3192:     my $res_error;
 3193:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3194:     if ($res_error) {
 3195:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3196:         return;
 3197:     }
 3198:     my @handedback;
 3199:     my $file_msg;
 3200:     my @part_response_id = &flatten_responseType($responseType);
 3201:     foreach my $part_response_id (@part_response_id) {
 3202:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3203: 	my $part_resp = join('_',@{ $part_response_id });
 3204:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3205:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3206:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3207: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3208:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3209:                     my ($directory,$answer_file) = 
 3210:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3211:                     my ($answer_name,$answer_ver,$answer_ext) =
 3212: 		        &file_name_version_ext($answer_file);
 3213: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3214:                     my $getpropath = 1;
 3215:                     my ($dir_list,$listerror) =
 3216:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3217:                                                  $domain,$stuname,$getpropath);
 3218: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3219:                     # fix filename
 3220:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3221:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3222:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3223:             	                                $save_file_name);
 3224:                     if ($result !~ m|^/uploaded/|) {
 3225:                         $request->print('<br /><span class="LC_error">'.
 3226:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3227:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3228:                                         '</span>');
 3229:                     } else {
 3230:                         # mark the file as read only
 3231:                         push(@handedback,$save_file_name);
 3232: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3233: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3234: 			}
 3235:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3236: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3237: 
 3238:                     }
 3239:                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 3240:                 }
 3241:             }
 3242:         }
 3243:     }
 3244:     if (@handedback > 0) {
 3245:         $request->print('<br />');
 3246:         my @what = ($symb,$env{'request.course.id'},'handback');
 3247:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3248:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3249:         my ($subject,$message);
 3250:         if (scalar(@handedback) == 1) {
 3251:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3252:         } else {
 3253:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3254:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3255:         }
 3256:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3257:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3258:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3259:         my ($feedurl,$showsymb) =
 3260:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3261:         my $restitle = &Apache::lonnet::gettitle($symb);
 3262:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3263:         my $msgstatus =
 3264:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3265:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3266:                  $restitle);
 3267:         if ($msgstatus) {
 3268:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3269:         }
 3270:     }
 3271:     return;
 3272: }
 3273: 
 3274: sub get_feedurl_and_symb {
 3275:     my ($symb,$uname,$udom) = @_;
 3276:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3277:     $url = &Apache::lonnet::clutter($url);
 3278:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3279: 					$symb,$udom,$uname);
 3280:     if ($encrypturl =~ /^yes$/i) {
 3281: 	&Apache::lonenc::encrypted(\$url,1);
 3282: 	&Apache::lonenc::encrypted(\$symb,1);
 3283:     }
 3284:     return ($url,$symb);
 3285: }
 3286: 
 3287: sub get_submitted_files {
 3288:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3289:     my @files;
 3290:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3291:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3292:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3293:     	    push(@files,$file_url.$file);
 3294:         }
 3295:     }
 3296:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3297:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3298:     }
 3299:     return (\@files);
 3300: }
 3301: 
 3302: # ----------- Provides number of tries since last reset.
 3303: sub get_num_tries {
 3304:     my ($record,$last_reset,$part) = @_;
 3305:     my $timestamp = '';
 3306:     my $num_tries = 0;
 3307:     if ($$record{'version'}) {
 3308:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3309:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3310:                 $timestamp = $$record{$version.':timestamp'};
 3311:                 if ($timestamp > $last_reset) {
 3312:                     $num_tries ++;
 3313:                 } else {
 3314:                     last;
 3315:                 }
 3316:             }
 3317:         }
 3318:     }
 3319:     return $num_tries;
 3320: }
 3321: 
 3322: # ----------- Determine decrements required in aggregate totals 
 3323: sub decrement_aggs {
 3324:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3325:     my %decrement = (
 3326:                         attempts => 0,
 3327:                         users => 0,
 3328:                         correct => 0
 3329:                     );
 3330:     $decrement{'attempts'} = $aggtries;
 3331:     if ($solvedstatus =~ /^correct/) {
 3332:         $decrement{'correct'} = 1;
 3333:     }
 3334:     if ($aggtries == $totaltries) {
 3335:         $decrement{'users'} = 1;
 3336:     }
 3337:     foreach my $type (keys(%decrement)) {
 3338:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3339:     }
 3340:     return;
 3341: }
 3342: 
 3343: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3344: sub get_last_resets {
 3345:     my ($symb,$courseid,$partids) =@_;
 3346:     my %last_resets;
 3347:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3348:     my $cname = $env{'course.'.$courseid.'.num'};
 3349:     my @keys;
 3350:     foreach my $part (@{$partids}) {
 3351: 	push(@keys,"$symb\0$part\0resettime");
 3352:     }
 3353:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3354: 				     $cdom,$cname);
 3355:     foreach my $part (@{$partids}) {
 3356: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3357:     }
 3358:     return %last_resets;
 3359: }
 3360: 
 3361: # ----------- Handles creating versions for portfolio files as answers
 3362: sub version_portfiles {
 3363:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3364:     my $version_parts = join('|',@$v_flag);
 3365:     my @returned_keys;
 3366:     my $parts = join('|', @$parts_graded);
 3367:     my $portfolio_root = '/userfiles/portfolio';
 3368:     foreach my $key (keys(%$record)) {
 3369:         my $new_portfiles;
 3370:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3371:             my @versioned_portfiles;
 3372:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3373:             foreach my $file (@portfiles) {
 3374:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3375:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3376: 		my ($answer_name,$answer_ver,$answer_ext) =
 3377: 		    &file_name_version_ext($answer_file);
 3378:                 my $getpropath = 1;
 3379:                 my ($dir_list,$listerror) =
 3380:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3381:                                              $stu_name,$getpropath);
 3382:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3383:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3384:                 if ($new_answer ne 'problem getting file') {
 3385:                     push(@versioned_portfiles, $directory.$new_answer);
 3386:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3387:                         [$directory.$new_answer],
 3388:                         [$symb,$env{'request.course.id'},'graded']);
 3389:                 }
 3390:             }
 3391:             $$record{$key} = join(',',@versioned_portfiles);
 3392:             push(@returned_keys,$key);
 3393:         }
 3394:     } 
 3395:     return (@returned_keys);   
 3396: }
 3397: 
 3398: sub get_next_version {
 3399:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3400:     my $version;
 3401:     if (ref($dir_list) eq 'ARRAY') {
 3402:         foreach my $row (@{$dir_list}) {
 3403:             my ($file) = split(/\&/,$row,2);
 3404:             my ($file_name,$file_version,$file_ext) =
 3405: 	        &file_name_version_ext($file);
 3406:             if (($file_name eq $answer_name) && 
 3407: 	        ($file_ext eq $answer_ext)) {
 3408:                 # gets here if filename and extension match, 
 3409:                 # regardless of version
 3410:                 if ($file_version ne '') {
 3411:                     # a versioned file is found  so save it for later
 3412:                     if ($file_version > $version) {
 3413: 		        $version = $file_version;
 3414:                     }
 3415: 	        }
 3416:             }
 3417:         }
 3418:     }
 3419:     $version ++;
 3420:     return($version);
 3421: }
 3422: 
 3423: sub version_selected_portfile {
 3424:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3425:     my ($answer_name,$answer_ver,$answer_ext) =
 3426:         &file_name_version_ext($file_name);
 3427:     my $new_answer;
 3428:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3429:     if($env{'form.copy'} eq '-1') {
 3430:         $new_answer = 'problem getting file';
 3431:     } else {
 3432:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3433:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3434:                             $stu_name,$domain,'copy',
 3435: 		        '/portfolio'.$directory.$new_answer);
 3436:     }    
 3437:     return ($new_answer);
 3438: }
 3439: 
 3440: sub file_name_version_ext {
 3441:     my ($file)=@_;
 3442:     my @file_parts = split(/\./, $file);
 3443:     my ($name,$version,$ext);
 3444:     if (@file_parts > 1) {
 3445: 	$ext=pop(@file_parts);
 3446: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3447: 	    $version=pop(@file_parts);
 3448: 	}
 3449: 	$name=join('.',@file_parts);
 3450:     } else {
 3451: 	$name=join('.',@file_parts);
 3452:     }
 3453:     return($name,$version,$ext);
 3454: }
 3455: 
 3456: #--------------------------------------------------------------------------------------
 3457: #
 3458: #-------------------------- Next few routines handles grading by section or whole class
 3459: #
 3460: #--- Javascript to handle grading by section or whole class
 3461: sub viewgrades_js {
 3462:     my ($request) = shift;
 3463: 
 3464:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3465:     $request->print(<<VIEWJAVASCRIPT);
 3466: <script type="text/javascript" language="javascript">
 3467:    function writePoint(partid,weight,point) {
 3468: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3469: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3470: 	if (point == "textval") {
 3471: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3472: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3473: 		alert("$alertmsg"+parseFloat(point));
 3474: 		var resetbox = false;
 3475: 		for (var i=0; i<radioButton.length; i++) {
 3476: 		    if (radioButton[i].checked) {
 3477: 			textbox.value = i;
 3478: 			resetbox = true;
 3479: 		    }
 3480: 		}
 3481: 		if (!resetbox) {
 3482: 		    textbox.value = "";
 3483: 		}
 3484: 		return;
 3485: 	    }
 3486: 	    if (parseFloat(point) > parseFloat(weight)) {
 3487: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3488: 				   ") greater than the weight for the part. Accept?");
 3489: 		if (resp == false) {
 3490: 		    textbox.value = "";
 3491: 		    return;
 3492: 		}
 3493: 	    }
 3494: 	    for (var i=0; i<radioButton.length; i++) {
 3495: 		radioButton[i].checked=false;
 3496: 		if (parseFloat(point) == i) {
 3497: 		    radioButton[i].checked=true;
 3498: 		}
 3499: 	    }
 3500: 
 3501: 	} else {
 3502: 	    textbox.value = parseFloat(point);
 3503: 	}
 3504: 	for (i=0;i<document.classgrade.total.value;i++) {
 3505: 	    var user = document.classgrade["ctr"+i].value;
 3506: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3507: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3508: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3509: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3510: 	    if (saveval != "correct") {
 3511: 		scorename.value = point;
 3512: 		if (selname[0].selected != true) {
 3513: 		    selname[0].selected = true;
 3514: 		}
 3515: 	    }
 3516: 	}
 3517: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3518:     }
 3519: 
 3520:     function writeRadText(partid,weight) {
 3521: 	var selval   = document.classgrade["SELVAL_"+partid];
 3522: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3523:         var override = document.classgrade["FORCE_"+partid].checked;
 3524: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3525: 	if (selval[1].selected || selval[2].selected) {
 3526: 	    for (var i=0; i<radioButton.length; i++) {
 3527: 		radioButton[i].checked=false;
 3528: 
 3529: 	    }
 3530: 	    textbox.value = "";
 3531: 
 3532: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3533: 		var user = document.classgrade["ctr"+i].value;
 3534: 		user = user.replace(new RegExp(':', 'g'),"_");
 3535: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3536: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3537: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3538: 		if ((saveval != "correct") || override) {
 3539: 		    scorename.value = "";
 3540: 		    if (selval[1].selected) {
 3541: 			selname[1].selected = true;
 3542: 		    } else {
 3543: 			selname[2].selected = true;
 3544: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3545: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3546: 		    }
 3547: 		}
 3548: 	    }
 3549: 	} else {
 3550: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3551: 		var user = document.classgrade["ctr"+i].value;
 3552: 		user = user.replace(new RegExp(':', 'g'),"_");
 3553: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3554: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3555: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3556: 		if ((saveval != "correct") || override) {
 3557: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3558: 		    selname[0].selected = true;
 3559: 		}
 3560: 	    }
 3561: 	}	    
 3562:     }
 3563: 
 3564:     function changeSelect(partid,user) {
 3565: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3566: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3567: 	var point  = textbox.value;
 3568: 	var weight = document.classgrade["weight_"+partid].value;
 3569: 
 3570: 	if (isNaN(point) || parseFloat(point) < 0) {
 3571: 	    alert("$alertmsg"+parseFloat(point));
 3572: 	    textbox.value = "";
 3573: 	    return;
 3574: 	}
 3575: 	if (parseFloat(point) > parseFloat(weight)) {
 3576: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3577: 			       ") greater than the weight of the part. Accept?");
 3578: 	    if (resp == false) {
 3579: 		textbox.value = "";
 3580: 		return;
 3581: 	    }
 3582: 	}
 3583: 	selval[0].selected = true;
 3584:     }
 3585: 
 3586:     function changeOneScore(partid,user) {
 3587: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3588: 	if (selval[1].selected || selval[2].selected) {
 3589: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3590: 	    if (selval[2].selected) {
 3591: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3592: 	    }
 3593:         }
 3594:     }
 3595: 
 3596:     function resetEntry(numpart) {
 3597: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3598: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3599: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3600: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3601: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3602: 	    for (var i=0; i<radioButton.length; i++) {
 3603: 		radioButton[i].checked=false;
 3604: 
 3605: 	    }
 3606: 	    textbox.value = "";
 3607: 	    selval[0].selected = true;
 3608: 
 3609: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3610: 		var user = document.classgrade["ctr"+i].value;
 3611: 		user = user.replace(new RegExp(':', 'g'),"_");
 3612: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3613: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3614: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3615: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3616: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3617: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3618: 		if (saveselval == "excused") {
 3619: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3620: 		} else {
 3621: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3622: 		}
 3623: 	    }
 3624: 	}
 3625:     }
 3626: 
 3627: </script>
 3628: VIEWJAVASCRIPT
 3629: }
 3630: 
 3631: #--- show scores for a section or whole class w/ option to change/update a score
 3632: sub viewgrades {
 3633:     my ($request) = shift;
 3634:     &viewgrades_js($request);
 3635: 
 3636:     my ($symb) = &get_symb($request);
 3637:     #need to make sure we have the correct data for later EXT calls, 
 3638:     #thus invalidate the cache
 3639:     &Apache::lonnet::devalidatecourseresdata(
 3640:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3641:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3642:     &Apache::lonnet::clear_EXT_cache_status();
 3643: 
 3644:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3645:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3646: 
 3647:     #view individual student submission form - called using Javascript viewOneStudent
 3648:     $result.=&jscriptNform($symb);
 3649: 
 3650:     #beginning of class grading form
 3651:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3652:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3653: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3654: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3655: 	&build_section_inputs().
 3656: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3657: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3658: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3659: 
 3660:     my ($common_header,$specific_header);
 3661:     if ($env{'form.section'} eq 'all') {
 3662: 	$common_header = &mt('Assign Common Grade to Class');
 3663:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3664:     } elsif ($env{'form.section'} eq 'none') {
 3665:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3666: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3667:     } else {
 3668:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3669:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3670: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3671:     }
 3672:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3673:     #radio buttons/text box for assigning points for a section or class.
 3674:     #handles different parts of a problem
 3675:     my $res_error;
 3676:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3677:     if ($res_error) {
 3678:         return &navmap_errormsg();
 3679:     }
 3680:     my %weight = ();
 3681:     my $ctsparts = 0;
 3682:     my %seen = ();
 3683:     my @part_response_id = &flatten_responseType($responseType);
 3684:     foreach my $part_response_id (@part_response_id) {
 3685:     	my ($partid,$respid) = @{ $part_response_id };
 3686: 	my $part_resp = join('_',@{ $part_response_id });
 3687: 	next if $seen{$partid};
 3688: 	$seen{$partid}++;
 3689: 	my $handgrade=$$handgrade{$part_resp};
 3690: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3691: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3692: 
 3693: 	my $display_part=&get_display_part($partid,$symb);
 3694: 	my $radio.='<table border="0"><tr>';  
 3695: 	my $ctr = 0;
 3696: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3697: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3698: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3699: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3700: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3701: 	    $ctr++;
 3702: 	}
 3703: 	$radio.='</tr></table>';
 3704: 	my $line = '<input type="text" name="TEXTVAL_'.
 3705: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3706: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3707: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3708: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3709: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3710: 		$weight{$partid}.')"> '.
 3711: 	    '<option selected="selected"> </option>'.
 3712: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3713: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3714: 	    '</select></td>'.
 3715:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3716: 	$line.='<input type="hidden" name="partid_'.
 3717: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3718: 	$line.='<input type="hidden" name="weight_'.
 3719: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3720: 
 3721: 	$result.=
 3722: 	    &Apache::loncommon::start_data_table_row()."\n".
 3723: 	    '<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>'.
 3724: 	    &Apache::loncommon::end_data_table_row()."\n";
 3725: 	$ctsparts++;
 3726:     }
 3727:     $result.=&Apache::loncommon::end_data_table()."\n".
 3728: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3729:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3730: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3731: 
 3732:     #table listing all the students in a section/class
 3733:     #header of table
 3734:     $result.= '<h3>'.$specific_header.'</h3>'.
 3735:               &Apache::loncommon::start_data_table().
 3736: 	      &Apache::loncommon::start_data_table_header_row().
 3737: 	      '<th>'.&mt('No.').'</th>'.
 3738: 	      '<th>'.&nameUserString('header')."</th>\n";
 3739:     my $partserror;
 3740:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3741:     if ($partserror) {
 3742:         return &navmap_errormsg();
 3743:     }
 3744:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3745:     my @partids = ();
 3746:     foreach my $part (@parts) {
 3747: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3748:         my $narrowtext = &mt('Tries');
 3749: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3750: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3751: 	my ($partid) = &split_part_type($part);
 3752:         push(@partids,$partid);
 3753: 	my $display_part=&get_display_part($partid,$symb);
 3754: 	if ($display =~ /^Partial Credit Factor/) {
 3755: 	    $result.='<th>'.
 3756:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3757:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3758: 	    next;
 3759: 	    
 3760: 	} else {
 3761: 	    if ($display =~ /Problem Status/) {
 3762: 		my $grade_status_mt = &mt('Grade Status');
 3763: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3764: 	    }
 3765: 	    my $part_mt = &mt('Part:');
 3766: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3767: 	}
 3768: 
 3769: 	$result.='<th>'.$display.'</th>'."\n";
 3770:     }
 3771:     $result.=&Apache::loncommon::end_data_table_header_row();
 3772: 
 3773:     my %last_resets = 
 3774: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3775: 
 3776:     #get info for each student
 3777:     #list all the students - with points and grade status
 3778:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3779:     my $ctr = 0;
 3780:     foreach (sort 
 3781: 	     {
 3782: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3783: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3784: 		 }
 3785: 		 return $a cmp $b;
 3786: 	     } (keys(%$fullname))) {
 3787: 	$ctr++;
 3788: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3789: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3790:     }
 3791:     $result.=&Apache::loncommon::end_data_table();
 3792:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3793:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3794: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3795:     if (scalar(%$fullname) eq 0) {
 3796: 	my $colspan=3+scalar(@parts);
 3797: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3798:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3799: 	$result='<span class="LC_warning">'.
 3800: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3801: 	        $section_display, $stu_status).
 3802: 	    '</span>';
 3803:     }
 3804:     $result.=&show_grading_menu_form($symb);
 3805:     return $result;
 3806: }
 3807: 
 3808: #--- call by previous routine to display each student
 3809: sub viewstudentgrade {
 3810:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3811:     my ($uname,$udom) = split(/:/,$student);
 3812:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3813:     my %aggregates = (); 
 3814:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3815: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3816: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3817: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3818: 	'\');" target="_self">'.$fullname.'</a> '.
 3819: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3820:     $student=~s/:/_/; # colon doen't work in javascript for names
 3821:     foreach my $apart (@$parts) {
 3822: 	my ($part,$type) = &split_part_type($apart);
 3823: 	my $score=$record{"resource.$part.$type"};
 3824:         $result.='<td align="center">';
 3825:         my ($aggtries,$totaltries);
 3826:         unless (exists($aggregates{$part})) {
 3827: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3828: 
 3829: 	    $aggtries = $totaltries;
 3830:             if ($$last_resets{$part}) {  
 3831:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3832: 					   $part);
 3833:             }
 3834:             $result.='<input type="hidden" name="'.
 3835:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3836:             $result.='<input type="hidden" name="'.
 3837:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3838:             $aggregates{$part} = 1;
 3839:         }
 3840: 	if ($type eq 'awarded') {
 3841: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3842: 	    $result.='<input type="hidden" name="'.
 3843: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3844: 	    $result.='<input type="text" name="'.
 3845: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3846:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3847: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3848: 	} elsif ($type eq 'solved') {
 3849: 	    my ($status,$foo)=split(/_/,$score,2);
 3850: 	    $status = 'nothing' if ($status eq '');
 3851: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3852: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3853: 	    $result.='&nbsp;<select name="'.
 3854: 		'GD_'.$student.'_'.$part.'_solved" '.
 3855:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3856: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3857: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3858: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3859: 	    $result.="</select>&nbsp;</td>\n";
 3860: 	} else {
 3861: 	    $result.='<input type="hidden" name="'.
 3862: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3863: 		    "\n";
 3864: 	    $result.='<input type="text" name="'.
 3865: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3866: 		'value="'.$score.'" size="4" /></td>'."\n";
 3867: 	}
 3868:     }
 3869:     $result.=&Apache::loncommon::end_data_table_row();
 3870:     return $result;
 3871: }
 3872: 
 3873: #--- change scores for all the students in a section/class
 3874: #    record does not get update if unchanged
 3875: sub editgrades {
 3876:     my ($request) = @_;
 3877: 
 3878:     my ($symb)=&get_symb($request);
 3879:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3880:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3881:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3882:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3883: 
 3884:     my $result= &Apache::loncommon::start_data_table().
 3885: 	&Apache::loncommon::start_data_table_header_row().
 3886: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3887: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3888:     my %scoreptr = (
 3889: 		    'correct'  =>'correct_by_override',
 3890: 		    'incorrect'=>'incorrect_by_override',
 3891: 		    'excused'  =>'excused',
 3892: 		    'ungraded' =>'ungraded_attempted',
 3893:                     'credited' =>'credit_attempted',
 3894: 		    'nothing'  => '',
 3895: 		    );
 3896:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3897: 
 3898:     my (@partid);
 3899:     my %weight = ();
 3900:     my %columns = ();
 3901:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3902: 
 3903:     my $partserror;
 3904:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3905:     if ($partserror) {
 3906:         return &navmap_errormsg();
 3907:     }
 3908:     my $header;
 3909:     while ($ctr < $env{'form.totalparts'}) {
 3910: 	my $partid = $env{'form.partid_'.$ctr};
 3911: 	push(@partid,$partid);
 3912: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3913: 	$ctr++;
 3914:     }
 3915:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3916:     foreach my $partid (@partid) {
 3917: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3918: 	    '<th align="center">'.&mt('New Score').'</th>';
 3919: 	$columns{$partid}=2;
 3920: 	foreach my $stores (@parts) {
 3921: 	    my ($part,$type) = &split_part_type($stores);
 3922: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3923: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3924: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3925: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3926:             my $narrowtext = &mt('Tries');
 3927: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3928: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3929: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3930: 	    $columns{$partid}+=2;
 3931: 	}
 3932:     }
 3933:     foreach my $partid (@partid) {
 3934: 	my $display_part=&get_display_part($partid,$symb);
 3935: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3936: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3937: 	    '</th>';
 3938: 
 3939:     }
 3940:     $result .= &Apache::loncommon::end_data_table_header_row().
 3941: 	&Apache::loncommon::start_data_table_header_row().
 3942: 	$header.
 3943: 	&Apache::loncommon::end_data_table_header_row();
 3944:     my @noupdate;
 3945:     my ($updateCtr,$noupdateCtr) = (1,1);
 3946:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3947: 	my $line;
 3948: 	my $user = $env{'form.ctr'.$i};
 3949: 	my ($uname,$udom)=split(/:/,$user);
 3950: 	my %newrecord;
 3951: 	my $updateflag = 0;
 3952: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3953: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3954: 	if (!&canmodify($usec)) {
 3955: 	    my $numcols=scalar(@partid)*4+2;
 3956: 	    push(@noupdate,
 3957: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3958: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3959: 	    next;
 3960: 	}
 3961:         my %aggregate = ();
 3962:         my $aggregateflag = 0;
 3963: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3964: 	foreach (@partid) {
 3965: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3966: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3967: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3968: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3969: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3970: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3971: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3972: 	    my $score;
 3973: 	    if ($partial eq '') {
 3974: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3975: 	    } elsif ($partial > 0) {
 3976: 		$score = 'correct_by_override';
 3977: 	    } elsif ($partial == 0) {
 3978: 		$score = 'incorrect_by_override';
 3979: 	    }
 3980: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3981: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3982: 
 3983: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3984: 		"$env{'user.name'}:$env{'user.domain'}";
 3985: 	    if ($dropMenu eq 'reset status' &&
 3986: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3987: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3988: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3989: 		$newrecord{'resource.'.$_.'.award'} = '';
 3990: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3991: 		$updateflag = 1;
 3992:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3993:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3994:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3995:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3996:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3997:                     $aggregateflag = 1;
 3998:                 }
 3999: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4000: 		$updateflag = 1;
 4001: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4002: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4003: 		$rec_update++;
 4004: 	    }
 4005: 
 4006: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4007: 		'<td align="center">'.$awarded.
 4008: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4009: 
 4010: 
 4011: 	    my $partid=$_;
 4012: 	    foreach my $stores (@parts) {
 4013: 		my ($part,$type) = &split_part_type($stores);
 4014: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4015: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4016: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4017: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4018: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4019: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4020: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4021: 		    $updateflag=1;
 4022: 		}
 4023: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4024: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4025: 	    }
 4026: 	}
 4027: 	$line.="\n";
 4028: 
 4029: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4030: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4031: 
 4032: 	if ($updateflag) {
 4033: 	    $count++;
 4034: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4035: 				    $udom,$uname);
 4036: 
 4037: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4038: 					      $cnum,$udom,$uname)) {
 4039: 		# need to figure out if should be in queue.
 4040: 		my %record =  
 4041: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4042: 					     $udom,$uname);
 4043: 		my $all_graded = 1;
 4044: 		my $none_graded = 1;
 4045: 		foreach my $part (@parts) {
 4046: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4047: 			$all_graded = 0;
 4048: 		    } else {
 4049: 			$none_graded = 0;
 4050: 		    }
 4051: 		}
 4052: 
 4053: 		if ($all_graded || $none_graded) {
 4054: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4055: 							   $symb,$cdom,$cnum,
 4056: 							   $udom,$uname);
 4057: 		}
 4058: 	    }
 4059: 
 4060: 	    $result.=&Apache::loncommon::start_data_table_row().
 4061: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4062: 		&Apache::loncommon::end_data_table_row();
 4063: 	    $updateCtr++;
 4064: 	} else {
 4065: 	    push(@noupdate,
 4066: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4067: 	    $noupdateCtr++;
 4068: 	}
 4069:         if ($aggregateflag) {
 4070:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4071: 				  $cdom,$cnum);
 4072:         }
 4073:     }
 4074:     if (@noupdate) {
 4075: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4076: 	my $numcols=scalar(@partid)*4+2;
 4077: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4078: 	    '<td align="center" colspan="'.$numcols.'">'.
 4079: 	    &mt('No Changes Occurred For the Students Below').
 4080: 	    '</td>'.
 4081: 	    &Apache::loncommon::end_data_table_row();
 4082: 	foreach my $line (@noupdate) {
 4083: 	    $result.=
 4084: 		&Apache::loncommon::start_data_table_row().
 4085: 		$line.
 4086: 		&Apache::loncommon::end_data_table_row();
 4087: 	}
 4088:     }
 4089:     $result .= &Apache::loncommon::end_data_table().
 4090: 	&show_grading_menu_form($symb);
 4091:     my $msg = '<p><b>'.
 4092: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4093: 	    $rec_update,$count).'</b><br />'.
 4094: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4095: 	'</b></p>';
 4096:     return $title.$msg.$result;
 4097: }
 4098: 
 4099: sub split_part_type {
 4100:     my ($partstr) = @_;
 4101:     my ($temp,@allparts)=split(/_/,$partstr);
 4102:     my $type=pop(@allparts);
 4103:     my $part=join('_',@allparts);
 4104:     return ($part,$type);
 4105: }
 4106: 
 4107: #------------- end of section for handling grading by section/class ---------
 4108: #
 4109: #----------------------------------------------------------------------------
 4110: 
 4111: 
 4112: #----------------------------------------------------------------------------
 4113: #
 4114: #-------------------------- Next few routines handles grading by csv upload
 4115: #
 4116: #--- Javascript to handle csv upload
 4117: sub csvupload_javascript_reverse_associate {
 4118:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4119:     my $error2=&mt('You need to specify at least one grading field');
 4120:   return(<<ENDPICK);
 4121:   function verify(vf) {
 4122:     var foundsomething=0;
 4123:     var founduname=0;
 4124:     var foundID=0;
 4125:     for (i=0;i<=vf.nfields.value;i++) {
 4126:       tw=eval('vf.f'+i+'.selectedIndex');
 4127:       if (i==0 && tw!=0) { foundID=1; }
 4128:       if (i==1 && tw!=0) { founduname=1; }
 4129:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4130:     }
 4131:     if (founduname==0 && foundID==0) {
 4132: 	alert('$error1');
 4133: 	return;
 4134:     }
 4135:     if (foundsomething==0) {
 4136: 	alert('$error2');
 4137: 	return;
 4138:     }
 4139:     vf.submit();
 4140:   }
 4141:   function flip(vf,tf) {
 4142:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4143:     var i;
 4144:     for (i=0;i<=vf.nfields.value;i++) {
 4145:       //can not pick the same destination field for both name and domain
 4146:       if (((i ==0)||(i ==1)) && 
 4147:           ((tf==0)||(tf==1)) && 
 4148:           (i!=tf) &&
 4149:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4150:         eval('vf.f'+i+'.selectedIndex=0;')
 4151:       }
 4152:     }
 4153:   }
 4154: ENDPICK
 4155: }
 4156: 
 4157: sub csvupload_javascript_forward_associate {
 4158:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4159:     my $error2=&mt('You need to specify at least one grading field');
 4160:   return(<<ENDPICK);
 4161:   function verify(vf) {
 4162:     var foundsomething=0;
 4163:     var founduname=0;
 4164:     var foundID=0;
 4165:     for (i=0;i<=vf.nfields.value;i++) {
 4166:       tw=eval('vf.f'+i+'.selectedIndex');
 4167:       if (tw==1) { foundID=1; }
 4168:       if (tw==2) { founduname=1; }
 4169:       if (tw>3) { foundsomething=1; }
 4170:     }
 4171:     if (founduname==0 && foundID==0) {
 4172: 	alert('$error1');
 4173: 	return;
 4174:     }
 4175:     if (foundsomething==0) {
 4176: 	alert('$error2');
 4177: 	return;
 4178:     }
 4179:     vf.submit();
 4180:   }
 4181:   function flip(vf,tf) {
 4182:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4183:     var i;
 4184:     //can not pick the same destination field twice
 4185:     for (i=0;i<=vf.nfields.value;i++) {
 4186:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4187:         eval('vf.f'+i+'.selectedIndex=0;')
 4188:       }
 4189:     }
 4190:   }
 4191: ENDPICK
 4192: }
 4193: 
 4194: sub csvuploadmap_header {
 4195:     my ($request,$symb,$datatoken,$distotal)= @_;
 4196:     my $javascript;
 4197:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4198: 	$javascript=&csvupload_javascript_reverse_associate();
 4199:     } else {
 4200: 	$javascript=&csvupload_javascript_forward_associate();
 4201:     }
 4202: 
 4203:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4204:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4205:     my $ignore=&mt('Ignore First Line');
 4206:     $symb = &Apache::lonenc::check_encrypt($symb);
 4207:     $request->print(<<ENDPICK);
 4208: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4209: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4210: $result
 4211: <hr />
 4212: <h3>Identify fields</h3>
 4213: Total number of records found in file: $distotal <hr />
 4214: Enter as many fields as you can. The system will inform you and bring you back
 4215: to this page if the data selected is insufficient to run your class.<hr />
 4216: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4217: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4218: <input type="hidden" name="associate"  value="" />
 4219: <input type="hidden" name="phase"      value="three" />
 4220: <input type="hidden" name="datatoken"  value="$datatoken" />
 4221: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4222: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4223: <input type="hidden" name="upfile_associate" 
 4224:                                        value="$env{'form.upfile_associate'}" />
 4225: <input type="hidden" name="symb"       value="$symb" />
 4226: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4227: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4228: <input type="hidden" name="command"    value="csvuploadoptions" />
 4229: <hr />
 4230: <script type="text/javascript" language="Javascript">
 4231: $javascript
 4232: </script>
 4233: ENDPICK
 4234:     return '';
 4235: 
 4236: }
 4237: 
 4238: sub csvupload_fields {
 4239:     my ($symb,$errorref) = @_;
 4240:     my (@parts) = &getpartlist($symb,$errorref);
 4241:     if (ref($errorref)) {
 4242:         if ($$errorref) {
 4243:             return;
 4244:         }
 4245:     }
 4246: 
 4247:     my @fields=(['ID','Student/Employee ID'],
 4248: 		['username','Student Username'],
 4249: 		['domain','Student Domain']);
 4250:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4251:     foreach my $part (sort(@parts)) {
 4252: 	my @datum;
 4253: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4254: 	my $name=$part;
 4255: 	if  (!$display) { $display = $name; }
 4256: 	@datum=($name,$display);
 4257: 	if ($name=~/^stores_(.*)_awarded/) {
 4258: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4259: 	}
 4260: 	push(@fields,\@datum);
 4261:     }
 4262:     return (@fields);
 4263: }
 4264: 
 4265: sub csvuploadmap_footer {
 4266:     my ($request,$i,$keyfields) =@_;
 4267:     $request->print(<<ENDPICK);
 4268: </table>
 4269: <input type="hidden" name="nfields" value="$i" />
 4270: <input type="hidden" name="keyfields" value="$keyfields" />
 4271: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 4272: </form>
 4273: ENDPICK
 4274: }
 4275: 
 4276: sub checkforfile_js {
 4277:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4278:     my $result =<<CSVFORMJS;
 4279: <script type="text/javascript" language="javascript">
 4280:     function checkUpload(formname) {
 4281: 	if (formname.upfile.value == "") {
 4282: 	    alert("$alertmsg");
 4283: 	    return false;
 4284: 	}
 4285: 	formname.submit();
 4286:     }
 4287:     </script>
 4288: CSVFORMJS
 4289:     return $result;
 4290: }
 4291: 
 4292: sub upcsvScores_form {
 4293:     my ($request) = shift;
 4294:     my ($symb)=&get_symb($request);
 4295:     if (!$symb) {return '';}
 4296:     my $result=&checkforfile_js();
 4297:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4298:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4299:     $result.=$table;
 4300:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4301:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4302:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4303: 	'</b></td></tr>'."\n";
 4304:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4305:     my $upload=&mt("Upload Scores");
 4306:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4307:     my $ignore=&mt('Ignore First Line');
 4308:     $symb = &Apache::lonenc::check_encrypt($symb);
 4309:     $result.=<<ENDUPFORM;
 4310: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4311: <input type="hidden" name="symb" value="$symb" />
 4312: <input type="hidden" name="command" value="csvuploadmap" />
 4313: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4314: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4315: $upfile_select
 4316: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4317: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4318: </form>
 4319: ENDUPFORM
 4320:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4321:                            &mt("How do I create a CSV file from a spreadsheet"))
 4322:     .'</td></tr></table>'."\n";
 4323:     $result.='</td></tr></table><br /><br />'."\n";
 4324:     $result.=&show_grading_menu_form($symb);
 4325:     return $result;
 4326: }
 4327: 
 4328: 
 4329: sub csvuploadmap {
 4330:     my ($request)= @_;
 4331:     my ($symb)=&get_symb($request);
 4332:     if (!$symb) {return '';}
 4333: 
 4334:     my $datatoken;
 4335:     if (!$env{'form.datatoken'}) {
 4336: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4337:     } else {
 4338: 	$datatoken=$env{'form.datatoken'};
 4339: 	&Apache::loncommon::load_tmp_file($request);
 4340:     }
 4341:     my @records=&Apache::loncommon::upfile_record_sep();
 4342:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4343:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4344:     my ($i,$keyfields);
 4345:     if (@records) {
 4346:         my $fieldserror;
 4347: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4348:         if ($fieldserror) {
 4349:             $request->print(&navmap_errormsg());
 4350:             return;
 4351:         }
 4352: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4353: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4354: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4355: 							  \@fields);
 4356: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4357: 	    chop($keyfields);
 4358: 	} else {
 4359: 	    unshift(@fields,['none','']);
 4360: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4361: 							    \@fields);
 4362:             foreach my $rec (@records) {
 4363:                 my %temp = &Apache::loncommon::record_sep($rec);
 4364:                 if (%temp) {
 4365:                     $keyfields=join(',',sort(keys(%temp)));
 4366:                     last;
 4367:                 }
 4368:             }
 4369: 	}
 4370:     }
 4371:     &csvuploadmap_footer($request,$i,$keyfields);
 4372:     $request->print(&show_grading_menu_form($symb));
 4373: 
 4374:     return '';
 4375: }
 4376: 
 4377: sub csvuploadoptions {
 4378:     my ($request)= @_;
 4379:     my ($symb)=&get_symb($request);
 4380:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4381:     my $ignore=&mt('Ignore First Line');
 4382:     $request->print(<<ENDPICK);
 4383: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4384: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4385: <input type="hidden" name="command"    value="csvuploadassign" />
 4386: <!--
 4387: <p>
 4388: <label>
 4389:    <input type="checkbox" name="show_full_results" />
 4390:    Show a table of all changes
 4391: </label>
 4392: </p>
 4393: -->
 4394: <p>
 4395: <label>
 4396:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4397:    Overwrite any existing score
 4398: </label>
 4399: </p>
 4400: ENDPICK
 4401:     my %fields=&get_fields();
 4402:     if (!defined($fields{'domain'})) {
 4403: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4404: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4405:     }
 4406:     foreach my $key (sort(keys(%env))) {
 4407: 	if ($key !~ /^form\.(.*)$/) { next; }
 4408: 	my $cleankey=$1;
 4409: 	if ($cleankey eq 'command') { next; }
 4410: 	$request->print('<input type="hidden" name="'.$cleankey.
 4411: 			'"  value="'.$env{$key}.'" />'."\n");
 4412:     }
 4413:     # FIXME do a check for any duplicated user ids...
 4414:     # FIXME do a check for any invalid user ids?...
 4415:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4416: <hr /></form>'."\n");
 4417:     $request->print(&show_grading_menu_form($symb));
 4418:     return '';
 4419: }
 4420: 
 4421: sub get_fields {
 4422:     my %fields;
 4423:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4424:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4425: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4426: 	    if ($env{'form.f'.$i} ne 'none') {
 4427: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4428: 	    }
 4429: 	} else {
 4430: 	    if ($env{'form.f'.$i} ne 'none') {
 4431: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4432: 	    }
 4433: 	}
 4434:     }
 4435:     return %fields;
 4436: }
 4437: 
 4438: sub csvuploadassign {
 4439:     my ($request)= @_;
 4440:     my ($symb)=&get_symb($request);
 4441:     if (!$symb) {return '';}
 4442:     my $error_msg = '';
 4443:     &Apache::loncommon::load_tmp_file($request);
 4444:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4445:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4446:     my %fields=&get_fields();
 4447:     $request->print('<h3>Assigning Grades</h3>');
 4448:     my $courseid=$env{'request.course.id'};
 4449:     my ($classlist) = &getclasslist('all',0);
 4450:     my @notallowed;
 4451:     my @skipped;
 4452:     my @warnings;
 4453:     my $countdone=0;
 4454:     foreach my $grade (@gradedata) {
 4455: 	my %entries=&Apache::loncommon::record_sep($grade);
 4456: 	my $domain;
 4457: 	if ($entries{$fields{'domain'}}) {
 4458: 	    $domain=$entries{$fields{'domain'}};
 4459: 	} else {
 4460: 	    $domain=$env{'form.default_domain'};
 4461: 	}
 4462: 	$domain=~s/\s//g;
 4463: 	my $username=$entries{$fields{'username'}};
 4464: 	$username=~s/\s//g;
 4465: 	if (!$username) {
 4466: 	    my $id=$entries{$fields{'ID'}};
 4467: 	    $id=~s/\s//g;
 4468: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4469: 	    $username=$ids{$id};
 4470: 	}
 4471: 	if (!exists($$classlist{"$username:$domain"})) {
 4472: 	    my $id=$entries{$fields{'ID'}};
 4473: 	    $id=~s/\s//g;
 4474: 	    if ($id) {
 4475: 		push(@skipped,"$id:$domain");
 4476: 	    } else {
 4477: 		push(@skipped,"$username:$domain");
 4478: 	    }
 4479: 	    next;
 4480: 	}
 4481: 	my $usec=$classlist->{"$username:$domain"}[5];
 4482: 	if (!&canmodify($usec)) {
 4483: 	    push(@notallowed,"$username:$domain");
 4484: 	    next;
 4485: 	}
 4486: 	my %points;
 4487: 	my %grades;
 4488: 	foreach my $dest (keys(%fields)) {
 4489: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4490: 		$dest eq 'domain') { next; }
 4491: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4492: 	    if ($dest=~/stores_(.*)_points/) {
 4493: 		my $part=$1;
 4494: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4495: 					      $symb,$domain,$username);
 4496:                 if ($wgt) {
 4497:                     $entries{$fields{$dest}}=~s/\s//g;
 4498:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4499:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4500:                                           : 'correct_by_override';
 4501:                     if ($pcr>1) {
 4502:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4503:                     }
 4504:                     $grades{"resource.$part.awarded"}=$pcr;
 4505:                     $grades{"resource.$part.solved"}=$award;
 4506:                     $points{$part}=1;
 4507:                 } else {
 4508:                     $error_msg = "<br />" .
 4509:                         &mt("Some point values were assigned"
 4510:                             ." for problems with a weight "
 4511:                             ."of zero. These values were "
 4512:                             ."ignored.");
 4513:                 }
 4514: 	    } else {
 4515: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4516: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4517: 		my $store_key=$dest;
 4518: 		$store_key=~s/^stores/resource/;
 4519: 		$store_key=~s/_/\./g;
 4520: 		$grades{$store_key}=$entries{$fields{$dest}};
 4521: 	    }
 4522: 	}
 4523: 	if (! %grades) { 
 4524:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4525:         } else {
 4526: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4527: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4528: 					   $env{'request.course.id'},
 4529: 					   $domain,$username);
 4530: 	   if ($result eq 'ok') {
 4531: 	      $request->print('.');
 4532: # Remove from grading queue
 4533:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4534:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4535:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4536:                                              $domain,$username);
 4537: 	   } else {
 4538: 	      $request->print("<p><span class=\"LC_error\">".
 4539:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4540:                                   "$username:$domain",$result)."</span></p>");
 4541: 	   }
 4542: 	   $request->rflush();
 4543: 	   $countdone++;
 4544:         }
 4545:     }
 4546:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4547:     if (@warnings) {
 4548:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4549:         $request->print(join(', ',@warnings));
 4550:     }
 4551:     if (@skipped) {
 4552: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4553:         $request->print(join(', ',@skipped));
 4554:     }
 4555:     if (@notallowed) {
 4556: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4557: 	$request->print(join(', ',@notallowed));
 4558:     }
 4559:     $request->print("<br />\n");
 4560:     $request->print(&show_grading_menu_form($symb));
 4561:     return $error_msg;
 4562: }
 4563: #------------- end of section for handling csv file upload ---------
 4564: #
 4565: #-------------------------------------------------------------------
 4566: #
 4567: #-------------- Next few routines handle grading by page/sequence
 4568: #
 4569: #--- Select a page/sequence and a student to grade
 4570: sub pickStudentPage {
 4571:     my ($request) = shift;
 4572: 
 4573:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4574:     $request->print(<<LISTJAVASCRIPT);
 4575: <script type="text/javascript" language="javascript">
 4576: 
 4577: function checkPickOne(formname) {
 4578:     if (radioSelection(formname.student) == null) {
 4579: 	alert("$alertmsg");
 4580: 	return;
 4581:     }
 4582:     ptr = pullDownSelection(formname.selectpage);
 4583:     formname.page.value = formname["page"+ptr].value;
 4584:     formname.title.value = formname["title"+ptr].value;
 4585:     formname.submit();
 4586: }
 4587: 
 4588: </script>
 4589: LISTJAVASCRIPT
 4590:     &commonJSfunctions($request);
 4591:     my ($symb) = &get_symb($request);
 4592:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4593:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4594:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4595: 
 4596:     my $result='<h3><span class="LC_info">&nbsp;'.
 4597: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4598: 
 4599:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4600:     my $map_error;
 4601:     my ($titles,$symbx) = &getSymbMap($map_error);
 4602:     if ($map_error) {
 4603:         $request->print(&navmap_errormsg());
 4604:         return; 
 4605:     }
 4606:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4607: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4608: #    my $type=($curpage =~ /\.(page|sequence)/);
 4609:     my $select = '<select name="selectpage">'."\n";
 4610:     my $ctr=0;
 4611:     foreach (@$titles) {
 4612: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4613: 	$select.='<option value="'.$ctr.'" '.
 4614: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4615: 	    '>'.$showtitle.'</option>'."\n";
 4616: 	$ctr++;
 4617:     }
 4618:     $select.= '</select>';
 4619:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4620: 
 4621:     $ctr=0;
 4622:     foreach (@$titles) {
 4623: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4624: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4625: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4626: 	$ctr++;
 4627:     }
 4628:     $result.='<input type="hidden" name="page" />'."\n".
 4629: 	'<input type="hidden" name="title" />'."\n";
 4630: 
 4631:     my $options =
 4632: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4633: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4634:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4635: 
 4636:     $options =
 4637: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4638: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4639: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4640:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4641:     
 4642:     $result.=&build_section_inputs();
 4643:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4644:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4645: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4646: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4647: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4648: 
 4649:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4650: 
 4651:     $result.='&nbsp;<input type="button" '.
 4652:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4653: 
 4654:     $request->print($result);
 4655: 
 4656:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4657: 	&Apache::loncommon::start_data_table().
 4658: 	&Apache::loncommon::start_data_table_header_row().
 4659: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4660: 	'<th>'.&nameUserString('header').'</th>'.
 4661: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4662: 	'<th>'.&nameUserString('header').'</th>'.
 4663: 	&Apache::loncommon::end_data_table_header_row();
 4664:  
 4665:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4666:     my $ptr = 1;
 4667:     foreach my $student (sort 
 4668: 			 {
 4669: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4670: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4671: 			     }
 4672: 			     return $a cmp $b;
 4673: 			 } (keys(%$fullname))) {
 4674: 	my ($uname,$udom) = split(/:/,$student);
 4675: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4676:                                   : '</td>');
 4677: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4678: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4679: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4680: 	$studentTable.=
 4681: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4682:                          : '');
 4683: 	$ptr++;
 4684:     }
 4685:     if ($ptr%2 == 0) {
 4686: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4687: 	    &Apache::loncommon::end_data_table_row();
 4688:     }
 4689:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4690:     $studentTable.='<input type="button" '.
 4691:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4692: 
 4693:     $studentTable.=&show_grading_menu_form($symb);
 4694:     $request->print($studentTable);
 4695: 
 4696:     return '';
 4697: }
 4698: 
 4699: sub getSymbMap {
 4700:     my ($map_error) = @_;
 4701:     my $navmap = Apache::lonnavmaps::navmap->new();
 4702:     unless (ref($navmap)) {
 4703:         if (ref($map_error)) {
 4704:             $$map_error = 'navmap';
 4705:         }
 4706:         return;
 4707:     }
 4708:     my %symbx = ();
 4709:     my @titles = ();
 4710:     my $minder = 0;
 4711: 
 4712:     # Gather every sequence that has problems.
 4713:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4714: 					       1,0,1);
 4715:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4716: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4717: 	    my $title = $minder.'.'.
 4718: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4719: 	    push(@titles, $title); # minder in case two titles are identical
 4720: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4721: 	    $minder++;
 4722: 	}
 4723:     }
 4724:     return \@titles,\%symbx;
 4725: }
 4726: 
 4727: #
 4728: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4729: sub displayPage {
 4730:     my ($request) = shift;
 4731: 
 4732:     my ($symb) = &get_symb($request);
 4733:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4734:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4735:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4736:     my $pageTitle = $env{'form.page'};
 4737:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4738:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4739:     my $usec=$classlist->{$env{'form.student'}}[5];
 4740: 
 4741:     #need to make sure we have the correct data for later EXT calls, 
 4742:     #thus invalidate the cache
 4743:     &Apache::lonnet::devalidatecourseresdata(
 4744:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4745:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4746:     &Apache::lonnet::clear_EXT_cache_status();
 4747: 
 4748:     if (!&canview($usec)) {
 4749: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4750: 	$request->print(&show_grading_menu_form($symb));
 4751: 	return;
 4752:     }
 4753:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4754:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4755: 	'</h3>'."\n";
 4756:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4757:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4758: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4759:     } else {
 4760: 	delete($env{'form.CODE'});
 4761:     }
 4762:     &sub_page_js($request);
 4763:     $request->print($result);
 4764: 
 4765:     my $navmap = Apache::lonnavmaps::navmap->new();
 4766:     unless (ref($navmap)) {
 4767:         $request->print(&navmap_errormsg());
 4768:         $request->print(&show_grading_menu_form($symb));
 4769:         return;
 4770:     }
 4771:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4772:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4773:     if (!$map) {
 4774: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4775: 	$request->print(&show_grading_menu_form($symb));
 4776: 	return; 
 4777:     }
 4778:     my $iterator = $navmap->getIterator($map->map_start(),
 4779: 					$map->map_finish());
 4780: 
 4781:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4782: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4783: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4784: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4785: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4786: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4787: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4788: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4789: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4790: 
 4791:     if (defined($env{'form.CODE'})) {
 4792: 	$studentTable.=
 4793: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4794:     }
 4795:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4796: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4797: 
 4798:     $studentTable.='&nbsp;<span class="LC_info">'.
 4799:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4800:         '</span>'."\n".
 4801: 	&Apache::loncommon::start_data_table().
 4802: 	&Apache::loncommon::start_data_table_header_row().
 4803: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4804: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4805: 	&Apache::loncommon::end_data_table_header_row();
 4806: 
 4807:     &Apache::lonxml::clear_problem_counter();
 4808:     my ($depth,$question,$prob) = (1,1,1);
 4809:     $iterator->next(); # skip the first BEGIN_MAP
 4810:     my $curRes = $iterator->next(); # for "current resource"
 4811:     while ($depth > 0) {
 4812:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4813:         if($curRes == $iterator->END_MAP) { $depth--; }
 4814: 
 4815:         if (ref($curRes) && $curRes->is_problem()) {
 4816: 	    my $parts = $curRes->parts();
 4817:             my $title = $curRes->compTitle();
 4818: 	    my $symbx = $curRes->symb();
 4819: 	    $studentTable.=
 4820: 		&Apache::loncommon::start_data_table_row().
 4821: 		'<td align="center" valign="top" >'.$prob.
 4822: 		(scalar(@{$parts}) == 1 ? '' 
 4823: 		                        : '<br />('.&mt('[_1]parts',
 4824: 							scalar(@{$parts}).'&nbsp;').')'
 4825: 		 ).
 4826: 		 '</td>';
 4827: 	    $studentTable.='<td valign="top">';
 4828: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4829: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4830: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4831: 					     undef,'both',\%form);
 4832: 	    } else {
 4833: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4834: 		$companswer =~ s|<form(.*?)>||g;
 4835: 		$companswer =~ s|</form>||g;
 4836: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4837: #		    $companswer =~ s/$1/ /ms;
 4838: #		    $request->print('match='.$1."<br />\n");
 4839: #		}
 4840: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4841: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4842: 	    }
 4843: 
 4844: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4845: 
 4846: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4847: 		if ($record{'version'} eq '') {
 4848: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4849: 		} else {
 4850: 		    my %responseType = ();
 4851: 		    foreach my $partid (@{$parts}) {
 4852: 			my @responseIds =$curRes->responseIds($partid);
 4853: 			my @responseType =$curRes->responseType($partid);
 4854: 			my %responseIds;
 4855: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4856: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4857: 			}
 4858: 			$responseType{$partid} = \%responseIds;
 4859: 		    }
 4860: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4861: 
 4862: 		}
 4863: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4864: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4865: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4866: 									$env{'request.course.id'},
 4867: 									'','.submission');
 4868:  
 4869: 	    }
 4870: 	    if (&canmodify($usec)) {
 4871:             $studentTable.=&gradeBox_start();
 4872: 		foreach my $partid (@{$parts}) {
 4873: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4874: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4875: 		    $question++;
 4876: 		}
 4877:             $studentTable.=&gradeBox_end();
 4878: 		$prob++;
 4879: 	    }
 4880: 	    $studentTable.='</td></tr>';
 4881: 
 4882: 	}
 4883:         $curRes = $iterator->next();
 4884:     }
 4885: 
 4886:     $studentTable.=
 4887:         '</table>'."\n".
 4888:         '<input type="button" value="'.&mt('Save').'" '.
 4889:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4890:         '</form>'."\n";
 4891:     $studentTable.=&show_grading_menu_form($symb);
 4892:     $request->print($studentTable);
 4893: 
 4894:     return '';
 4895: }
 4896: 
 4897: sub displaySubByDates {
 4898:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4899:     my $isCODE=0;
 4900:     my $isTask = ($symb =~/\.task$/);
 4901:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4902:     my $studentTable=&Apache::loncommon::start_data_table().
 4903: 	&Apache::loncommon::start_data_table_header_row().
 4904: 	'<th>'.&mt('Date/Time').'</th>'.
 4905: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4906:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4907: 	'<th>'.&mt('Submission').'</th>'.
 4908: 	'<th>'.&mt('Status').'</th>'.
 4909: 	&Apache::loncommon::end_data_table_header_row();
 4910:     my ($version);
 4911:     my %mark;
 4912:     my %orders;
 4913:     $mark{'correct_by_student'} = $checkIcon;
 4914:     if (!exists($$record{'1:timestamp'})) {
 4915: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4916:     }
 4917: 
 4918:     my $interaction;
 4919:     my $no_increment = 1;
 4920:     my %lastrndseed;
 4921:     for ($version=1;$version<=$$record{'version'};$version++) {
 4922: 	my $timestamp = 
 4923: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4924: 	if (exists($$record{$version.':resource.0.version'})) {
 4925: 	    $interaction = $$record{$version.':resource.0.version'};
 4926: 	}
 4927:         if ($isTask && $env{'form.previousversion'}) {
 4928:             next unless ($interaction == $env{'form.previousversion'});
 4929:         }
 4930: 	my $where = ($isTask ? "$version:resource.$interaction"
 4931: 		             : "$version:resource");
 4932: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4933: 	    '<td>'.$timestamp.'</td>';
 4934: 	if ($isCODE) {
 4935: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4936: 	}
 4937:         if ($isTask) {
 4938:             $studentTable.='<td>'.$interaction.'</td>';
 4939:         }
 4940: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4941: 	my @displaySub = ();
 4942: 	foreach my $partid (@{$parts}) {
 4943:             my ($hidden,$type);
 4944:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4945:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4946:                 $hidden = 1;
 4947:             }
 4948: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4949: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4950: 	    
 4951: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4952: 	    my $display_part=&get_display_part($partid,$symb);
 4953: 	    foreach my $matchKey (@matchKey) {
 4954: 		if (exists($$record{$version.':'.$matchKey}) &&
 4955: 		    $$record{$version.':'.$matchKey} ne '') {
 4956:                     
 4957: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4958: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4959:                     $displaySub[0].='<span class="LC_nobreak">';
 4960:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4961:                                    .' <span class="LC_internal_info">'
 4962:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4963:                                    .'</span>'
 4964:                                    .' <b>';
 4965:                     if ($hidden) {
 4966:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4967:                     } else {
 4968:                         my ($trial,$rndseed,$newvariation);
 4969:                         if ($type eq 'randomizetry') {
 4970:                             $trial = $$record{"$where.$partid.tries"};
 4971:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4972:                         }
 4973: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4974: 			    $displaySub[0].=&mt('Trial not counted');
 4975: 		        } else {
 4976: 			    $displaySub[0].=&mt('Trial: [_1]',
 4977: 					    $$record{"$where.$partid.tries"});
 4978:                             if ($rndseed || $lastrndseed{$partid}) {
 4979:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4980:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4981:                                 }
 4982:                             }
 4983: 		        }
 4984: 		        my $responseType=($isTask ? 'Task'
 4985:                                               : $responseType->{$partid}->{$responseId});
 4986: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4987: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4988: 			    $orders{$partid}->{$responseId}=
 4989: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4990:                                            $no_increment,$type,$trial,$rndseed);
 4991: 		        }
 4992: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4993: 		        $displaySub[0].='&nbsp; '.
 4994: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4995:                     }
 4996: 		}
 4997: 	    }
 4998: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4999: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5000: 				    $$record{"$where.$partid.checkedin"},
 5001: 				    $$record{"$where.$partid.checkedin.slot"}).
 5002: 					'<br />';
 5003: 	    }
 5004: 	    if (exists $$record{"$where.$partid.award"}) {
 5005: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5006: 		    lc($$record{"$where.$partid.award"}).' '.
 5007: 		    $mark{$$record{"$where.$partid.solved"}}.
 5008: 		    '<br />';
 5009: 	    }
 5010: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5011: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5012: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5013: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5014: 		$displaySub[2].=
 5015: 		    $$record{"$version:resource.$partid.regrader"}.
 5016: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5017: 	    }
 5018: 	}
 5019: 	# needed because old essay regrader has not parts info
 5020: 	if (exists $$record{"$version:resource.regrader"}) {
 5021: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5022: 	}
 5023: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5024: 	if ($displaySub[2]) {
 5025: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5026: 	}
 5027: 	$studentTable.='&nbsp;</td>'.
 5028: 	    &Apache::loncommon::end_data_table_row();
 5029:     }
 5030:     $studentTable.=&Apache::loncommon::end_data_table();
 5031:     return $studentTable;
 5032: }
 5033: 
 5034: sub updateGradeByPage {
 5035:     my ($request) = shift;
 5036: 
 5037:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5038:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5039:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5040:     my $pageTitle = $env{'form.page'};
 5041:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5042:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5043:     my $usec=$classlist->{$env{'form.student'}}[5];
 5044:     if (!&canmodify($usec)) {
 5045: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5046: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5047: 	return;
 5048:     }
 5049:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5050:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5051: 	'</h3>'."\n";
 5052: 
 5053:     $request->print($result);
 5054: 
 5055: 
 5056:     my $navmap = Apache::lonnavmaps::navmap->new();
 5057:     unless (ref($navmap)) {
 5058:         $request->print(&navmap_errormsg());
 5059:         return;
 5060:     }
 5061:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5062:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5063:     if (!$map) {
 5064: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5065: 	my ($symb)=&get_symb($request);
 5066: 	$request->print(&show_grading_menu_form($symb));
 5067: 	return; 
 5068:     }
 5069:     my $iterator = $navmap->getIterator($map->map_start(),
 5070: 					$map->map_finish());
 5071: 
 5072:     my $studentTable=
 5073: 	&Apache::loncommon::start_data_table().
 5074: 	&Apache::loncommon::start_data_table_header_row().
 5075: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5076: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5077: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5078: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5079: 	&Apache::loncommon::end_data_table_header_row();
 5080: 
 5081:     $iterator->next(); # skip the first BEGIN_MAP
 5082:     my $curRes = $iterator->next(); # for "current resource"
 5083:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 5084:     while ($depth > 0) {
 5085:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5086:         if($curRes == $iterator->END_MAP) { $depth--; }
 5087: 
 5088:         if (ref($curRes) && $curRes->is_problem()) {
 5089: 	    my $parts = $curRes->parts();
 5090:             my $title = $curRes->compTitle();
 5091: 	    my $symbx = $curRes->symb();
 5092: 	    $studentTable.=
 5093: 		&Apache::loncommon::start_data_table_row().
 5094: 		'<td align="center" valign="top" >'.$prob.
 5095: 		(scalar(@{$parts}) == 1 ? '' 
 5096:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5097: 		.')').'</td>';
 5098: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5099: 
 5100: 	    my %newrecord=();
 5101: 	    my @displayPts=();
 5102:             my %aggregate = ();
 5103:             my $aggregateflag = 0;
 5104: 	    foreach my $partid (@{$parts}) {
 5105: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5106: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5107: 
 5108: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5109: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5110: 		my $partial = $newpts/$wgt;
 5111: 		my $score;
 5112: 		if ($partial > 0) {
 5113: 		    $score = 'correct_by_override';
 5114: 		} elsif ($newpts ne '') { #empty is taken as 0
 5115: 		    $score = 'incorrect_by_override';
 5116: 		}
 5117: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5118: 		if ($dropMenu eq 'excused') {
 5119: 		    $partial = '';
 5120: 		    $score = 'excused';
 5121: 		} elsif ($dropMenu eq 'reset status'
 5122: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5123: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5124: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5125: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5126: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5127: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5128: 		    $changeflag++;
 5129: 		    $newpts = '';
 5130:                     
 5131:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5132:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5133:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5134:                     if ($aggtries > 0) {
 5135:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5136:                         $aggregateflag = 1;
 5137:                     }
 5138: 		}
 5139: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5140: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5141: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5142: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5143: 		    '&nbsp;<br />';
 5144: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5145: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5146: 		    '&nbsp;<br />';
 5147: 		$question++;
 5148: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5149: 
 5150: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5151: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5152: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5153: 		    if (scalar(keys(%newrecord)) > 0);
 5154: 
 5155: 		$changeflag++;
 5156: 	    }
 5157: 	    if (scalar(keys(%newrecord)) > 0) {
 5158: 		my %record = 
 5159: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5160: 					     $udom,$uname);
 5161: 
 5162: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5163: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5164: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5165: 		    $newrecord{'resource.CODE'} = '';
 5166: 		}
 5167: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5168: 					$udom,$uname);
 5169: 		%record = &Apache::lonnet::restore($symbx,
 5170: 						   $env{'request.course.id'},
 5171: 						   $udom,$uname);
 5172: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5173: 					     $cdom,$cnum,$udom,$uname);
 5174: 	    }
 5175: 	    
 5176:             if ($aggregateflag) {
 5177:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5178:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5179:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5180:             }
 5181: 
 5182: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5183: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5184: 		&Apache::loncommon::end_data_table_row();
 5185: 
 5186: 	    $prob++;
 5187: 	}
 5188:         $curRes = $iterator->next();
 5189:     }
 5190: 
 5191:     $studentTable.=&Apache::loncommon::end_data_table();
 5192:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5193:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5194: 		  &mt('The scores were changed for [quant,_1,problem].',
 5195: 		  $changeflag));
 5196:     $request->print($grademsg.$studentTable);
 5197: 
 5198:     return '';
 5199: }
 5200: 
 5201: #-------- end of section for handling grading by page/sequence ---------
 5202: #
 5203: #-------------------------------------------------------------------
 5204: 
 5205: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5206: #
 5207: #------ start of section for handling grading by page/sequence ---------
 5208: 
 5209: =pod
 5210: 
 5211: =head1 Bubble sheet grading routines
 5212: 
 5213:   For this documentation:
 5214: 
 5215:    'scanline' refers to the full line of characters
 5216:    from the file that we are parsing that represents one entire sheet
 5217: 
 5218:    'bubble line' refers to the data
 5219:    representing the line of bubbles that are on the physical bubblesheet
 5220: 
 5221: 
 5222: The overall process is that a scanned in bubblesheet data is uploaded
 5223: into a course. When a user wants to grade, they select a
 5224: sequence/folder of resources, a file of bubblesheet info, and pick
 5225: one of the predefined configurations for what each scanline looks
 5226: like.
 5227: 
 5228: Next each scanline is checked for any errors of either 'missing
 5229: bubbles' (it's an error because it may have been mis-scanned
 5230: because too light bubbling), 'double bubble' (each bubble line should
 5231: have no more that one letter picked), invalid or duplicated CODE,
 5232: invalid student/employee ID
 5233: 
 5234: If the CODE option is used that determines the randomization of the
 5235: homework problems, either way the student/employee ID is looked up into a
 5236: username:domain.
 5237: 
 5238: During the validation phase the instructor can choose to skip scanlines. 
 5239: 
 5240: After the validation phase, there are now 3 bubblesheet files
 5241: 
 5242:   scantron_original_filename (unmodified original file)
 5243:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5244:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5245: 
 5246: Also there is a separate hash nohist_scantrondata that contains extra
 5247: correction information that isn't representable in the bubblesheet
 5248: file (see &scantron_getfile() for more information)
 5249: 
 5250: After all scanlines are either valid, marked as valid or skipped, then
 5251: foreach line foreach problem in the picked sequence, an ssi request is
 5252: made that simulates a user submitting their selected letter(s) against
 5253: the homework problem.
 5254: 
 5255: =over 4
 5256: 
 5257: 
 5258: 
 5259: =item defaultFormData
 5260: 
 5261:   Returns html hidden inputs used to hold context/default values.
 5262: 
 5263:  Arguments:
 5264:   $symb - $symb of the current resource 
 5265: 
 5266: =cut
 5267: 
 5268: sub defaultFormData {
 5269:     my ($symb)=@_;
 5270:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5271:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5272:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5273: }
 5274: 
 5275: 
 5276: =pod 
 5277: 
 5278: =item getSequenceDropDown
 5279: 
 5280:    Return html dropdown of possible sequences to grade
 5281:  
 5282:  Arguments:
 5283:    $symb - $symb of the current resource
 5284:    $map_error - ref to scalar which will container error if
 5285:                 $navmap object is unavailable in &getSymbMap().
 5286: 
 5287: =cut
 5288: 
 5289: sub getSequenceDropDown {
 5290:     my ($symb,$map_error)=@_;
 5291:     my $result='<select name="selectpage">'."\n";
 5292:     my ($titles,$symbx) = &getSymbMap($map_error);
 5293:     if (ref($map_error)) {
 5294:         return if ($$map_error);
 5295:     }
 5296:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5297:     my $ctr=0;
 5298:     foreach (@$titles) {
 5299: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5300: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5301: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5302: 	    '>'.$showtitle.'</option>'."\n";
 5303: 	$ctr++;
 5304:     }
 5305:     $result.= '</select>';
 5306:     return $result;
 5307: }
 5308: 
 5309: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5310:                                    # key is zero-based index - 0, 1, 2 ...
 5311: 
 5312: my %first_bubble_line;             # First bubble line no. for each bubble.
 5313: 
 5314: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5315:                                    # matchresponse or rankresponse, where 
 5316:                                    # an individual response can have multiple 
 5317:                                    # lines
 5318: 
 5319: my %responsetype_per_response;     # responsetype for each response
 5320: 
 5321: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5322:                                    # numbered response. Needed when randomorder
 5323:                                    # or randompick are in use. Key is ID, value 
 5324:                                    # is response number.
 5325: 
 5326: # Save and restore the bubble lines array to the form env.
 5327: 
 5328: 
 5329: sub save_bubble_lines {
 5330:     foreach my $line (keys(%bubble_lines_per_response)) {
 5331: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5332: 	$env{"form.scantron.first_bubble_line.$line"} =
 5333: 	    $first_bubble_line{$line};
 5334:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5335:             $subdivided_bubble_lines{$line};
 5336:         $env{"form.scantron.responsetype.$line"} =
 5337:             $responsetype_per_response{$line};
 5338:     }
 5339:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5340:         my $line = $masterseq_id_responsenum{$resid};
 5341:         $env{"form.scantron.residpart.$line"} = $resid;
 5342:     }
 5343: }
 5344: 
 5345: 
 5346: sub restore_bubble_lines {
 5347:     my $line = 0;
 5348:     %bubble_lines_per_response = ();
 5349:     %masterseq_id_responsenum = ();
 5350:     while ($env{"form.scantron.bubblelines.$line"}) {
 5351: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5352: 	$bubble_lines_per_response{$line} = $value;
 5353: 	$first_bubble_line{$line}  =
 5354: 	    $env{"form.scantron.first_bubble_line.$line"};
 5355:         $subdivided_bubble_lines{$line} =
 5356:             $env{"form.scantron.sub_bubblelines.$line"};
 5357:         $responsetype_per_response{$line} =
 5358:             $env{"form.scantron.responsetype.$line"};
 5359:         my $id = $env{"form.scantron.residpart.$line"};
 5360:         $masterseq_id_responsenum{$id} = $line;
 5361: 	$line++;
 5362:     }
 5363: }
 5364: 
 5365: =pod 
 5366: 
 5367: =item scantron_filenames
 5368: 
 5369:    Returns a list of the scantron files in the current course 
 5370: 
 5371: =cut
 5372: 
 5373: sub scantron_filenames {
 5374:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5375:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5376:     my $getpropath = 1;
 5377:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5378:                                                         $cname,$getpropath);
 5379:     my @possiblenames;
 5380:     if (ref($dirlist) eq 'ARRAY') {
 5381:         foreach my $filename (sort(@{$dirlist})) {
 5382: 	    ($filename)=split(/&/,$filename);
 5383: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5384: 	    $filename=~s/^scantron_orig_//;
 5385: 	    push(@possiblenames,$filename);
 5386:         }
 5387:     }
 5388:     return @possiblenames;
 5389: }
 5390: 
 5391: =pod 
 5392: 
 5393: =item scantron_uploads
 5394: 
 5395:    Returns  html drop-down list of scantron files in current course.
 5396: 
 5397:  Arguments:
 5398:    $file2grade - filename to set as selected in the dropdown
 5399: 
 5400: =cut
 5401: 
 5402: sub scantron_uploads {
 5403:     my ($file2grade) = @_;
 5404:     my $result=	'<select name="scantron_selectfile">';
 5405:     $result.="<option></option>";
 5406:     foreach my $filename (sort(&scantron_filenames())) {
 5407: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5408:     }
 5409:     $result.="</select>";
 5410:     return $result;
 5411: }
 5412: 
 5413: =pod 
 5414: 
 5415: =item scantron_scantab
 5416: 
 5417:   Returns html drop down of the scantron formats in the scantronformat.tab
 5418:   file.
 5419: 
 5420: =cut
 5421: 
 5422: sub scantron_scantab {
 5423:     my $result='<select name="scantron_format">'."\n";
 5424:     $result.='<option></option>'."\n";
 5425:     my @lines = &get_scantronformat_file();
 5426:     if (@lines > 0) {
 5427:         foreach my $line (@lines) {
 5428:             next if (($line =~ /^\#/) || ($line eq ''));
 5429: 	    my ($name,$descrip)=split(/:/,$line);
 5430: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5431:         }
 5432:     }
 5433:     $result.='</select>'."\n";
 5434:     return $result;
 5435: }
 5436: 
 5437: =pod
 5438: 
 5439: =item get_scantronformat_file
 5440: 
 5441:   Returns an array containing lines from the scantron format file for
 5442:   the domain of the course.
 5443: 
 5444:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5445:   lines are from this file.
 5446: 
 5447:   Otherwise, if a default.tab has been published in RES space by the 
 5448:   domainconfig user, lines are from this file.
 5449: 
 5450:   Otherwise, fall back to getting lines from the legacy file on the
 5451:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5452: 
 5453: =cut
 5454: 
 5455: sub get_scantronformat_file {
 5456:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5457:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5458:     my $gottab = 0;
 5459:     my @lines;
 5460:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5461:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5462:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5463:             if ($formatfile ne '-1') {
 5464:                 @lines = split("\n",$formatfile,-1);
 5465:                 $gottab = 1;
 5466:             }
 5467:         }
 5468:     }
 5469:     if (!$gottab) {
 5470:         my $confname = $cdom.'-domainconfig';
 5471:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5472:         my $formatfile =  &Apache::lonnet::getfile($default);
 5473:         if ($formatfile ne '-1') {
 5474:             @lines = split("\n",$formatfile,-1);
 5475:             $gottab = 1;
 5476:         }
 5477:     }
 5478:     if (!$gottab) {
 5479:         my @domains = &Apache::lonnet::current_machine_domains();
 5480:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5481:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5482:             @lines = <$fh>;
 5483:             close($fh);
 5484:         } else {
 5485:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5486:             @lines = <$fh>;
 5487:             close($fh);
 5488:         }
 5489:     }
 5490:     return @lines;
 5491: }
 5492: 
 5493: =pod 
 5494: 
 5495: =item scantron_CODElist
 5496: 
 5497:   Returns html drop down of the saved CODE lists from current course,
 5498:   generated from earlier printings.
 5499: 
 5500: =cut
 5501: 
 5502: sub scantron_CODElist {
 5503:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5504:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5505:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5506:     my $namechoice='<option></option>';
 5507:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5508: 	if ($name =~ /^error: 2 /) { next; }
 5509: 	if ($name =~ /^type\0/) { next; }
 5510: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5511:     }
 5512:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5513:     return $namechoice;
 5514: }
 5515: 
 5516: =pod 
 5517: 
 5518: =item scantron_CODEunique
 5519: 
 5520:   Returns the html for "Each CODE to be used once" radio.
 5521: 
 5522: =cut
 5523: 
 5524: sub scantron_CODEunique {
 5525:     my $result='<span class="LC_nobreak">
 5526:                  <label><input type="radio" name="scantron_CODEunique"
 5527:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5528:                 </span>
 5529:                 <span class="LC_nobreak">
 5530:                  <label><input type="radio" name="scantron_CODEunique"
 5531:                         value="no" />'.&mt('No').' </label>
 5532:                 </span>';
 5533:     return $result;
 5534: }
 5535: 
 5536: =pod 
 5537: 
 5538: =item scantron_selectphase
 5539: 
 5540:   Generates the initial screen to start the bubblesheet process.
 5541:   Allows for - starting a grading run.
 5542:              - downloading existing scan data (original, corrected
 5543:                                                 or skipped info)
 5544: 
 5545:              - uploading new scan data
 5546: 
 5547:  Arguments:
 5548:   $r          - The Apache request object
 5549:   $file2grade - name of the file that contain the scanned data to score
 5550: 
 5551: =cut
 5552: 
 5553: sub scantron_selectphase {
 5554:     my ($r,$file2grade) = @_;
 5555:     my ($symb)=&get_symb($r);
 5556:     if (!$symb) {return '';}
 5557:     my $map_error;
 5558:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5559:     if ($map_error) {
 5560:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5561:         return;
 5562:     }
 5563:     my $default_form_data=&defaultFormData($symb);
 5564:     my $grading_menu_button=&show_grading_menu_form($symb);
 5565:     my $file_selector=&scantron_uploads($file2grade);
 5566:     my $format_selector=&scantron_scantab();
 5567:     my $CODE_selector=&scantron_CODElist();
 5568:     my $CODE_unique=&scantron_CODEunique();
 5569:     my $result;
 5570: 
 5571:     $ssi_error = 0;
 5572: 
 5573:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5574:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5575: 
 5576:         # Chunk of form to prompt for a scantron file upload.
 5577: 
 5578:         $r->print('
 5579:     <br />
 5580:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5581:        '.&Apache::loncommon::start_data_table_header_row().'
 5582:             <th>
 5583:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5584:             </th>
 5585:        '.&Apache::loncommon::end_data_table_header_row().'
 5586:        '.&Apache::loncommon::start_data_table_row().'
 5587:             <td>
 5588: ');
 5589:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5590:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5591:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5592:     $r->print('
 5593:               <script type="text/javascript" language="javascript">
 5594:     function checkUpload(formname) {
 5595:         if (formname.upfile.value == "") {
 5596:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5597:             return false;
 5598:         }
 5599:         formname.submit();
 5600:     }
 5601:               </script>
 5602: 
 5603:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5604:                 '.$default_form_data.'
 5605:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5606:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5607:                 <input name="command" value="scantronupload_save" type="hidden" />
 5608:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5609:                 <br />
 5610:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5611:               </form>
 5612: ');
 5613: 
 5614:         $r->print('
 5615:             </td>
 5616:        '.&Apache::loncommon::end_data_table_row().'
 5617:        '.&Apache::loncommon::end_data_table().'
 5618: ');
 5619:     }
 5620: 
 5621:     # Chunk of form to prompt for a file to grade and how:
 5622: 
 5623:     $result.= '
 5624:     <br />
 5625:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5626:     <input type="hidden" name="command" value="scantron_warning" />
 5627:     '.$default_form_data.'
 5628:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5629:        '.&Apache::loncommon::start_data_table_header_row().'
 5630:             <th colspan="2">
 5631:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5632:             </th>
 5633:        '.&Apache::loncommon::end_data_table_header_row().'
 5634:        '.&Apache::loncommon::start_data_table_row().'
 5635:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5636:        '.&Apache::loncommon::end_data_table_row().'
 5637:        '.&Apache::loncommon::start_data_table_row().'
 5638:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5639:        '.&Apache::loncommon::end_data_table_row().'
 5640:        '.&Apache::loncommon::start_data_table_row().'
 5641:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5642:        '.&Apache::loncommon::end_data_table_row().'
 5643:        '.&Apache::loncommon::start_data_table_row().'
 5644:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5645:        '.&Apache::loncommon::end_data_table_row().'
 5646:        '.&Apache::loncommon::start_data_table_row().'
 5647:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5648:        '.&Apache::loncommon::end_data_table_row().'
 5649:        '.&Apache::loncommon::start_data_table_row().'
 5650: 	    <td> '.&mt('Options:').' </td>
 5651:             <td>
 5652: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5653:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5654:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5655: 	    </td>
 5656:        '.&Apache::loncommon::end_data_table_row().'
 5657:        '.&Apache::loncommon::start_data_table_row().'
 5658:             <td colspan="2">
 5659:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5660:             </td>
 5661:        '.&Apache::loncommon::end_data_table_row().'
 5662:     '.&Apache::loncommon::end_data_table().'
 5663:     </form>
 5664: ';
 5665:    
 5666:     $r->print($result);
 5667: 
 5668:     # Chunk of the form that prompts to view a scoring office file,
 5669:     # corrected file, skipped records in a file.
 5670: 
 5671:     $r->print('
 5672:    <br />
 5673:    <form action="/adm/grades" name="scantron_download">
 5674:      '.$default_form_data.'
 5675:      <input type="hidden" name="command" value="scantron_download" />
 5676:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5677:        '.&Apache::loncommon::start_data_table_header_row().'
 5678:               <th>
 5679:                 &nbsp;'.&mt('Download a scoring office file').'
 5680:               </th>
 5681:        '.&Apache::loncommon::end_data_table_header_row().'
 5682:        '.&Apache::loncommon::start_data_table_row().'
 5683:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5684:                 <br />
 5685:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5686:        '.&Apache::loncommon::end_data_table_row().'
 5687:      '.&Apache::loncommon::end_data_table().'
 5688:    </form>
 5689:    <br />
 5690: ');
 5691: 
 5692:     &Apache::lonpickcode::code_list($r,2);
 5693: 
 5694:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5695:              $default_form_data."\n".
 5696:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5697:              &Apache::loncommon::start_data_table_header_row()."\n".
 5698:              '<th colspan="2">
 5699:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5700:              '</th>'."\n".
 5701:               &Apache::loncommon::end_data_table_header_row()."\n".
 5702:               &Apache::loncommon::start_data_table_row()."\n".
 5703:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5704:               '<td> '.$sequence_selector.' </td>'.
 5705:               &Apache::loncommon::end_data_table_row()."\n".
 5706:               &Apache::loncommon::start_data_table_row()."\n".
 5707:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5708:               '<td> '.$file_selector.' </td>'."\n".
 5709:               &Apache::loncommon::end_data_table_row()."\n".
 5710:               &Apache::loncommon::start_data_table_row()."\n".
 5711:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5712:               '<td> '.$format_selector.' </td>'."\n".
 5713:               &Apache::loncommon::end_data_table_row()."\n".
 5714:               &Apache::loncommon::start_data_table_row()."\n".
 5715:               '<td> '.&mt('Options').' </td>'."\n".
 5716:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5717:               &Apache::loncommon::end_data_table_row()."\n".
 5718:               &Apache::loncommon::start_data_table_row()."\n".
 5719:               '<td colspan="2">'."\n".
 5720:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5721:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5722:               '</td>'."\n".
 5723:               &Apache::loncommon::end_data_table_row()."\n".
 5724:               &Apache::loncommon::end_data_table()."\n".
 5725:               '</form><br />');
 5726:     $r->print($grading_menu_button);
 5727:     return;
 5728: }
 5729: 
 5730: =pod
 5731: 
 5732: =item get_scantron_config
 5733: 
 5734:    Parse and return the scantron configuration line selected as a
 5735:    hash of configuration file fields.
 5736: 
 5737:  Arguments:
 5738:     which - the name of the configuration to parse from the file.
 5739: 
 5740: 
 5741:  Returns:
 5742:             If the named configuration is not in the file, an empty
 5743:             hash is returned.
 5744:     a hash with the fields
 5745:       name         - internal name for the this configuration setup
 5746:       description  - text to display to operator that describes this config
 5747:       CODElocation - if 0 or the string 'none'
 5748:                           - no CODE exists for this config
 5749:                      if -1 || the string 'letter'
 5750:                           - a CODE exists for this config and is
 5751:                             a string of letters
 5752:                      Unsupported value (but planned for future support)
 5753:                           if a positive integer
 5754:                                - The CODE exists as the first n items from
 5755:                                  the question section of the form
 5756:                           if the string 'number'
 5757:                                - The CODE exists for this config and is
 5758:                                  a string of numbers
 5759:       CODEstart   - (only matter if a CODE exists) column in the line where
 5760:                      the CODE starts
 5761:       CODElength  - length of the CODE
 5762:       IDstart     - column where the student/employee ID starts
 5763:       IDlength    - length of the student/employee ID info
 5764:       Qstart      - column where the information from the bubbled
 5765:                     'questions' start
 5766:       Qlength     - number of columns comprising a single bubble line from
 5767:                     the sheet. (usually either 1 or 10)
 5768:       Qon         - either a single character representing the character used
 5769:                     to signal a bubble was chosen in the positional setup, or
 5770:                     the string 'letter' if the letter of the chosen bubble is
 5771:                     in the final, or 'number' if a number representing the
 5772:                     chosen bubble is in the file (1->A 0->J)
 5773:       Qoff        - the character used to represent that a bubble was
 5774:                     left blank
 5775:       PaperID     - if the scanning process generates a unique number for each
 5776:                     sheet scanned the column that this ID number starts in
 5777:       PaperIDlength - number of columns that comprise the unique ID number
 5778:                       for the sheet of paper
 5779:       FirstName   - column that the first name starts in
 5780:       FirstNameLength - number of columns that the first name spans
 5781:  
 5782:       LastName    - column that the last name starts in
 5783:       LastNameLength - number of columns that the last name spans
 5784:       BubblesPerRow - number of bubbles available in each row used to
 5785:                       bubble an answer. (If not specified, 10 assumed).
 5786: 
 5787: =cut
 5788: 
 5789: sub get_scantron_config {
 5790:     my ($which) = @_;
 5791:     my @lines = &get_scantronformat_file();
 5792:     my %config;
 5793:     #FIXME probably should move to XML it has already gotten a bit much now
 5794:     foreach my $line (@lines) {
 5795: 	my ($name,$descrip)=split(/:/,$line);
 5796: 	if ($name ne $which ) { next; }
 5797: 	chomp($line);
 5798: 	my @config=split(/:/,$line);
 5799: 	$config{'name'}=$config[0];
 5800: 	$config{'description'}=$config[1];
 5801: 	$config{'CODElocation'}=$config[2];
 5802: 	$config{'CODEstart'}=$config[3];
 5803: 	$config{'CODElength'}=$config[4];
 5804: 	$config{'IDstart'}=$config[5];
 5805: 	$config{'IDlength'}=$config[6];
 5806: 	$config{'Qstart'}=$config[7];
 5807:  	$config{'Qlength'}=$config[8];
 5808: 	$config{'Qoff'}=$config[9];
 5809: 	$config{'Qon'}=$config[10];
 5810: 	$config{'PaperID'}=$config[11];
 5811: 	$config{'PaperIDlength'}=$config[12];
 5812: 	$config{'FirstName'}=$config[13];
 5813: 	$config{'FirstNamelength'}=$config[14];
 5814: 	$config{'LastName'}=$config[15];
 5815: 	$config{'LastNamelength'}=$config[16];
 5816:         $config{'BubblesPerRow'}=$config[17];
 5817: 	last;
 5818:     }
 5819:     return %config;
 5820: }
 5821: 
 5822: =pod 
 5823: 
 5824: =item username_to_idmap
 5825: 
 5826:     creates a hash keyed by student/employee ID with values of the corresponding
 5827:     student username:domain.
 5828: 
 5829:   Arguments:
 5830: 
 5831:     $classlist - reference to the class list hash. This is a hash
 5832:                  keyed by student name:domain  whose elements are references
 5833:                  to arrays containing various chunks of information
 5834:                  about the student. (See loncoursedata for more info).
 5835: 
 5836:   Returns
 5837:     %idmap - the constructed hash
 5838: 
 5839: =cut
 5840: 
 5841: sub username_to_idmap {
 5842:     my ($classlist)= @_;
 5843:     my %idmap;
 5844:     foreach my $student (keys(%$classlist)) {
 5845: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5846: 	    $student;
 5847:     }
 5848:     return %idmap;
 5849: }
 5850: 
 5851: =pod
 5852: 
 5853: =item scantron_fixup_scanline
 5854: 
 5855:    Process a requested correction to a scanline.
 5856: 
 5857:   Arguments:
 5858:     $scantron_config   - hash from &get_scantron_config()
 5859:     $scan_data         - hash of correction information 
 5860:                           (see &scantron_getfile())
 5861:     $line              - existing scanline
 5862:     $whichline         - line number of the passed in scanline
 5863:     $field             - type of change to process 
 5864:                          (either 
 5865:                           'ID'     -> correct the student/employee ID
 5866:                           'CODE'   -> correct the CODE
 5867:                           'answer' -> fixup the submitted answers)
 5868:     
 5869:    $args               - hash of additional info,
 5870:                           - 'ID' 
 5871:                                'newid' -> studentID to use in replacement
 5872:                                           of existing one
 5873:                           - 'CODE' 
 5874:                                'CODE_ignore_dup' - set to true if duplicates
 5875:                                                    should be ignored.
 5876: 	                       'CODE' - is new code or 'use_unfound'
 5877:                                         if the existing unfound code should
 5878:                                         be used as is
 5879:                           - 'answer'
 5880:                                'response' - new answer or 'none' if blank
 5881:                                'question' - the bubble line to change
 5882:                                'questionnum' - the question identifier,
 5883:                                                may include subquestion. 
 5884: 
 5885:   Returns:
 5886:     $line - the modified scanline
 5887: 
 5888:   Side effects: 
 5889:     $scan_data - may be updated
 5890: 
 5891: =cut
 5892: 
 5893: 
 5894: sub scantron_fixup_scanline {
 5895:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5896:     if ($field eq 'ID') {
 5897: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5898: 	    return ($line,1,'New value too large');
 5899: 	}
 5900: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5901: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5902: 				     $args->{'newid'});
 5903: 	}
 5904: 	substr($line,$$scantron_config{'IDstart'}-1,
 5905: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5906: 	if ($args->{'newid'}=~/^\s*$/) {
 5907: 	    &scan_data($scan_data,"$whichline.user",
 5908: 		       $args->{'username'}.':'.$args->{'domain'});
 5909: 	}
 5910:     } elsif ($field eq 'CODE') {
 5911: 	if ($args->{'CODE_ignore_dup'}) {
 5912: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5913: 	}
 5914: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5915: 	if ($args->{'CODE'} ne 'use_unfound') {
 5916: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5917: 		return ($line,1,'New CODE value too large');
 5918: 	    }
 5919: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5920: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5921: 	    }
 5922: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5923: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5924: 	}
 5925:     } elsif ($field eq 'answer') {
 5926: 	my $length=$scantron_config->{'Qlength'};
 5927: 	my $off=$scantron_config->{'Qoff'};
 5928: 	my $on=$scantron_config->{'Qon'};
 5929: 	my $answer=${off}x$length;
 5930: 	if ($args->{'response'} eq 'none') {
 5931: 	    &scan_data($scan_data,
 5932: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5933: 	} else {
 5934: 	    if ($on eq 'letter') {
 5935: 		my @alphabet=('A'..'Z');
 5936: 		$answer=$alphabet[$args->{'response'}];
 5937: 	    } elsif ($on eq 'number') {
 5938: 		$answer=$args->{'response'}+1;
 5939: 		if ($answer == 10) { $answer = '0'; }
 5940: 	    } else {
 5941: 		substr($answer,$args->{'response'},1)=$on;
 5942: 	    }
 5943: 	    &scan_data($scan_data,
 5944: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5945: 	}
 5946: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5947: 	substr($line,$where-1,$length)=$answer;
 5948:     }
 5949:     return $line;
 5950: }
 5951: 
 5952: =pod
 5953: 
 5954: =item scan_data
 5955: 
 5956:     Edit or look up  an item in the scan_data hash.
 5957: 
 5958:   Arguments:
 5959:     $scan_data  - The hash (see scantron_getfile)
 5960:     $key        - shorthand of the key to edit (actual key is
 5961:                   scantronfilename_key).
 5962:     $data        - New value of the hash entry.
 5963:     $delete      - If true, the entry is removed from the hash.
 5964: 
 5965:   Returns:
 5966:     The new value of the hash table field (undefined if deleted).
 5967: 
 5968: =cut
 5969: 
 5970: 
 5971: sub scan_data {
 5972:     my ($scan_data,$key,$value,$delete)=@_;
 5973:     my $filename=$env{'form.scantron_selectfile'};
 5974:     if (defined($value)) {
 5975: 	$scan_data->{$filename.'_'.$key} = $value;
 5976:     }
 5977:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5978:     return $scan_data->{$filename.'_'.$key};
 5979: }
 5980: 
 5981: # ----- These first few routines are general use routines.----
 5982: 
 5983: # Return the number of occurences of a pattern in a string.
 5984: 
 5985: sub occurence_count {
 5986:     my ($string, $pattern) = @_;
 5987: 
 5988:     my @matches = ($string =~ /$pattern/g);
 5989: 
 5990:     return scalar(@matches);
 5991: }
 5992: 
 5993: 
 5994: # Take a string known to have digits and convert all the
 5995: # digits into letters in the range J,A..I.
 5996: 
 5997: sub digits_to_letters {
 5998:     my ($input) = @_;
 5999: 
 6000:     my @alphabet = ('J', 'A'..'I');
 6001: 
 6002:     my @input    = split(//, $input);
 6003:     my $output ='';
 6004:     for (my $i = 0; $i < scalar(@input); $i++) {
 6005: 	if ($input[$i] =~ /\d/) {
 6006: 	    $output .= $alphabet[$input[$i]];
 6007: 	} else {
 6008: 	    $output .= $input[$i];
 6009: 	}
 6010:     }
 6011:     return $output;
 6012: }
 6013: 
 6014: =pod 
 6015: 
 6016: =item scantron_parse_scanline
 6017: 
 6018:   Decodes a scanline from the selected scantron file
 6019: 
 6020:  Arguments:
 6021:     line             - The text of the scantron file line to process
 6022:     whichline        - Line number
 6023:     scantron_config  - Hash describing the format of the scantron lines.
 6024:     scan_data        - Hash of extra information about the scanline
 6025:                        (see scantron_getfile for more information)
 6026:     just_header      - True if should not process question answers but only
 6027:                        the stuff to the left of the answers.
 6028:     randomorder      - True if randomorder in use
 6029:     randompick       - True if randompick in use
 6030:     sequence         - Exam folder URL
 6031:     master_seq       - Ref to array containing symbs in exam folder
 6032:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6033:                        (corresponding values are resource objects)
 6034:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6035:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6036:                        are refs to an array of resource objects, ordered
 6037:                        according to order used for CODE, when randomorder
 6038:                        and or randompick are in use.
 6039:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6040:                        for current line to question number used for same question
 6041:                         in "Master Sequence" (as seen by Course Coordinator).
 6042:     startline        - Ref to hash where key is question number (0 is first)
 6043:                        and value is number of first bubble line for current 
 6044:                        student or code-based randompick and/or randomorder.
 6045:     totalref         - Ref of scalar used to score total number of bubble
 6046:                        lines needed for responses in a scan line (used when
 6047:                        randompick in use. 
 6048: 
 6049:  Returns:
 6050:    Hash containing the result of parsing the scanline
 6051: 
 6052:    Keys are all proceeded by the string 'scantron.'
 6053: 
 6054:        CODE    - the CODE in use for this scanline
 6055:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6056:                  by the operator
 6057:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6058:                             CODEs were selected, but the usage has been
 6059:                             forced by the operator
 6060:        ID  - student/employee ID
 6061:        PaperID - if used, the ID number printed on the sheet when the 
 6062:                  paper was scanned
 6063:        FirstName - first name from the sheet
 6064:        LastName  - last name from the sheet
 6065: 
 6066:      if just_header was not true these key may also exist
 6067: 
 6068:        missingerror - a list of bubble ranges that are considered to be answers
 6069:                       to a single question that don't have any bubbles filled in.
 6070:                       Of the form questionnumber:firstbubblenumber:count.
 6071:        doubleerror  - a list of bubble ranges that are considered to be answers
 6072:                       to a single question that have more than one bubble filled in.
 6073:                       Of the form questionnumber::firstbubblenumber:count
 6074:    
 6075:                 In the above, count is the number of bubble responses in the
 6076:                 input line needed to represent the possible answers to the question.
 6077:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6078:                 per line would have count = 2.
 6079: 
 6080:        maxquest     - the number of the last bubble line that was parsed
 6081: 
 6082:        (<number> starts at 1)
 6083:        <number>.answer - zero or more letters representing the selected
 6084:                          letters from the scanline for the bubble line 
 6085:                          <number>.
 6086:                          if blank there was either no bubble or there where
 6087:                          multiple bubbles, (consult the keys missingerror and
 6088:                          doubleerror if this is an error condition)
 6089: 
 6090: =cut
 6091: 
 6092: sub scantron_parse_scanline {
 6093:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6094:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6095:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6096: 
 6097:     my %record;
 6098:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6099:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6100: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6101: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6102: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6103: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6104: 	    $record{'scantron.CODE'}=substr($data,
 6105: 					    $$scantron_config{'CODEstart'}-1,
 6106: 					    $$scantron_config{'CODElength'});
 6107: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6108: 		$record{'scantron.useCODE'}=1;
 6109: 	    }
 6110: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6111: 		$record{'scantron.CODE_ignore_dup'}=1;
 6112: 	    }
 6113: 	} else {
 6114: 	    #FIXME interpret first N questions
 6115: 	}
 6116:     }
 6117:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6118: 				  $$scantron_config{'IDlength'});
 6119:     $record{'scantron.PaperID'}=
 6120: 	substr($data,$$scantron_config{'PaperID'}-1,
 6121: 	       $$scantron_config{'PaperIDlength'});
 6122:     $record{'scantron.FirstName'}=
 6123: 	substr($data,$$scantron_config{'FirstName'}-1,
 6124: 	       $$scantron_config{'FirstNamelength'});
 6125:     $record{'scantron.LastName'}=
 6126: 	substr($data,$$scantron_config{'LastName'}-1,
 6127: 	       $$scantron_config{'LastNamelength'});
 6128:     if ($just_header) { return \%record; }
 6129: 
 6130:     my @alphabet=('A'..'Z');
 6131:     my $questnum=0;
 6132:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6133: 
 6134:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6135:     if ($randompick || $randomorder) {
 6136:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6137:                                          $master_seq,$symb_to_resource,
 6138:                                          $partids_by_symb,$orderedforcode,
 6139:                                          $respnumlookup,$startline);
 6140:         if ($total) {
 6141:             $lastpos = $total*$$scantron_config{'Qlength'};
 6142:         }
 6143:         if (ref($totalref)) {
 6144:             $$totalref = $total;
 6145:         }
 6146:     }
 6147:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6148:     chomp($questions);		# Get rid of any trailing \n.
 6149:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6150:     while (length($questions)) {
 6151:         my $answers_needed;
 6152:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6153:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6154:         } else {
 6155:             $answers_needed = $bubble_lines_per_response{$questnum};
 6156:         }
 6157:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6158:                              || 1;
 6159:         $questnum++;
 6160:         my $quest_id = $questnum;
 6161:         my $currentquest = substr($questions,0,$answer_length);
 6162:         $questions       = substr($questions,$answer_length);
 6163:         if (length($currentquest) < $answer_length) { next; }
 6164: 
 6165:         my $subdivided;
 6166:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6167:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6168:         } else {
 6169:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6170:         }
 6171:         if ($subdivided =~ /,/) {
 6172:             my $subquestnum = 1;
 6173:             my $subquestions = $currentquest;
 6174:             my @subanswers_needed = split(/,/,$subdivided);
 6175:             foreach my $subans (@subanswers_needed) {
 6176:                 my $subans_length =
 6177:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6178:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6179:                 $subquestions   = substr($subquestions,$subans_length);
 6180:                 $quest_id = "$questnum.$subquestnum";
 6181:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6182:                     ($$scantron_config{'Qon'} eq 'number')) {
 6183:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6184:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6185:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6186:                         $randomorder,$randompick,$respnumlookup);
 6187:                 } else {
 6188:                     $ansnum = &scantron_validator_positional($ansnum,
 6189:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6190:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6191:                         $randomorder,$randompick,$respnumlookup);
 6192:                 }
 6193:                 $subquestnum ++;
 6194:             }
 6195:         } else {
 6196:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6197:                 ($$scantron_config{'Qon'} eq 'number')) {
 6198:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6199:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6200:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6201:                     $randomorder,$randompick,$respnumlookup);
 6202:             } else {
 6203:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6204:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6205:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6206:                     $randomorder,$randompick,$respnumlookup);
 6207:             }
 6208:         }
 6209:     }
 6210:     $record{'scantron.maxquest'}=$questnum;
 6211:     return \%record;
 6212: }
 6213: 
 6214: sub get_master_seq {
 6215:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6216:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6217:                    (ref($symb_to_resource) eq 'HASH'));
 6218:     my $resource_error;
 6219:     foreach my $resource (@{$resources}) {
 6220:         my $ressymb;
 6221:         if (ref($resource)) {
 6222:             $ressymb = $resource->symb();
 6223:             push(@{$master_seq},$ressymb);
 6224:             $symb_to_resource->{$ressymb} = $resource;
 6225:         } else {
 6226:             $resource_error = 1;
 6227:             last;
 6228:         }
 6229:     }
 6230:     return $resource_error;
 6231: }
 6232: 
 6233: sub get_respnum_lookups {
 6234:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6235:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6236:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6237:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6238:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6239:                    (ref($startline) eq 'HASH'));
 6240:     my ($user,$scancode);
 6241:     if ((exists($record->{'scantron.CODE'})) &&
 6242:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6243:         $scancode = $record->{'scantron.CODE'};
 6244:     } else {
 6245:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6246:     }
 6247:     my @mapresources =
 6248:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6249:                      $orderedforcode);
 6250:     my $total = 0;
 6251:     my $count = 0;
 6252:     foreach my $resource (@mapresources) {
 6253:         my $id = $resource->id();
 6254:         my $symb = $resource->symb();
 6255:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6256:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6257:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6258:                 if ($respnum ne '') {
 6259:                     $respnumlookup->{$count} = $respnum;
 6260:                     $startline->{$count} = $total;
 6261:                     $total += $bubble_lines_per_response{$respnum};
 6262:                     $count ++;
 6263:                 }
 6264:             }
 6265:         }
 6266:     }
 6267:     return $total;
 6268: }
 6269: 
 6270: sub scantron_validator_lettnum {
 6271:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6272:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6273:         $randompick,$respnumlookup) = @_;
 6274: 
 6275:     # Qon 'letter' implies for each slot in currquest we have:
 6276:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6277:     #    about anything else (esp. a value of Qoff) for missing
 6278:     #    bubbles.
 6279:     #
 6280:     # Qon 'number' implies each slot gives a digit that indexes the
 6281:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6282:     #    and * or ? for double bubbles on a single line.
 6283:     #
 6284: 
 6285:     my $matchon;
 6286:     if ($$scantron_config{'Qon'} eq 'letter') {
 6287:         $matchon = '[A-Z]';
 6288:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6289:         $matchon = '\d';
 6290:     }
 6291:     my $occurrences = 0;
 6292:     my $responsenum = $questnum-1;
 6293:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6294:        $responsenum = $respnumlookup->{$questnum-1}
 6295:     }
 6296:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6297:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6298:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6299:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6300:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6301:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6302:         my @singlelines = split('',$currquest);
 6303:         foreach my $entry (@singlelines) {
 6304:             $occurrences = &occurence_count($entry,$matchon);
 6305:             if ($occurrences > 1) {
 6306:                 last;
 6307:             }
 6308:         }
 6309:     } else {
 6310:         $occurrences = &occurence_count($currquest,$matchon); 
 6311:     }
 6312:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6313:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6314:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6315:             my $bubble = substr($currquest,$ans,1);
 6316:             if ($bubble =~ /$matchon/ ) {
 6317:                 if ($$scantron_config{'Qon'} eq 'number') {
 6318:                     if ($bubble == 0) {
 6319:                         $bubble = 10; 
 6320:                     }
 6321:                     $record->{"scantron.$ansnum.answer"} = 
 6322:                         $alphabet->[$bubble-1];
 6323:                 } else {
 6324:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6325:                 }
 6326:             } else {
 6327:                 $record->{"scantron.$ansnum.answer"}='';
 6328:             }
 6329:             $ansnum++;
 6330:         }
 6331:     } elsif (!defined($currquest)
 6332:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6333:             || (&occurence_count($currquest,$matchon) == 0)) {
 6334:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6335:             $record->{"scantron.$ansnum.answer"}='';
 6336:             $ansnum++;
 6337:         }
 6338:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6339:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6340:         }
 6341:     } else {
 6342:         if ($$scantron_config{'Qon'} eq 'number') {
 6343:             $currquest = &digits_to_letters($currquest);            
 6344:         }
 6345:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6346:             my $bubble = substr($currquest,$ans,1);
 6347:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6348:             $ansnum++;
 6349:         }
 6350:     }
 6351:     return $ansnum;
 6352: }
 6353: 
 6354: sub scantron_validator_positional {
 6355:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6356:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6357:         $randomorder,$randompick,$respnumlookup) = @_;
 6358: 
 6359:     # Otherwise there's a positional notation;
 6360:     # each bubble line requires Qlength items, and there are filled in
 6361:     # bubbles for each case where there 'Qon' characters.
 6362:     #
 6363: 
 6364:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6365: 
 6366:     # If the split only gives us one element.. the full length of the
 6367:     # answer string, no bubbles are filled in:
 6368: 
 6369:     if ($answers_needed eq '') {
 6370:         return;
 6371:     }
 6372: 
 6373:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6374:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6375:             $record->{"scantron.$ansnum.answer"}='';
 6376:             $ansnum++;
 6377:         }
 6378:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6379:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6380:         }
 6381:     } elsif (scalar(@array) == 2) {
 6382:         my $location = length($array[0]);
 6383:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6384:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6385:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6386:             if ($ans eq $line_num) {
 6387:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6388:             } else {
 6389:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6390:             }
 6391:             $ansnum++;
 6392:          }
 6393:     } else {
 6394:         #  If there's more than one instance of a bubble character
 6395:         #  That's a double bubble; with positional notation we can
 6396:         #  record all the bubbles filled in as well as the
 6397:         #  fact this response consists of multiple bubbles.
 6398:         #
 6399:         my $responsenum = $questnum-1;
 6400:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6401:             $responsenum = $respnumlookup->{$questnum-1}
 6402:         }
 6403:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6404:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6405:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6406:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6407:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6408:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6409:             my $doubleerror = 0;
 6410:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6411:                    (!$doubleerror)) {
 6412:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6413:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6414:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6415:                if (length(@currarray) > 2) {
 6416:                    $doubleerror = 1;
 6417:                } 
 6418:             }
 6419:             if ($doubleerror) {
 6420:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6421:             }
 6422:         } else {
 6423:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6424:         }
 6425:         my $item = $ansnum;
 6426:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6427:             $record->{"scantron.$item.answer"} = '';
 6428:             $item ++;
 6429:         }
 6430: 
 6431:         my @ans=@array;
 6432:         my $i=0;
 6433:         my $increment = 0;
 6434:         while ($#ans) {
 6435:             $i+=length($ans[0]) + $increment;
 6436:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6437:             my $bubble = $i%$$scantron_config{'Qlength'};
 6438:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6439:             shift(@ans);
 6440:             $increment = 1;
 6441:         }
 6442:         $ansnum += $answers_needed;
 6443:     }
 6444:     return $ansnum;
 6445: }
 6446: 
 6447: =pod
 6448: 
 6449: =item scantron_add_delay
 6450: 
 6451:    Adds an error message that occurred during the grading phase to a
 6452:    queue of messages to be shown after grading pass is complete
 6453: 
 6454:  Arguments:
 6455:    $delayqueue  - arrary ref of hash ref of error messages
 6456:    $scanline    - the scanline that caused the error
 6457:    $errormesage - the error message
 6458:    $errorcode   - a numeric code for the error
 6459: 
 6460:  Side Effects:
 6461:    updates the $delayqueue to have a new hash ref of the error
 6462: 
 6463: =cut
 6464: 
 6465: sub scantron_add_delay {
 6466:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6467:     push(@$delayqueue,
 6468: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6469: 	  'ecode' => $errorcode }
 6470: 	 );
 6471: }
 6472: 
 6473: =pod
 6474: 
 6475: =item scantron_find_student
 6476: 
 6477:    Finds the username for the current scanline
 6478: 
 6479:   Arguments:
 6480:    $scantron_record - hash result from scantron_parse_scanline
 6481:    $scan_data       - hash of correction information 
 6482:                       (see &scantron_getfile() form more information)
 6483:    $idmap           - hash from &username_to_idmap()
 6484:    $line            - number of current scanline
 6485:  
 6486:   Returns:
 6487:    Either 'username:domain' or undef if unknown
 6488: 
 6489: =cut
 6490: 
 6491: sub scantron_find_student {
 6492:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6493:     my $scanID=$$scantron_record{'scantron.ID'};
 6494:     if ($scanID =~ /^\s*$/) {
 6495:  	return &scan_data($scan_data,"$line.user");
 6496:     }
 6497:     foreach my $id (keys(%$idmap)) {
 6498:  	if (lc($id) eq lc($scanID)) {
 6499:  	    return $$idmap{$id};
 6500:  	}
 6501:     }
 6502:     return undef;
 6503: }
 6504: 
 6505: =pod
 6506: 
 6507: =item scantron_filter
 6508: 
 6509:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6510:    hidden resources was selected
 6511: 
 6512: =cut
 6513: 
 6514: sub scantron_filter {
 6515:     my ($curres)=@_;
 6516: 
 6517:     if (ref($curres) && $curres->is_problem()) {
 6518: 	# if the user has asked to not have either hidden
 6519: 	# or 'randomout' controlled resources to be graded
 6520: 	# don't include them
 6521: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6522: 	    && $curres->randomout) {
 6523: 	    return 0;
 6524: 	}
 6525: 	return 1;
 6526:     }
 6527:     return 0;
 6528: }
 6529: 
 6530: =pod
 6531: 
 6532: =item scantron_process_corrections
 6533: 
 6534:    Gets correction information out of submitted form data and corrects
 6535:    the scanline
 6536: 
 6537: =cut
 6538: 
 6539: sub scantron_process_corrections {
 6540:     my ($r) = @_;
 6541:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6542:     my ($scanlines,$scan_data)=&scantron_getfile();
 6543:     my $classlist=&Apache::loncoursedata::get_classlist();
 6544:     my $which=$env{'form.scantron_line'};
 6545:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6546:     my ($skip,$err,$errmsg);
 6547:     if ($env{'form.scantron_skip_record'}) {
 6548: 	$skip=1;
 6549:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6550: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6551: 	    $env{'form.scantron_domain'};
 6552: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6553: 	($line,$err,$errmsg)=
 6554: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6555: 				     'ID',{'newid'=>$newid,
 6556: 				    'username'=>$env{'form.scantron_username'},
 6557: 				    'domain'=>$env{'form.scantron_domain'}});
 6558:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6559: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6560: 	my $newCODE;
 6561: 	my %args;
 6562: 	if      ($resolution eq 'use_unfound') {
 6563: 	    $newCODE='use_unfound';
 6564: 	} elsif ($resolution eq 'use_found') {
 6565: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6566: 	} elsif ($resolution eq 'use_typed') {
 6567: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6568: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6569: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6570: 	}
 6571: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6572: 	    $args{'CODE_ignore_dup'}=1;
 6573: 	}
 6574: 	$args{'CODE'}=$newCODE;
 6575: 	($line,$err,$errmsg)=
 6576: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6577: 				     'CODE',\%args);
 6578:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6579: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6580: 	    ($line,$err,$errmsg)=
 6581: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6582: 					 $which,'answer',
 6583: 					 { 'question'=>$question,
 6584: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6585:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6586: 	    if ($err) { last; }
 6587: 	}
 6588:     }
 6589:     if ($err) {
 6590: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6591:     } else {
 6592: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6593: 	&scantron_putfile($scanlines,$scan_data);
 6594:     }
 6595: }
 6596: 
 6597: =pod
 6598: 
 6599: =item reset_skipping_status
 6600: 
 6601:    Forgets the current set of remember skipped scanlines (and thus
 6602:    reverts back to considering all lines in the
 6603:    scantron_skipped_<filename> file)
 6604: 
 6605: =cut
 6606: 
 6607: sub reset_skipping_status {
 6608:     my ($scanlines,$scan_data)=&scantron_getfile();
 6609:     &scan_data($scan_data,'remember_skipping',undef,1);
 6610:     &scantron_putfile(undef,$scan_data);
 6611: }
 6612: 
 6613: =pod
 6614: 
 6615: =item start_skipping
 6616: 
 6617:    Marks a scanline to be skipped. 
 6618: 
 6619: =cut
 6620: 
 6621: sub start_skipping {
 6622:     my ($scan_data,$i)=@_;
 6623:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6624:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6625: 	$remembered{$i}=2;
 6626:     } else {
 6627: 	$remembered{$i}=1;
 6628:     }
 6629:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6630: }
 6631: 
 6632: =pod
 6633: 
 6634: =item should_be_skipped
 6635: 
 6636:    Checks whether a scanline should be skipped.
 6637: 
 6638: =cut
 6639: 
 6640: sub should_be_skipped {
 6641:     my ($scanlines,$scan_data,$i)=@_;
 6642:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6643: 	# not redoing old skips
 6644: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6645: 	return 0;
 6646:     }
 6647:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6648: 
 6649:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6650: 	return 0;
 6651:     }
 6652:     return 1;
 6653: }
 6654: 
 6655: =pod
 6656: 
 6657: =item remember_current_skipped
 6658: 
 6659:    Discovers what scanlines are in the scantron_skipped_<filename>
 6660:    file and remembers them into scan_data for later use.
 6661: 
 6662: =cut
 6663: 
 6664: sub remember_current_skipped {
 6665:     my ($scanlines,$scan_data)=&scantron_getfile();
 6666:     my %to_remember;
 6667:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6668: 	if ($scanlines->{'skipped'}[$i]) {
 6669: 	    $to_remember{$i}=1;
 6670: 	}
 6671:     }
 6672: 
 6673:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6674:     &scantron_putfile(undef,$scan_data);
 6675: }
 6676: 
 6677: =pod
 6678: 
 6679: =item check_for_error
 6680: 
 6681:     Checks if there was an error when attempting to remove a specific
 6682:     scantron_.. bubblesheet data file. Prints out an error if
 6683:     something went wrong.
 6684: 
 6685: =cut
 6686: 
 6687: sub check_for_error {
 6688:     my ($r,$result)=@_;
 6689:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6690: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6691:     }
 6692: }
 6693: 
 6694: =pod
 6695: 
 6696: =item scantron_warning_screen
 6697: 
 6698:    Interstitial screen to make sure the operator has selected the
 6699:    correct options before we start the validation phase.
 6700: 
 6701: =cut
 6702: 
 6703: sub scantron_warning_screen {
 6704:     my ($button_text)=@_;
 6705:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6706:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6707:     my $CODElist;
 6708:     if ($scantron_config{'CODElocation'} &&
 6709: 	$scantron_config{'CODEstart'} &&
 6710: 	$scantron_config{'CODElength'}) {
 6711: 	$CODElist=$env{'form.scantron_CODElist'};
 6712: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6713: 	$CODElist=
 6714: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6715: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6716:     }
 6717:     my $lastbubblepoints;
 6718:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6719:         $lastbubblepoints =
 6720:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6721:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6722:     }
 6723:     return ('
 6724: <p>
 6725: <span class="LC_warning">
 6726: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6727: </p>
 6728: <table>
 6729: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6730: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6731: '.$CODElist.$lastbubblepoints.'
 6732: </table>
 6733: <br />
 6734: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 6735: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 6736: 
 6737: <br />
 6738: ');
 6739: }
 6740: 
 6741: =pod
 6742: 
 6743: =item scantron_do_warning
 6744: 
 6745:    Check if the operator has picked something for all required
 6746:    fields. Error out if something is missing.
 6747: 
 6748: =cut
 6749: 
 6750: sub scantron_do_warning {
 6751:     my ($r)=@_;
 6752:     my ($symb)=&get_symb($r);
 6753:     if (!$symb) {return '';}
 6754:     my $default_form_data=&defaultFormData($symb);
 6755:     $r->print(&scantron_form_start().$default_form_data);
 6756:     if ( $env{'form.selectpage'} eq '' ||
 6757: 	 $env{'form.scantron_selectfile'} eq '' ||
 6758: 	 $env{'form.scantron_format'} eq '' ) {
 6759: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6760: 	if ( $env{'form.selectpage'} eq '') {
 6761: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6762: 	} 
 6763: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6764: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6765: 	} 
 6766: 	if ( $env{'form.scantron_format'} eq '') {
 6767: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6768: 	} 
 6769:     } else {
 6770: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6771:         my $bubbledbyhand=&hand_bubble_option();
 6772: 	$r->print('
 6773: '.$warning.$bubbledbyhand.'
 6774: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6775: <input type="hidden" name="command" value="scantron_validate" />
 6776: ');
 6777:     }
 6778:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6779:     return '';
 6780: }
 6781: 
 6782: =pod
 6783: 
 6784: =item scantron_form_start
 6785: 
 6786:     html hidden input for remembering all selected grading options
 6787: 
 6788: =cut
 6789: 
 6790: sub scantron_form_start {
 6791:     my ($max_bubble)=@_;
 6792:     my $result= <<SCANTRONFORM;
 6793: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6794:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6795:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6796:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6797:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6798:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6799:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6800:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6801:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6802:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6803: SCANTRONFORM
 6804: 
 6805:   my $line = 0;
 6806:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6807:        my $chunk =
 6808: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6809:        $chunk .=
 6810: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6811:        $chunk .= 
 6812:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6813:        $chunk .=
 6814:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6815:        $chunk .=
 6816:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6817:        $result .= $chunk;
 6818:        $line++;
 6819:     }
 6820:     return $result;
 6821: }
 6822: 
 6823: =pod
 6824: 
 6825: =item scantron_validate_file
 6826: 
 6827:     Dispatch routine for doing validation of a bubblesheet data file.
 6828: 
 6829:     Also processes any necessary information resets that need to
 6830:     occur before validation begins (ignore previous corrections,
 6831:     restarting the skipped records processing)
 6832: 
 6833: =cut
 6834: 
 6835: sub scantron_validate_file {
 6836:     my ($r) = @_;
 6837:     my ($symb)=&get_symb($r);
 6838:     if (!$symb) {return '';}
 6839:     my $default_form_data=&defaultFormData($symb);
 6840:     
 6841:     # do the detection of only doing skipped records first befroe we delete
 6842:     # them when doing the corrections reset
 6843:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6844: 	&reset_skipping_status();
 6845:     }
 6846:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6847: 	&remember_current_skipped();
 6848: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6849:     }
 6850: 
 6851:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6852: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6853: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6854: 	&check_for_error($r,&scantron_remove_scan_data());
 6855: 	$env{'form.scantron_options_ignore'}='done';
 6856:     }
 6857: 
 6858:     if ($env{'form.scantron_corrections'}) {
 6859: 	&scantron_process_corrections($r);
 6860:     }
 6861:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6862:     #get the student pick code ready
 6863:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6864:     my $nav_error;
 6865:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6866:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6867:     if ($nav_error) {
 6868:         $r->print(&navmap_errormsg());
 6869:         return '';
 6870:     }
 6871:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6872:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6873:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6874:     }
 6875:     $r->print($result);
 6876:     
 6877:     my @validate_phases=( 'sequence',
 6878: 			  'ID',
 6879: 			  'CODE',
 6880: 			  'doublebubble',
 6881: 			  'missingbubbles');
 6882:     if (!$env{'form.validatepass'}) {
 6883: 	$env{'form.validatepass'} = 0;
 6884:     }
 6885:     my $currentphase=$env{'form.validatepass'};
 6886: 
 6887: 
 6888:     my $stop=0;
 6889:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6890: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6891: 	$r->rflush();
 6892: 
 6893: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6894: 	{
 6895: 	    no strict 'refs';
 6896: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6897: 	}
 6898:     }
 6899:     if (!$stop) {
 6900: 	my $warning=&scantron_warning_screen('Start Grading');
 6901: 	$r->print(&mt('Validation process complete.').'<br />'.
 6902:                   $warning.
 6903:                   &mt('Perform verification for each student after storage of submissions?').
 6904:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6905:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6906:                   ('&nbsp;'x3).'<label>'.
 6907:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6908:                   '</label></span><br />'.
 6909:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6910:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6911:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6912:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6913:     } else {
 6914: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6915: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6916:     }
 6917:     if ($stop) {
 6918: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6919: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6920: 	    $r->print(' '.&mt('this error').' <br />');
 6921: 
 6922: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6923: 	} else {
 6924:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6925: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6926:             } else {
 6927:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6928:             }
 6929: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6930: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6931: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6932: 	}
 6933:     }
 6934:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6935:     return '';
 6936: }
 6937: 
 6938: 
 6939: =pod
 6940: 
 6941: =item scantron_remove_file
 6942: 
 6943:    Removes the requested bubblesheet data file, makes sure that
 6944:    scantron_original_<filename> is never removed
 6945: 
 6946: 
 6947: =cut
 6948: 
 6949: sub scantron_remove_file {
 6950:     my ($which)=@_;
 6951:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6952:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6953:     my $file='scantron_';
 6954:     if ($which eq 'corrected' || $which eq 'skipped') {
 6955: 	$file.=$which.'_';
 6956:     } else {
 6957: 	return 'refused';
 6958:     }
 6959:     $file.=$env{'form.scantron_selectfile'};
 6960:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6961: }
 6962: 
 6963: 
 6964: =pod
 6965: 
 6966: =item scantron_remove_scan_data
 6967: 
 6968:    Removes all scan_data correction for the requested bubblesheet
 6969:    data file.  (In the case that both the are doing skipped records we need
 6970:    to remember the old skipped lines for the time being so that element
 6971:    persists for a while.)
 6972: 
 6973: =cut
 6974: 
 6975: sub scantron_remove_scan_data {
 6976:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6977:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6978:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6979:     my @todelete;
 6980:     my $filename=$env{'form.scantron_selectfile'};
 6981:     foreach my $key (@keys) {
 6982: 	if ($key=~/^\Q$filename\E_/) {
 6983: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6984: 		$key=~/remember_skipping/) {
 6985: 		next;
 6986: 	    }
 6987: 	    push(@todelete,$key);
 6988: 	}
 6989:     }
 6990:     my $result;
 6991:     if (@todelete) {
 6992: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6993: 				       \@todelete,$cdom,$cname);
 6994:     } else {
 6995: 	$result = 'ok';
 6996:     }
 6997:     return $result;
 6998: }
 6999: 
 7000: 
 7001: =pod
 7002: 
 7003: =item scantron_getfile
 7004: 
 7005:     Fetches the requested bubblesheet data file (all 3 versions), and
 7006:     the scan_data hash
 7007:   
 7008:   Arguments:
 7009:     None
 7010: 
 7011:   Returns:
 7012:     2 hash references
 7013: 
 7014:      - first one has 
 7015:          orig      -
 7016:          corrected -
 7017:          skipped   -  each of which points to an array ref of the specified
 7018:                       file broken up into individual lines
 7019:          count     - number of scanlines
 7020:  
 7021:      - second is the scan_data hash possible keys are
 7022:        ($number refers to scanline numbered $number and thus the key affects
 7023:         only that scanline
 7024:         $bubline refers to the specific bubble line element and the aspects
 7025:         refers to that specific bubble line element)
 7026: 
 7027:        $number.user - username:domain to use
 7028:        $number.CODE_ignore_dup 
 7029:                     - ignore the duplicate CODE error 
 7030:        $number.useCODE
 7031:                     - use the CODE in the scanline as is
 7032:        $number.no_bubble.$bubline
 7033:                     - it is valid that there is no bubbled in bubble
 7034:                       at $number $bubline
 7035:        remember_skipping
 7036:                     - a frozen hash containing keys of $number and values
 7037:                       of either 
 7038:                         1 - we are on a 'do skipped records pass' and plan
 7039:                             on processing this line
 7040:                         2 - we are on a 'do skipped records pass' and this
 7041:                             scanline has been marked to skip yet again
 7042: 
 7043: =cut
 7044: 
 7045: sub scantron_getfile {
 7046:     #FIXME really would prefer a scantron directory
 7047:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7048:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7049:     my $lines;
 7050:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7051: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7052:     my %scanlines;
 7053:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7054:     my $temp=$scanlines{'orig'};
 7055:     $scanlines{'count'}=$#$temp;
 7056: 
 7057:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7058: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7059:     if ($lines eq '-1') {
 7060: 	$scanlines{'corrected'}=[];
 7061:     } else {
 7062: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7063:     }
 7064:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7065: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7066:     if ($lines eq '-1') {
 7067: 	$scanlines{'skipped'}=[];
 7068:     } else {
 7069: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7070:     }
 7071:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7072:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7073:     my %scan_data = @tmp;
 7074:     return (\%scanlines,\%scan_data);
 7075: }
 7076: 
 7077: =pod
 7078: 
 7079: =item lonnet_putfile
 7080: 
 7081:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7082: 
 7083:  Arguments:
 7084:    $contents - data to store
 7085:    $filename - filename to store $contents into
 7086: 
 7087:  Returns:
 7088:    result value from &Apache::lonnet::finishuserfileupload
 7089: 
 7090: =cut
 7091: 
 7092: sub lonnet_putfile {
 7093:     my ($contents,$filename)=@_;
 7094:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7095:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7096:     $env{'form.sillywaytopassafilearound'}=$contents;
 7097:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7098: 
 7099: }
 7100: 
 7101: =pod
 7102: 
 7103: =item scantron_putfile
 7104: 
 7105:     Stores the current version of the bubblesheet data files, and the
 7106:     scan_data hash. (Does not modify the original version only the
 7107:     corrected and skipped versions.
 7108: 
 7109:  Arguments:
 7110:     $scanlines - hash ref that looks like the first return value from
 7111:                  &scantron_getfile()
 7112:     $scan_data - hash ref that looks like the second return value from
 7113:                  &scantron_getfile()
 7114: 
 7115: =cut
 7116: 
 7117: sub scantron_putfile {
 7118:     my ($scanlines,$scan_data) = @_;
 7119:     #FIXME really would prefer a scantron directory
 7120:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7121:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7122:     if ($scanlines) {
 7123: 	my $prefix='scantron_';
 7124: # no need to update orig, shouldn't change
 7125: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7126: #		    $env{'form.scantron_selectfile'});
 7127: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7128: 			$prefix.'corrected_'.
 7129: 			$env{'form.scantron_selectfile'});
 7130: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7131: 			$prefix.'skipped_'.
 7132: 			$env{'form.scantron_selectfile'});
 7133:     }
 7134:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7135: }
 7136: 
 7137: =pod
 7138: 
 7139: =item scantron_get_line
 7140: 
 7141:    Returns the correct version of the scanline
 7142: 
 7143:  Arguments:
 7144:     $scanlines - hash ref that looks like the first return value from
 7145:                  &scantron_getfile()
 7146:     $scan_data - hash ref that looks like the second return value from
 7147:                  &scantron_getfile()
 7148:     $i         - number of the requested line (starts at 0)
 7149: 
 7150:  Returns:
 7151:    A scanline, (either the original or the corrected one if it
 7152:    exists), or undef if the requested scanline should be
 7153:    skipped. (Either because it's an skipped scanline, or it's an
 7154:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7155:    pass.
 7156: 
 7157: =cut
 7158: 
 7159: sub scantron_get_line {
 7160:     my ($scanlines,$scan_data,$i)=@_;
 7161:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7162:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7163:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7164:     return $scanlines->{'orig'}[$i]; 
 7165: }
 7166: 
 7167: =pod
 7168: 
 7169: =item scantron_todo_count
 7170: 
 7171:     Counts the number of scanlines that need processing.
 7172: 
 7173:  Arguments:
 7174:     $scanlines - hash ref that looks like the first return value from
 7175:                  &scantron_getfile()
 7176:     $scan_data - hash ref that looks like the second return value from
 7177:                  &scantron_getfile()
 7178: 
 7179:  Returns:
 7180:     $count - number of scanlines to process
 7181: 
 7182: =cut
 7183: 
 7184: sub get_todo_count {
 7185:     my ($scanlines,$scan_data)=@_;
 7186:     my $count=0;
 7187:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7188: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7189: 	if ($line=~/^[\s\cz]*$/) { next; }
 7190: 	$count++;
 7191:     }
 7192:     return $count;
 7193: }
 7194: 
 7195: =pod
 7196: 
 7197: =item scantron_put_line
 7198: 
 7199:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7200:     data file.
 7201: 
 7202:  Arguments:
 7203:     $scanlines - hash ref that looks like the first return value from
 7204:                  &scantron_getfile()
 7205:     $scan_data - hash ref that looks like the second return value from
 7206:                  &scantron_getfile()
 7207:     $i         - line number to update
 7208:     $newline   - contents of the updated scanline
 7209:     $skip      - if true make the line for skipping and update the
 7210:                  'skipped' file
 7211: 
 7212: =cut
 7213: 
 7214: sub scantron_put_line {
 7215:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7216:     if ($skip) {
 7217: 	$scanlines->{'skipped'}[$i]=$newline;
 7218: 	&start_skipping($scan_data,$i);
 7219: 	return;
 7220:     }
 7221:     $scanlines->{'corrected'}[$i]=$newline;
 7222: }
 7223: 
 7224: =pod
 7225: 
 7226: =item scantron_clear_skip
 7227: 
 7228:    Remove a line from the 'skipped' file
 7229: 
 7230:  Arguments:
 7231:     $scanlines - hash ref that looks like the first return value from
 7232:                  &scantron_getfile()
 7233:     $scan_data - hash ref that looks like the second return value from
 7234:                  &scantron_getfile()
 7235:     $i         - line number to update
 7236: 
 7237: =cut
 7238: 
 7239: sub scantron_clear_skip {
 7240:     my ($scanlines,$scan_data,$i)=@_;
 7241:     if (exists($scanlines->{'skipped'}[$i])) {
 7242: 	undef($scanlines->{'skipped'}[$i]);
 7243: 	return 1;
 7244:     }
 7245:     return 0;
 7246: }
 7247: 
 7248: =pod
 7249: 
 7250: =item scantron_filter_not_exam
 7251: 
 7252:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7253:    filter out resources that are not marked as 'exam' mode
 7254: 
 7255: =cut
 7256: 
 7257: sub scantron_filter_not_exam {
 7258:     my ($curres)=@_;
 7259:     
 7260:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7261: 	# if the user has asked to not have either hidden
 7262: 	# or 'randomout' controlled resources to be graded
 7263: 	# don't include them
 7264: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7265: 	    && $curres->randomout) {
 7266: 	    return 0;
 7267: 	}
 7268: 	return 1;
 7269:     }
 7270:     return 0;
 7271: }
 7272: 
 7273: =pod
 7274: 
 7275: =item scantron_validate_sequence
 7276: 
 7277:     Validates the selected sequence, checking for resource that are
 7278:     not set to exam mode.
 7279: 
 7280: =cut
 7281: 
 7282: sub scantron_validate_sequence {
 7283:     my ($r,$currentphase) = @_;
 7284: 
 7285:     my $navmap=Apache::lonnavmaps::navmap->new();
 7286:     unless (ref($navmap)) {
 7287:         $r->print(&navmap_errormsg());
 7288:         return (1,$currentphase);
 7289:     }
 7290:     my (undef,undef,$sequence)=
 7291: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7292: 
 7293:     my $map=$navmap->getResourceByUrl($sequence);
 7294: 
 7295:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7296:                                     value="ignore" />');
 7297:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7298: 	my @resources=
 7299: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7300: 	if (@resources) {
 7301: 	    $r->print('<p class="LC_warning">'
 7302:                .&mt('Some resources in the sequence currently are not set to'
 7303:                    .' exam mode. Grading these resources currently may not'
 7304:                    .' work correctly.')
 7305:                .'</p>'
 7306:             );
 7307: 	    return (1,$currentphase);
 7308: 	}
 7309:     }
 7310: 
 7311:     return (0,$currentphase+1);
 7312: }
 7313: 
 7314: 
 7315: 
 7316: sub scantron_validate_ID {
 7317:     my ($r,$currentphase) = @_;
 7318:     
 7319:     #get student info
 7320:     my $classlist=&Apache::loncoursedata::get_classlist();
 7321:     my %idmap=&username_to_idmap($classlist);
 7322: 
 7323:     #get scantron line setup
 7324:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7325:     my ($scanlines,$scan_data)=&scantron_getfile();
 7326: 
 7327:     my $nav_error;
 7328:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7329:     if ($nav_error) {
 7330:         $r->print(&navmap_errormsg());
 7331:         return(1,$currentphase);
 7332:     }
 7333: 
 7334:     my %found=('ids'=>{},'usernames'=>{});
 7335:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7336: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7337: 	if ($line=~/^[\s\cz]*$/) { next; }
 7338: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7339: 						 $scan_data);
 7340: 	my $id=$$scan_record{'scantron.ID'};
 7341: 	my $found;
 7342: 	foreach my $checkid (keys(%idmap)) {
 7343: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7344: 	}
 7345: 	if ($found) {
 7346: 	    my $username=$idmap{$found};
 7347: 	    if ($found{'ids'}{$found}) {
 7348: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7349: 					 $line,'duplicateID',$found);
 7350: 		return(1,$currentphase);
 7351: 	    } elsif ($found{'usernames'}{$username}) {
 7352: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7353: 					 $line,'duplicateID',$username);
 7354: 		return(1,$currentphase);
 7355: 	    }
 7356: 	    #FIXME store away line we previously saw the ID on to use above
 7357: 	    $found{'ids'}{$found}++;
 7358: 	    $found{'usernames'}{$username}++;
 7359: 	} else {
 7360: 	    if ($id =~ /^\s*$/) {
 7361: 		my $username=&scan_data($scan_data,"$i.user");
 7362: 		if (defined($username) && $found{'usernames'}{$username}) {
 7363: 		    &scantron_get_correction($r,$i,$scan_record,
 7364: 					     \%scantron_config,
 7365: 					     $line,'duplicateID',$username);
 7366: 		    return(1,$currentphase);
 7367: 		} elsif (!defined($username)) {
 7368: 		    &scantron_get_correction($r,$i,$scan_record,
 7369: 					     \%scantron_config,
 7370: 					     $line,'incorrectID');
 7371: 		    return(1,$currentphase);
 7372: 		}
 7373: 		$found{'usernames'}{$username}++;
 7374: 	    } else {
 7375: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7376: 					 $line,'incorrectID');
 7377: 		return(1,$currentphase);
 7378: 	    }
 7379: 	}
 7380:     }
 7381: 
 7382:     return (0,$currentphase+1);
 7383: }
 7384: 
 7385: 
 7386: sub scantron_get_correction {
 7387:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7388:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7389: #FIXME in the case of a duplicated ID the previous line, probably need
 7390: #to show both the current line and the previous one and allow skipping
 7391: #the previous one or the current one
 7392: 
 7393:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7394:         $r->print(
 7395:             '<p class="LC_warning">'
 7396:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7397:                 "<b>$error</b>",
 7398:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7399:            ."</p> \n");
 7400:     } else {
 7401:         $r->print(
 7402:             '<p class="LC_warning">'
 7403:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7404:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7405:            ."</p> \n");
 7406:     }
 7407:     my $message =
 7408:         '<p>'
 7409:        .&mt('The ID on the form is [_1]',
 7410:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7411:        .'<br />'
 7412:        .&mt('The name on the paper is [_1], [_2]',
 7413:             $$scan_record{'scantron.LastName'},
 7414:             $$scan_record{'scantron.FirstName'})
 7415:        .'</p>';
 7416: 
 7417:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7418:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7419:                            # Array populated for doublebubble or
 7420:     my @lines_to_correct;  # missingbubble errors to build javascript
 7421:                            # to validate radio button checking   
 7422: 
 7423:     if ($error =~ /ID$/) {
 7424: 	if ($error eq 'incorrectID') {
 7425: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7426: 		      "</p>\n");
 7427: 	} elsif ($error eq 'duplicateID') {
 7428: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7429: 	}
 7430: 	$r->print($message);
 7431: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7432: 	$r->print("\n<ul><li> ");
 7433: 	#FIXME it would be nice if this sent back the user ID and
 7434: 	#could do partial userID matches
 7435: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7436: 				       'scantron_username','scantron_domain'));
 7437: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7438: 	$r->print("\n:\n".
 7439: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7440: 
 7441: 	$r->print('</li>');
 7442:     } elsif ($error =~ /CODE$/) {
 7443: 	if ($error eq 'incorrectCODE') {
 7444: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7445: 	} elsif ($error eq 'duplicateCODE') {
 7446: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 7447: 	}
 7448:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7449:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7450:                  ."</p>\n");
 7451: 	$r->print($message);
 7452: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7453: 	$r->print("\n<br /> ");
 7454: 	my $i=0;
 7455: 	if ($error eq 'incorrectCODE' 
 7456: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7457: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7458: 	    if ($closest > 0) {
 7459: 		foreach my $testcode (@{$closest}) {
 7460: 		    my $checked='';
 7461: 		    if (!$i) { $checked=' checked="checked"'; }
 7462: 		    $r->print("
 7463:    <label>
 7464:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7465:        ".&mt("Use the similar CODE [_1] instead.",
 7466: 	    "<b><tt>".$testcode."</tt></b>")."
 7467:     </label>
 7468:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7469: 		    $r->print("\n<br />");
 7470: 		    $i++;
 7471: 		}
 7472: 	    }
 7473: 	}
 7474: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7475: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7476: 	    $r->print("
 7477:     <label>
 7478:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7479:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7480: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7481:     </label>");
 7482: 	    $r->print("\n<br />");
 7483: 	}
 7484: 
 7485: 	$r->print(<<ENDSCRIPT);
 7486: <script type="text/javascript">
 7487: function change_radio(field) {
 7488:     var slct=document.scantronupload.scantron_CODE_resolution;
 7489:     var i;
 7490:     for (i=0;i<slct.length;i++) {
 7491:         if (slct[i].value==field) { slct[i].checked=true; }
 7492:     }
 7493: }
 7494: </script>
 7495: ENDSCRIPT
 7496: 	my $href="/adm/pickcode?".
 7497: 	   "form=".&escape("scantronupload").
 7498: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7499: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7500: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7501: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7502: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7503: 	    $r->print("
 7504:     <label>
 7505:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7506:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7507: 	     "<a target='_blank' href='$href'>","</a>")."
 7508:     </label> 
 7509:     ".&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\')" />'));
 7510: 	    $r->print("\n<br />");
 7511: 	}
 7512: 	$r->print("
 7513:     <label>
 7514:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7515:        ".&mt("Use [_1] as the CODE.",
 7516: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7517: 	$r->print("\n<br /><br />");
 7518:     } elsif ($error eq 'doublebubble') {
 7519: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7520: 
 7521: 	# The form field scantron_questions is acutally a list of line numbers.
 7522: 	# represented by this form so:
 7523: 
 7524: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7525:                                                 $respnumlookup,$startline);
 7526: 
 7527: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7528: 		  $line_list.'" />');
 7529: 	$r->print($message);
 7530: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7531: 	foreach my $question (@{$arg}) {
 7532: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7533:                                                    $scan_record, $error,
 7534:                                                    $randomorder,$randompick,
 7535:                                                    $respnumlookup,$startline);
 7536:             push(@lines_to_correct,@linenums);
 7537: 	}
 7538:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7539:     } elsif ($error eq 'missingbubble') {
 7540: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7541: 	$r->print($message);
 7542: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7543: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7544: 
 7545: 	# The form field scantron_questions is actually a list of line numbers not
 7546: 	# a list of question numbers. Therefore:
 7547: 	#
 7548: 	
 7549: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7550:                                                 $respnumlookup,$startline);
 7551: 
 7552: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7553: 		  $line_list.'" />');
 7554: 	foreach my $question (@{$arg}) {
 7555: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7556:                                                    $scan_record, $error,
 7557:                                                    $randomorder,$randompick,
 7558:                                                    $respnumlookup,$startline);
 7559:             push(@lines_to_correct,@linenums);
 7560: 	}
 7561:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7562:     } else {
 7563: 	$r->print("\n<ul>");
 7564:     }
 7565:     $r->print("\n</li></ul>");
 7566: }
 7567: 
 7568: sub verify_bubbles_checked {
 7569:     my (@ansnums) = @_;
 7570:     my $ansnumstr = join('","',@ansnums);
 7571:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7572:     my $output = (<<ENDSCRIPT);
 7573: <script type="text/javascript">
 7574: function verify_bubble_radio(form) {
 7575:     var ansnumArray = new Array ("$ansnumstr");
 7576:     var need_bubble_count = 0;
 7577:     for (var i=0; i<ansnumArray.length; i++) {
 7578:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7579:             var bubble_picked = 0; 
 7580:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7581:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7582:                     bubble_picked = 1;
 7583:                 }
 7584:             }
 7585:             if (bubble_picked == 0) {
 7586:                 need_bubble_count ++;
 7587:             }
 7588:         }
 7589:     }
 7590:     if (need_bubble_count) {
 7591:         alert("$warning");
 7592:         return;
 7593:     }
 7594:     form.submit(); 
 7595: }
 7596: </script>
 7597: ENDSCRIPT
 7598:     return $output;
 7599: }
 7600: 
 7601: =pod
 7602: 
 7603: =item  questions_to_line_list
 7604: 
 7605: Converts a list of questions into a string of comma separated
 7606: line numbers in the answer sheet used by the questions.  This is
 7607: used to fill in the scantron_questions form field.
 7608: 
 7609:   Arguments:
 7610:      questions    - Reference to an array of questions.
 7611:      randomorder  - True if randomorder in use.
 7612:      randompick   - True if randompick in use.
 7613:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7614:                      for current line to question number used for same question
 7615:                      in "Master Seqence" (as seen by Course Coordinator).
 7616:      startline    - Reference to hash where key is question number (0 is first)
 7617:                     and key is number of first bubble line for current student
 7618:                     or code-based randompick and/or randomorder.
 7619: 
 7620: =cut
 7621: 
 7622: 
 7623: sub questions_to_line_list {
 7624:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7625:     my @lines;
 7626: 
 7627:     foreach my $item (@{$questions}) {
 7628:         my $question = $item;
 7629:         my ($first,$count,$last);
 7630:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7631:             $question = $1;
 7632:             my $subquestion = $2;
 7633:             my $responsenum = $question-1;
 7634:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7635:                 $responsenum = $respnumlookup->{$question-1};
 7636:                 if (ref($startline) eq 'HASH') {
 7637:                     $first = $startline->{$question-1} + 1;
 7638:                 }
 7639:             } else {
 7640:                 $first = $first_bubble_line{$responsenum} + 1;
 7641:             }
 7642:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7643:             my $subcount = 1;
 7644:             while ($subcount<$subquestion) {
 7645:                 $first += $subans[$subcount-1];
 7646:                 $subcount ++;
 7647:             }
 7648:             $count = $subans[$subquestion-1];
 7649:         } else {
 7650:             my $responsenum = $question-1;
 7651:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7652:                 $responsenum = $respnumlookup->{$question-1};
 7653:                 if (ref($startline) eq 'HASH') {
 7654:                     $first = $startline->{$question-1} + 1;
 7655:                 }
 7656:             } else {
 7657:                 $first = $first_bubble_line{$responsenum} + 1;
 7658:             }
 7659:             $count   = $bubble_lines_per_response{$responsenum};
 7660:         }
 7661:         $last = $first+$count-1;
 7662:         push(@lines, ($first..$last));
 7663:     }
 7664:     return join(',', @lines);
 7665: }
 7666: 
 7667: =pod 
 7668: 
 7669: =item prompt_for_corrections
 7670: 
 7671: Prompts for a potentially multiline correction to the
 7672: user's bubbling (factors out common code from scantron_get_correction
 7673: for multi and missing bubble cases).
 7674: 
 7675:  Arguments:
 7676:    $r           - Apache request object.
 7677:    $question    - The question number to prompt for.
 7678:    $scan_config - The scantron file configuration hash.
 7679:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7680:    $error       - Type of error
 7681:    $randomorder - True if randomorder in use.
 7682:    $randompick  - True if randompick in use.
 7683:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7684:                     for current line to question number used for same question
 7685:                     in "Master Seqence" (as seen by Course Coordinator).
 7686:    $startline   - Reference to hash where key is question number (0 is first)
 7687:                   and value is number of first bubble line for current student
 7688:                   or code-based randompick and/or randomorder.
 7689: 
 7690:  Implicit inputs:
 7691:    %bubble_lines_per_response   - Starting line numbers for each question.
 7692:                                   Numbered from 0 (but question numbers are from
 7693:                                   1.
 7694:    %first_bubble_line           - Starting bubble line for each question.
 7695:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7696:                                   type problems render as separate sub-questions, 
 7697:                                   in exam mode. This hash contains a 
 7698:                                   comma-separated list of the lines per 
 7699:                                   sub-question.
 7700:    %responsetype_per_response   - essayresponse, formularesponse,
 7701:                                   stringresponse, imageresponse, reactionresponse,
 7702:                                   and organicresponse type problem parts can have
 7703:                                   multiple lines per response if the weight
 7704:                                   assigned exceeds 10.  In this case, only
 7705:                                   one bubble per line is permitted, but more 
 7706:                                   than one line might contain bubbles, e.g.
 7707:                                   bubbling of: line 1 - J, line 2 - J, 
 7708:                                   line 3 - B would assign 22 points.  
 7709: 
 7710: =cut
 7711: 
 7712: sub prompt_for_corrections {
 7713:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7714:         $randompick, $respnumlookup, $startline) = @_;
 7715:     my ($current_line,$lines);
 7716:     my @linenums;
 7717:     my $questionnum = $question;
 7718:     my ($first,$responsenum);
 7719:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7720:         $question = $1;
 7721:         my $subquestion = $2;
 7722:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7723:             $responsenum = $respnumlookup->{$question-1};
 7724:             if (ref($startline) eq 'HASH') {
 7725:                 $first = $startline->{$question-1};
 7726:             }
 7727:         } else {
 7728:             $responsenum = $question-1;
 7729:             $first = $first_bubble_line{$responsenum} + 1;
 7730:         }
 7731:         $current_line = $first + 1 ;
 7732:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7733:         my $subcount = 1;
 7734:         while ($subcount<$subquestion) {
 7735:             $current_line += $subans[$subcount-1];
 7736:             $subcount ++;
 7737:         }
 7738:         $lines = $subans[$subquestion-1];
 7739:     } else {
 7740:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7741:             $responsenum = $respnumlookup->{$question-1};
 7742:             if (ref($startline) eq 'HASH') {
 7743:                 $first = $startline->{$question-1};
 7744:             }
 7745:         } else {
 7746:             $responsenum = $question-1;
 7747:             $first = $first_bubble_line{$responsenum};
 7748:         }
 7749:         $current_line = $first + 1;
 7750:         $lines        = $bubble_lines_per_response{$responsenum};
 7751:     }
 7752:     if ($lines > 1) {
 7753:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7754:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7755:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7756:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7757:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7758:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7759:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7760:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet 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 />');
 7761:         } else {
 7762:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7763:         }
 7764:     }
 7765:     for (my $i =0; $i < $lines; $i++) {
 7766:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7767: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7768: 	        		  $questionnum,$error,split('', $selected));
 7769:         push(@linenums,$current_line);
 7770: 	$current_line++;
 7771:     }
 7772:     if ($lines > 1) {
 7773: 	$r->print("<hr /><br />");
 7774:     }
 7775:     return @linenums;
 7776: }
 7777: 
 7778: =pod
 7779: 
 7780: =item scantron_bubble_selector
 7781:   
 7782:    Generates the html radiobuttons to correct a single bubble line
 7783:    possibly showing the existing the selected bubbles if known
 7784: 
 7785:  Arguments:
 7786:     $r           - Apache request object
 7787:     $scan_config - hash from &get_scantron_config()
 7788:     $line        - Number of the line being displayed.
 7789:     $questionnum - Question number (may include subquestion)
 7790:     $error       - Type of error.
 7791:     @selected    - Array of bubbles picked on this line.
 7792: 
 7793: =cut
 7794: 
 7795: sub scantron_bubble_selector {
 7796:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7797:     my $max=$$scan_config{'Qlength'};
 7798: 
 7799:     my $scmode=$$scan_config{'Qon'};
 7800:     if ($scmode eq 'number' || $scmode eq 'letter') {
 7801:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7802:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7803:             $max=$$scan_config{'BubblesPerRow'};
 7804:             if (($scmode eq 'number') && ($max > 10)) {
 7805:                 $max = 10;
 7806:             } elsif (($scmode eq 'letter') && $max > 26) {
 7807:                 $max = 26;
 7808:             }
 7809:         } else {
 7810:             $max = 10;
 7811:         }
 7812:     }
 7813: 
 7814:     my @alphabet=('A'..'Z');
 7815:     $r->print(&Apache::loncommon::start_data_table().
 7816:               &Apache::loncommon::start_data_table_row());
 7817:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7818:     for (my $i=0;$i<$max+1;$i++) {
 7819: 	$r->print("\n".'<td align="center">');
 7820: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7821: 	else { $r->print('&nbsp;'); }
 7822: 	$r->print('</td>');
 7823:     }
 7824:     $r->print(&Apache::loncommon::end_data_table_row().
 7825:               &Apache::loncommon::start_data_table_row());
 7826:     for (my $i=0;$i<$max;$i++) {
 7827: 	$r->print("\n".
 7828: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7829: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7830:     }
 7831:     my $nobub_checked = ' ';
 7832:     if ($error eq 'missingbubble') {
 7833:         $nobub_checked = ' checked = "checked" ';
 7834:     }
 7835:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7836: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7837:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7838:               $line.'" value="'.$questionnum.'" /></td>');
 7839:     $r->print(&Apache::loncommon::end_data_table_row().
 7840:               &Apache::loncommon::end_data_table());
 7841: }
 7842: 
 7843: =pod
 7844: 
 7845: =item num_matches
 7846: 
 7847:    Counts the number of characters that are the same between the two arguments.
 7848: 
 7849:  Arguments:
 7850:    $orig - CODE from the scanline
 7851:    $code - CODE to match against
 7852: 
 7853:  Returns:
 7854:    $count - integer count of the number of same characters between the
 7855:             two arguments
 7856: 
 7857: =cut
 7858: 
 7859: sub num_matches {
 7860:     my ($orig,$code) = @_;
 7861:     my @code=split(//,$code);
 7862:     my @orig=split(//,$orig);
 7863:     my $same=0;
 7864:     for (my $i=0;$i<scalar(@code);$i++) {
 7865: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7866:     }
 7867:     return $same;
 7868: }
 7869: 
 7870: =pod
 7871: 
 7872: =item scantron_get_closely_matching_CODEs
 7873: 
 7874:    Cycles through all CODEs and finds the set that has the greatest
 7875:    number of same characters as the provided CODE
 7876: 
 7877:  Arguments:
 7878:    $allcodes - hash ref returned by &get_codes()
 7879:    $CODE     - CODE from the current scanline
 7880: 
 7881:  Returns:
 7882:    2 element list
 7883:     - first elements is number of how closely matching the best fit is 
 7884:       (5 means best set has 5 matching characters)
 7885:     - second element is an arrary ref containing the set of valid CODEs
 7886:       that best fit the passed in CODE
 7887: 
 7888: =cut
 7889: 
 7890: sub scantron_get_closely_matching_CODEs {
 7891:     my ($allcodes,$CODE)=@_;
 7892:     my @CODEs;
 7893:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7894: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7895:     }
 7896: 
 7897:     return ($#CODEs,$CODEs[-1]);
 7898: }
 7899: 
 7900: =pod
 7901: 
 7902: =item get_codes
 7903: 
 7904:    Builds a hash which has keys of all of the valid CODEs from the selected
 7905:    set of remembered CODEs.
 7906: 
 7907:  Arguments:
 7908:   $old_name - name of the set of remembered CODEs
 7909:   $cdom     - domain of the course
 7910:   $cnum     - internal course name
 7911: 
 7912:  Returns:
 7913:   %allcodes - keys are the valid CODEs, values are all 1
 7914: 
 7915: =cut
 7916: 
 7917: sub get_codes {
 7918:     my ($old_name, $cdom, $cnum) = @_;
 7919:     if (!$old_name) {
 7920: 	$old_name=$env{'form.scantron_CODElist'};
 7921:     }
 7922:     if (!$cdom) {
 7923: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7924:     }
 7925:     if (!$cnum) {
 7926: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7927:     }
 7928:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7929: 				    $cdom,$cnum);
 7930:     my %allcodes;
 7931:     if ($result{"type\0$old_name"} eq 'number') {
 7932: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7933:     } else {
 7934: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7935:     }
 7936:     return %allcodes;
 7937: }
 7938: 
 7939: =pod
 7940: 
 7941: =item scantron_validate_CODE
 7942: 
 7943:    Validates all scanlines in the selected file to not have any
 7944:    invalid or underspecified CODEs and that none of the codes are
 7945:    duplicated if this was requested.
 7946: 
 7947: =cut
 7948: 
 7949: sub scantron_validate_CODE {
 7950:     my ($r,$currentphase) = @_;
 7951:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7952:     if ($scantron_config{'CODElocation'} &&
 7953: 	$scantron_config{'CODEstart'} &&
 7954: 	$scantron_config{'CODElength'}) {
 7955: 	if (!defined($env{'form.scantron_CODElist'})) {
 7956: 	    &FIXME_blow_up()
 7957: 	}
 7958:     } else {
 7959: 	return (0,$currentphase+1);
 7960:     }
 7961:     
 7962:     my %usedCODEs;
 7963: 
 7964:     my %allcodes=&get_codes();
 7965: 
 7966:     my $nav_error;
 7967:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7968:     if ($nav_error) {
 7969:         $r->print(&navmap_errormsg());
 7970:         return(1,$currentphase);
 7971:     }
 7972: 
 7973:     my ($scanlines,$scan_data)=&scantron_getfile();
 7974:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7975: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7976: 	if ($line=~/^[\s\cz]*$/) { next; }
 7977: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7978: 						 $scan_data);
 7979: 	my $CODE=$$scan_record{'scantron.CODE'};
 7980: 	my $error=0;
 7981: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7982: 	    &scantron_get_correction($r,$i,$scan_record,
 7983: 				     \%scantron_config,
 7984: 				     $line,'incorrectCODE',\%allcodes);
 7985: 	    return(1,$currentphase);
 7986: 	}
 7987: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7988: 	    && !$$scan_record{'scantron.useCODE'}) {
 7989: 	    &scantron_get_correction($r,$i,$scan_record,
 7990: 				     \%scantron_config,
 7991: 				     $line,'incorrectCODE',\%allcodes);
 7992: 	    return(1,$currentphase);
 7993: 	}
 7994: 	if (exists($usedCODEs{$CODE}) 
 7995: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7996: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7997: 	    &scantron_get_correction($r,$i,$scan_record,
 7998: 				     \%scantron_config,
 7999: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8000: 	    return(1,$currentphase);
 8001: 	}
 8002: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8003:     }
 8004:     return (0,$currentphase+1);
 8005: }
 8006: 
 8007: =pod
 8008: 
 8009: =item scantron_validate_doublebubble
 8010: 
 8011:    Validates all scanlines in the selected file to not have any
 8012:    bubble lines with multiple bubbles marked.
 8013: 
 8014: =cut
 8015: 
 8016: sub scantron_validate_doublebubble {
 8017:     my ($r,$currentphase) = @_;
 8018:     #get student info
 8019:     my $classlist=&Apache::loncoursedata::get_classlist();
 8020:     my %idmap=&username_to_idmap($classlist);
 8021:     my (undef,undef,$sequence)=
 8022:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8023: 
 8024:     #get scantron line setup
 8025:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8026:     my ($scanlines,$scan_data)=&scantron_getfile();
 8027: 
 8028:     my $navmap = Apache::lonnavmaps::navmap->new();
 8029:     unless (ref($navmap)) {
 8030:         $r->print(&navmap_errormsg());
 8031:         return(1,$currentphase);
 8032:     }
 8033:     my $map=$navmap->getResourceByUrl($sequence);
 8034:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8035:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8036:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8037:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8038: 
 8039:     my $nav_error;
 8040:     if (ref($map)) {
 8041:         $randomorder = $map->randomorder();
 8042:         $randompick = $map->randompick();
 8043:         if ($randomorder || $randompick) {
 8044:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8045:             if ($nav_error) {
 8046:                 $r->print(&navmap_errormsg());
 8047:                 return(1,$currentphase);
 8048:             }
 8049:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8050:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8051:         }
 8052:     } else {
 8053:         $r->print(&navmap_errormsg());
 8054:         return(1,$currentphase);
 8055:     }
 8056: 
 8057:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8058:     if ($nav_error) {
 8059:         $r->print(&navmap_errormsg());
 8060:         return(1,$currentphase);
 8061:     }
 8062: 
 8063:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8064: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8065: 	if ($line=~/^[\s\cz]*$/) { next; }
 8066: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8067: 						 $scan_data,undef,\%idmap,$randomorder,
 8068:                                                  $randompick,$sequence,\@master_seq,
 8069:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8070:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8071: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8072: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8073: 				 'doublebubble',
 8074: 				 $$scan_record{'scantron.doubleerror'},
 8075:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8076:     	return (1,$currentphase);
 8077:     }
 8078:     return (0,$currentphase+1);
 8079: }
 8080: 
 8081: 
 8082: sub scantron_get_maxbubble {
 8083:     my ($nav_error,$scantron_config) = @_;
 8084:     if (defined($env{'form.scantron_maxbubble'}) &&
 8085: 	$env{'form.scantron_maxbubble'}) {
 8086: 	&restore_bubble_lines();
 8087: 	return $env{'form.scantron_maxbubble'};
 8088:     }
 8089: 
 8090:     my (undef, undef, $sequence) =
 8091: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8092: 
 8093:     my $navmap=Apache::lonnavmaps::navmap->new();
 8094:     unless (ref($navmap)) {
 8095:         if (ref($nav_error)) {
 8096:             $$nav_error = 1;
 8097:         }
 8098:         return;
 8099:     }
 8100:     my $map=$navmap->getResourceByUrl($sequence);
 8101:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8102:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8103: 
 8104:     &Apache::lonxml::clear_problem_counter();
 8105: 
 8106:     my $uname       = $env{'user.name'};
 8107:     my $udom        = $env{'user.domain'};
 8108:     my $cid         = $env{'request.course.id'};
 8109:     my $total_lines = 0;
 8110:     %bubble_lines_per_response = ();
 8111:     %first_bubble_line         = ();
 8112:     %subdivided_bubble_lines   = ();
 8113:     %responsetype_per_response = ();
 8114:     %masterseq_id_responsenum  = ();
 8115: 
 8116:     my $response_number = 0;
 8117:     my $bubble_line     = 0;
 8118:     foreach my $resource (@resources) {
 8119:         my $resid = $resource->id();
 8120:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8121:                                                           $udom,undef,$bubbles_per_row);
 8122:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8123: 	    foreach my $part_id (@{$parts}) {
 8124:                 my $lines;
 8125: 
 8126: 	        # TODO - make this a persistent hash not an array.
 8127: 
 8128:                 # optionresponse, matchresponse and rankresponse type items 
 8129:                 # render as separate sub-questions in exam mode.
 8130:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8131:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8132:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8133:                     my ($numbub,$numshown);
 8134:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8135:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8136:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8137:                         }
 8138:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8139:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8140:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8141:                         }
 8142:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8143:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8144:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8145:                         }
 8146:                     }
 8147:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8148:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8149:                     }
 8150:                     my $bubbles_per_row =
 8151:                         &bubblesheet_bubbles_per_row($scantron_config);
 8152:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8153:                     if (($numbub % $bubbles_per_row) != 0) {
 8154:                         $inner_bubble_lines++;
 8155:                     }
 8156:                     for (my $i=0; $i<$numshown; $i++) {
 8157:                         $subdivided_bubble_lines{$response_number} .= 
 8158:                             $inner_bubble_lines.',';
 8159:                     }
 8160:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8161:                     $lines = $numshown * $inner_bubble_lines;
 8162:                 } else {
 8163:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8164:                 }
 8165: 
 8166:                 $first_bubble_line{$response_number} = $bubble_line;
 8167: 	        $bubble_lines_per_response{$response_number} = $lines;
 8168:                 $responsetype_per_response{$response_number} = 
 8169:                     $analysis->{$part_id.'.type'};
 8170:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8171: 	        $response_number++;
 8172: 
 8173: 	        $bubble_line +=  $lines;
 8174: 	        $total_lines +=  $lines;
 8175: 	    }
 8176:         }
 8177:     }
 8178:     &Apache::lonnet::delenv('scantron.');
 8179: 
 8180:     &save_bubble_lines();
 8181:     $env{'form.scantron_maxbubble'} =
 8182: 	$total_lines;
 8183:     return $env{'form.scantron_maxbubble'};
 8184: }
 8185: 
 8186: sub bubblesheet_bubbles_per_row {
 8187:     my ($scantron_config) = @_;
 8188:     my $bubbles_per_row;
 8189:     if (ref($scantron_config) eq 'HASH') {
 8190:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8191:     }
 8192:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8193:         $bubbles_per_row = 10;
 8194:     }
 8195:     return $bubbles_per_row;
 8196: }
 8197: 
 8198: sub scantron_validate_missingbubbles {
 8199:     my ($r,$currentphase) = @_;
 8200:     #get student info
 8201:     my $classlist=&Apache::loncoursedata::get_classlist();
 8202:     my %idmap=&username_to_idmap($classlist);
 8203:     my (undef,undef,$sequence)=
 8204:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8205: 
 8206:     #get scantron line setup
 8207:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8208:     my ($scanlines,$scan_data)=&scantron_getfile();
 8209: 
 8210:     my $navmap = Apache::lonnavmaps::navmap->new();
 8211:     unless (ref($navmap)) {
 8212:         $r->print(&navmap_errormsg());
 8213:         return(1,$currentphase);
 8214:     }
 8215: 
 8216:     my $map=$navmap->getResourceByUrl($sequence);
 8217:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8218:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8219:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8220:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8221: 
 8222:     my $nav_error;
 8223:     if (ref($map)) {
 8224:         $randomorder = $map->randomorder();
 8225:         $randompick = $map->randompick();
 8226:         if ($randomorder || $randompick) {
 8227:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8228:             if ($nav_error) {
 8229:                 $r->print(&navmap_errormsg());
 8230:                 return(1,$currentphase);
 8231:             }
 8232:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8233:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8234:         }
 8235:     } else {
 8236:         $r->print(&navmap_errormsg());
 8237:         return(1,$currentphase);
 8238:     }
 8239: 
 8240: 
 8241:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8242:     if ($nav_error) {
 8243:         $r->print(&navmap_errormsg());
 8244:         return(1,$currentphase);
 8245:     }
 8246: 
 8247:     if (!$max_bubble) { $max_bubble=2**31; }
 8248:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8249: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8250: 	if ($line=~/^[\s\cz]*$/) { next; }
 8251:         my $scan_record =
 8252:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8253:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8254:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8255:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8256: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8257: 	my @to_correct;
 8258: 	
 8259: 	# Probably here's where the error is...
 8260: 
 8261: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8262:             my $lastbubble;
 8263:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8264:                 my $question = $1;
 8265:                 my $subquestion = $2;
 8266:                 my ($first,$responsenum);
 8267:                 if ($randomorder || $randompick) {
 8268:                     $responsenum = $respnumlookup{$question-1};
 8269:                     $first = $startline{$question-1};
 8270:                 } else {
 8271:                     $responsenum = $question-1;
 8272:                     $first = $first_bubble_line{$responsenum};
 8273:                 }
 8274:                 if (!defined($first)) { next; }
 8275:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8276:                 my $subcount = 1;
 8277:                 while ($subcount<$subquestion) {
 8278:                     $first += $subans[$subcount-1];
 8279:                     $subcount ++;
 8280:                 }
 8281:                 my $count = $subans[$subquestion-1];
 8282:                 $lastbubble = $first + $count;
 8283:             } else {
 8284:                 my ($first,$responsenum);
 8285:                 if ($randomorder || $randompick) {
 8286:                     $responsenum = $respnumlookup{$missing-1};
 8287:                     $first = $startline{$missing-1};
 8288:                 } else {
 8289:                     $responsenum = $missing-1;
 8290:                     $first = $first_bubble_line{$responsenum};
 8291:                 }
 8292:                 if (!defined($first)) { next; }
 8293:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8294:             }
 8295:             if ($lastbubble > $max_bubble) { next; }
 8296: 	    push(@to_correct,$missing);
 8297: 	}
 8298: 	if (@to_correct) {
 8299: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8300: 				     $line,'missingbubble',\@to_correct,
 8301:                                      $randomorder,$randompick,\%respnumlookup,
 8302:                                      \%startline);
 8303: 	    return (1,$currentphase);
 8304: 	}
 8305: 
 8306:     }
 8307:     return (0,$currentphase+1);
 8308: }
 8309: 
 8310: sub hand_bubble_option {
 8311:     my (undef, undef, $sequence) =
 8312:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8313:     return if ($sequence eq '');
 8314:     my $navmap = Apache::lonnavmaps::navmap->new();
 8315:     unless (ref($navmap)) {
 8316:         return;
 8317:     }
 8318:     my $needs_hand_bubbles;
 8319:     my $map=$navmap->getResourceByUrl($sequence);
 8320:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8321:     foreach my $res (@resources) {
 8322:         if (ref($res)) {
 8323:             if ($res->is_problem()) {
 8324:                 my $partlist = $res->parts();
 8325:                 foreach my $part (@{ $partlist }) {
 8326:                     my @types = $res->responseType($part);
 8327:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8328:                         $needs_hand_bubbles = 1;
 8329:                         last;
 8330:                     }
 8331:                 }
 8332:             }
 8333:         }
 8334:     }
 8335:     if ($needs_hand_bubbles) {
 8336:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8337:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8338:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8339:                &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
 8340:                '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label>&nbsp;'.&mt('or').'&nbsp;'.
 8341:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
 8342:     }
 8343:     return;
 8344: }
 8345: 
 8346: sub scantron_process_students {
 8347:     my ($r) = @_;
 8348: 
 8349:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8350:     my ($symb)=&get_symb($r);
 8351:     if (!$symb) {
 8352: 	return '';
 8353:     }
 8354:     my $default_form_data=&defaultFormData($symb);
 8355: 
 8356:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8357:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8358:     my ($scanlines,$scan_data)=&scantron_getfile();
 8359:     my $classlist=&Apache::loncoursedata::get_classlist();
 8360:     my %idmap=&username_to_idmap($classlist);
 8361:     my $navmap=Apache::lonnavmaps::navmap->new();
 8362:     unless (ref($navmap)) {
 8363:         $r->print(&navmap_errormsg());
 8364:         return '';
 8365:     }
 8366:     my $map=$navmap->getResourceByUrl($sequence);
 8367:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8368:         %grader_randomlists_by_symb);
 8369:     if (ref($map)) {
 8370:         $randomorder = $map->randomorder();
 8371:         $randompick = $map->randompick();
 8372:     } else {
 8373:         $r->print(&navmap_errormsg());
 8374:         return '';
 8375:     }
 8376:     my $nav_error;
 8377:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8378:     my (%grader_partids_by_symb,%grader_randomlists_by_symb,%ordered);
 8379:     if ($randomorder || $randompick) {
 8380:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8381:         if ($nav_error) {
 8382:             $r->print(&navmap_errormsg());
 8383:             return '';
 8384:         }
 8385:     }
 8386:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8387:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8388: 
 8389:     my ($uname,$udom);
 8390:     my $result= <<SCANTRONFORM;
 8391: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8392:   <input type="hidden" name="command" value="scantron_configphase" />
 8393:   $default_form_data
 8394: SCANTRONFORM
 8395:     $r->print($result);
 8396: 
 8397:     my @delayqueue;
 8398:     my (%completedstudents,%scandata);
 8399:     
 8400:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8401:     my $count=&get_todo_count($scanlines,$scan_data);
 8402:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8403:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8404: 					  'Processing first student');
 8405:     $r->print('<br />');
 8406:     my $start=&Time::HiRes::time();
 8407:     my $i=-1;
 8408:     my $started;
 8409: 
 8410:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8411:     if ($nav_error) {
 8412:         $r->print(&navmap_errormsg());
 8413:         return '';
 8414:     }
 8415: 
 8416:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8417:     # the user and return.
 8418: 
 8419:     if ($ssi_error) {
 8420: 	$r->print("</form>");
 8421: 	&ssi_print_error($r);
 8422: 	$r->print(&show_grading_menu_form($symb));
 8423:         &Apache::lonnet::remove_lock($lock);
 8424: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8425:     }
 8426: 
 8427:     my %lettdig = &letter_to_digits();
 8428:     my $numletts = scalar(keys(%lettdig));
 8429:     my %orderedforcode;
 8430: 
 8431:     while ($i<$scanlines->{'count'}) {
 8432:  	($uname,$udom)=('','');
 8433:  	$i++;
 8434:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8435:  	if ($line=~/^[\s\cz]*$/) { next; }
 8436: 	if ($started) {
 8437: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8438: 						     'last student');
 8439: 	}
 8440: 	$started=1;
 8441:         my %respnumlookup = ();
 8442:         my %startline = ();
 8443:         my $total;
 8444:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8445:  						 $scan_data,undef,\%idmap,$randomorder,
 8446:                                                  $randompick,$sequence,\@master_seq,
 8447:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8448:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8449:                                                  \$total);
 8450:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8451:  					      \%idmap,$i)) {
 8452:   	    &scantron_add_delay(\@delayqueue,$line,
 8453:  				'Unable to find a student that matches',1);
 8454:  	    next;
 8455:   	}
 8456:  	if (exists $completedstudents{$uname}) {
 8457:  	    &scantron_add_delay(\@delayqueue,$line,
 8458:  				'Student '.$uname.' has multiple sheets',2);
 8459:  	    next;
 8460:  	}
 8461:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8462:         my $user = $uname.':'.$usec;
 8463:   	($uname,$udom)=split(/:/,$uname);
 8464: 
 8465:         my $scancode;
 8466:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8467:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8468:             $scancode = $scan_record->{'scantron.CODE'};
 8469:         } else {
 8470:             $scancode = '';
 8471:         }
 8472: 
 8473:         my @mapresources = @resources;
 8474:         if ($randomorder || $randompick) {
 8475:             @mapresources =
 8476:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8477:                              \%orderedforcode);
 8478:         }
 8479:         my (%partids_by_symb,$res_error);
 8480:         foreach my $resource (@mapresources) {
 8481:             my $ressymb;
 8482:             if (ref($resource)) {
 8483:                 $ressymb = $resource->symb();
 8484:             } else {
 8485:                 $res_error = 1;
 8486:                 last;
 8487:             }
 8488:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8489:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8490:                 my ($analysis,$parts) =
 8491:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8492:                                               $uname,$udom,undef,$bubbles_per_row);
 8493:                 $partids_by_symb{$ressymb} = $parts;
 8494:             } else {
 8495:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8496:             }
 8497:         }
 8498: 
 8499:         if ($res_error) {
 8500:             &scantron_add_delay(\@delayqueue,$line,
 8501:                                 'An error occurred while grading student '.$uname,2);
 8502:             next;
 8503:         }
 8504: 
 8505: 	&Apache::lonxml::clear_problem_counter();
 8506:   	&Apache::lonnet::appenv($scan_record);
 8507: 
 8508: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8509: 	    &scantron_putfile($scanlines,$scan_data);
 8510: 	}
 8511: 	
 8512:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8513:                                    \@mapresources,\%partids_by_symb,
 8514:                                    $bubbles_per_row,$randomorder,$randompick,
 8515:                                    \%respnumlookup,\%startline) 
 8516:             eq 'ssi_error') {
 8517:             $ssi_error = 0; # So end of handler error message does not trigger.
 8518:             $r->print("</form>");
 8519:             &ssi_print_error($r);
 8520:             $r->print(&show_grading_menu_form($symb));
 8521:             &Apache::lonnet::remove_lock($lock);
 8522:             return '';      # Why return ''?  Beats me.
 8523:         }
 8524: 
 8525:         if (($scancode) && ($randomorder || $randompick)) {
 8526:             my $parmresult =
 8527:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8528:                                                        '0_examcode',2,$scancode,
 8529:                                                        'string_examcode',$uname,
 8530:                                                        $udom);
 8531:         }
 8532: 	$completedstudents{$uname}={'line'=>$line};
 8533:         if ($env{'form.verifyrecord'}) {
 8534:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8535:             if ($randompick) {
 8536:                 if ($total) {
 8537:                     $lastpos = $total*$scantron_config{'Qlength'};
 8538:                 }
 8539:             }
 8540: 
 8541:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8542:             chomp($studentdata);
 8543:             $studentdata =~ s/\r$//;
 8544:             my $studentrecord = '';
 8545:             my $counter = -1;
 8546:             foreach my $resource (@mapresources) {
 8547:                 my $ressymb = $resource->symb();
 8548:                 ($counter,my $recording) =
 8549:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8550:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8551:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8552:                                              $randompick,\%respnumlookup,\%startline);
 8553:                 $studentrecord .= $recording;
 8554:             }
 8555:             if ($studentrecord ne $studentdata) {
 8556:                 &Apache::lonxml::clear_problem_counter();
 8557:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8558:                                            \@mapresources,\%partids_by_symb,
 8559:                                            $bubbles_per_row,$randomorder,$randompick,
 8560:                                            \%respnumlookup,\%startline)
 8561:                     eq 'ssi_error') {
 8562:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8563:                     $r->print("</form>");
 8564:                     &ssi_print_error($r);
 8565:                     $r->print(&show_grading_menu_form($symb));
 8566:                     &Apache::lonnet::remove_lock($lock);
 8567:                     delete($completedstudents{$uname});
 8568:                     return '';
 8569:                 }
 8570:                 $counter = -1;
 8571:                 $studentrecord = '';
 8572:                 foreach my $resource (@mapresources) {
 8573:                     my $ressymb = $resource->symb();
 8574:                     ($counter,my $recording) =
 8575:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8576:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8577:                                                  \%scantron_config,\%lettdig,$numletts,
 8578:                                                  $randomorder,$randompick,\%respnumlookup,
 8579:                                                  \%startline);
 8580:                     $studentrecord .= $recording;
 8581:                 }
 8582:                 if ($studentrecord ne $studentdata) {
 8583:                     $r->print('<p><span class="LC_warning">');
 8584:                     if ($scancode eq '') {
 8585:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8586:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8587:                     } else {
 8588:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8589:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8590:                     }
 8591:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8592:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8593:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8594:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8595:                               &Apache::loncommon::start_data_table_row().
 8596:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8597:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 8598:                               &Apache::loncommon::end_data_table_row().
 8599:                               &Apache::loncommon::start_data_table_row().
 8600:                               '<td>'.&mt('Stored submissions').'</td>'.
 8601:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 8602:                               &Apache::loncommon::end_data_table_row().
 8603:                               &Apache::loncommon::end_data_table().'</p>');
 8604:                 } else {
 8605:                     $r->print('<br /><span class="LC_warning">'.
 8606:                              &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 />'.
 8607:                              &mt("As a consequence, this user's submission history records two tries.").
 8608:                                  '</span><br />');
 8609:                 }
 8610:             }
 8611:         }
 8612:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8613:     } continue {
 8614: 	&Apache::lonxml::clear_problem_counter();
 8615: 	&Apache::lonnet::delenv('scantron.');
 8616:     }
 8617:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8618:     &Apache::lonnet::remove_lock($lock);
 8619: #    my $lasttime = &Time::HiRes::time()-$start;
 8620: #    $r->print("<p>took $lasttime</p>");
 8621: 
 8622:     $r->print("</form>");
 8623:     $r->print(&show_grading_menu_form($symb));
 8624:     return '';
 8625: }
 8626: 
 8627: sub graders_resources_pass {
 8628:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8629:         $bubbles_per_row) = @_;
 8630:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8631:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8632:         foreach my $resource (@{$resources}) {
 8633:             my $ressymb = $resource->symb();
 8634:             my ($analysis,$parts) =
 8635:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8636:                                           $env{'user.name'},$env{'user.domain'},
 8637:                                           1,$bubbles_per_row);
 8638:             $grader_partids_by_symb->{$ressymb} = $parts;
 8639:             if (ref($analysis) eq 'HASH') {
 8640:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8641:                     $grader_randomlists_by_symb->{$ressymb} =
 8642:                         $analysis->{'parts_withrandomlist'};
 8643:                 }
 8644:             }
 8645:         }
 8646:     }
 8647:     return;
 8648: }
 8649: 
 8650: =pod
 8651: 
 8652: =item users_order
 8653: 
 8654:   Returns array of resources in current map, ordered based on either CODE,
 8655:   if this is a CODEd exam, or based on student's identity if this is a
 8656:   "NAMEd" exam.
 8657: 
 8658:   Should be used when randomorder and/or randompick applied when the 
 8659:   corresponding exam was printed, prior to students completing bubblesheets 
 8660:   for the version of the exam the student received.
 8661: 
 8662: =cut
 8663: 
 8664: sub users_order  {
 8665:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8666:     my @mapresources;
 8667:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8668:         return @mapresources;
 8669:     }
 8670:     if ($scancode) {
 8671:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8672:             @mapresources = @{$orderedforcode->{$scancode}};
 8673:         } else {
 8674:             $env{'form.CODE'} = $scancode;
 8675:             my $actual_seq =
 8676:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8677:                                                                $master_seq,
 8678:                                                                $user,$scancode,1);
 8679:             if (ref($actual_seq) eq 'ARRAY') {
 8680:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8681:                 if (ref($orderedforcode) eq 'HASH') {
 8682:                     if (@mapresources > 0) {
 8683:                         $orderedforcode->{$scancode} = \@mapresources;
 8684:                     }
 8685:                 }
 8686:             }
 8687:             delete($env{'form.CODE'});
 8688:         }
 8689:     } else {
 8690:         my $actual_seq =
 8691:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8692:                                                            $master_seq,
 8693:                                                            $user,undef,1);
 8694:         if (ref($actual_seq) eq 'ARRAY') {
 8695:             @mapresources =
 8696:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8697:         }
 8698:     }
 8699:     return @mapresources;
 8700: }
 8701: 
 8702: sub grade_student_bubbles {
 8703:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8704:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8705:     my $uselookup = 0;
 8706:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8707:         (ref($startline) eq 'HASH')) {
 8708:         $uselookup = 1;
 8709:     }
 8710: 
 8711:     if (ref($resources) eq 'ARRAY') {
 8712:         my $count = 0;
 8713:         foreach my $resource (@{$resources}) {
 8714:             my $ressymb = $resource->symb();
 8715:             my %form = ('submitted'      => 'scantron',
 8716:                         'grade_target'   => 'grade',
 8717:                         'grade_username' => $uname,
 8718:                         'grade_domain'   => $udom,
 8719:                         'grade_courseid' => $env{'request.course.id'},
 8720:                         'grade_symb'     => $ressymb,
 8721:                         'CODE'           => $scancode
 8722:                        );
 8723:             if ($bubbles_per_row ne '') {
 8724:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8725:             }
 8726:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8727:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8728:             }
 8729:             if (ref($parts) eq 'HASH') {
 8730:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8731:                     foreach my $part (@{$parts->{$ressymb}}) {
 8732:                         if ($uselookup) {
 8733:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8734:                         } else {
 8735:                             $form{'scantron_questnum_start.'.$part} =
 8736:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8737:                         }
 8738:                         $count++;
 8739:                     }
 8740:                 }
 8741:             }
 8742:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8743:             return 'ssi_error' if ($ssi_error);
 8744:             last if (&Apache::loncommon::connection_aborted($r));
 8745:         }
 8746:     }
 8747:     return;
 8748: }
 8749: 
 8750: sub scantron_upload_scantron_data {
 8751:     my ($r)=@_;
 8752:     my $dom = $env{'request.role.domain'};
 8753:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8754:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8755:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8756: 							  'domainid',
 8757: 							  'coursename',$dom);
 8758:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8759:                        ('&nbsp'x2).&mt('(shows course personnel)');
 8760:     my ($symb) = &get_symb($r,1);
 8761:     my $default_form_data=&defaultFormData($symb);
 8762:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8763:     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.");
 8764:     $r->print('
 8765: <script type="text/javascript" language="javascript">
 8766:     function checkUpload(formname) {
 8767: 	if (formname.upfile.value == "") {
 8768: 	    alert("'.$nofile_alert.'");
 8769: 	    return false;
 8770: 	}
 8771:         if (formname.courseid.value == "") {
 8772:             alert("'.$nocourseid_alert.'");
 8773:             return false;
 8774:         }
 8775: 	formname.submit();
 8776:     }
 8777: 
 8778:     function ToSyllabus() {
 8779:         var cdom = '."'$dom'".';
 8780:         var cnum = document.rules.courseid.value;
 8781:         if (cdom == "" || cdom == null) {
 8782:             return;
 8783:         }
 8784:         if (cnum == "" || cnum == null) {
 8785:            return;
 8786:         }
 8787:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8788:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8789:         return;
 8790:     }
 8791: 
 8792: </script>
 8793: 
 8794: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8795: 
 8796: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8797: '.$default_form_data.
 8798:   &Apache::lonhtmlcommon::start_pick_box().
 8799:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8800:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8801:   &Apache::lonhtmlcommon::row_closure().
 8802:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8803:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8804:   &Apache::lonhtmlcommon::row_closure().
 8805:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8806:   '<input name="domainid" type="hidden" />'.$domdesc.
 8807:   &Apache::lonhtmlcommon::row_closure().
 8808:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8809:   '<input type="file" name="upfile" size="50" />'.
 8810:   &Apache::lonhtmlcommon::row_closure(1).
 8811:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8812: 
 8813: <input name="command" value="scantronupload_save" type="hidden" />
 8814: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8815: </form>
 8816: ');
 8817:     return '';
 8818: }
 8819: 
 8820: 
 8821: sub scantron_upload_scantron_data_save {
 8822:     my($r)=@_;
 8823:     my ($symb)=&get_symb($r,1);
 8824:     my $doanotherupload=
 8825: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8826: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8827: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8828: 	'</form>'."\n";
 8829:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8830: 	!&Apache::lonnet::allowed('usc',
 8831: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8832: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8833: 	if ($symb) {
 8834: 	    $r->print(&show_grading_menu_form($symb));
 8835: 	} else {
 8836: 	    $r->print($doanotherupload);
 8837: 	}
 8838: 	return '';
 8839:     }
 8840:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8841:     my $uploadedfile;
 8842:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8843:     if (length($env{'form.upfile'}) < 2) {
 8844:         $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>'));
 8845:     } else {
 8846:         my $result = 
 8847:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8848:                                             $env{'form.courseid'},$env{'form.domainid'});
 8849: 	if ($result =~ m{^/uploaded/}) {
 8850: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8851:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8852: 			  '<span class="LC_filename">'.$result.'</span>'));
 8853:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8854:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8855:                                                        $env{'form.courseid'},$uploadedfile));
 8856: 	} else {
 8857: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8858:                           '<span class="LC_error">','</span>',$result,
 8859: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8860: 	}
 8861:     }
 8862:     if ($symb) {
 8863: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8864:     } else {
 8865: 	$r->print($doanotherupload);
 8866:     }
 8867:     return '';
 8868: }
 8869: 
 8870: sub validate_uploaded_scantron_file {
 8871:     my ($cdom,$cname,$fname) = @_;
 8872:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8873:     my @lines;
 8874:     if ($scanlines ne '-1') {
 8875:         @lines=split("\n",$scanlines,-1);
 8876:     }
 8877:     my $output;
 8878:     if (@lines) {
 8879:         my (%counts,$max_match_format);
 8880:         my ($max_match_count,$max_match_pct) = (0,0);
 8881:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8882:         my %idmap = &username_to_idmap($classlist);
 8883:         foreach my $key (keys(%idmap)) {
 8884:             my $lckey = lc($key);
 8885:             $idmap{$lckey} = $idmap{$key};
 8886:         }
 8887:         my %unique_formats;
 8888:         my @formatlines = &get_scantronformat_file();
 8889:         foreach my $line (@formatlines) {
 8890:             chomp($line);
 8891:             my @config = split(/:/,$line);
 8892:             my $idstart = $config[5];
 8893:             my $idlength = $config[6];
 8894:             if (($idstart ne '') && ($idlength > 0)) {
 8895:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8896:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8897:                 } else {
 8898:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8899:                 }
 8900:             }
 8901:         }
 8902:         foreach my $key (keys(%unique_formats)) {
 8903:             my ($idstart,$idlength) = split(':',$key);
 8904:             %{$counts{$key}} = (
 8905:                                'found'   => 0,
 8906:                                'total'   => 0,
 8907:                               );
 8908:             foreach my $line (@lines) {
 8909:                 next if ($line =~ /^#/);
 8910:                 next if ($line =~ /^[\s\cz]*$/);
 8911:                 my $id = substr($line,$idstart-1,$idlength);
 8912:                 $id = lc($id);
 8913:                 if (exists($idmap{$id})) {
 8914:                     $counts{$key}{'found'} ++;
 8915:                 }
 8916:                 $counts{$key}{'total'} ++;
 8917:             }
 8918:             if ($counts{$key}{'total'}) {
 8919:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8920:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8921:                     $max_match_pct = $percent_match;
 8922:                     $max_match_format = $key;
 8923:                     $max_match_count = $counts{$key}{'total'};
 8924:                 }
 8925:             }
 8926:         }
 8927:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8928:             my $format_descs;
 8929:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8930:             for (my $i=0; $i<$numwithformat; $i++) {
 8931:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8932:                 if ($i<$numwithformat-2) {
 8933:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8934:                 } elsif ($i==$numwithformat-2) {
 8935:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8936:                 } elsif ($i==$numwithformat-1) {
 8937:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8938:                 }
 8939:             }
 8940:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8941:             $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).
 8942:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8943:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8944:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8945:                                   '<i>'.$cdom.'</i>').'</li>'.
 8946:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8947:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8948:                        '</ul>';
 8949:         }
 8950:     } else {
 8951:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8952:     }
 8953:     return $output;
 8954: }
 8955: 
 8956: sub valid_file {
 8957:     my ($requested_file)=@_;
 8958:     foreach my $filename (sort(&scantron_filenames())) {
 8959: 	if ($requested_file eq $filename) { return 1; }
 8960:     }
 8961:     return 0;
 8962: }
 8963: 
 8964: sub scantron_download_scantron_data {
 8965:     my ($r)=@_;
 8966:     my ($symb) = &get_symb($r,1);
 8967:     my $default_form_data=&defaultFormData($symb);
 8968:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8969:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8970:     my $file=$env{'form.scantron_selectfile'};
 8971:     if (! &valid_file($file)) {
 8972: 	$r->print('
 8973: 	<p>
 8974: 	    '.&mt('The requested filename was invalid.').'
 8975:         </p>
 8976: ');
 8977: 	$r->print(&show_grading_menu_form($symb));
 8978: 	return;
 8979:     }
 8980:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8981:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8982:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8983:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8984:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8985:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8986:     $r->print('
 8987:     <p>
 8988: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8989: 	      '<a href="'.$orig.'">','</a>').'
 8990:     </p>
 8991:     <p>
 8992: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8993: 	      '<a href="'.$corrected.'">','</a>').'
 8994:     </p>
 8995:     <p>
 8996: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8997: 	      '<a href="'.$skipped.'">','</a>').'
 8998:     </p>
 8999: ');
 9000:     $r->print(&show_grading_menu_form($symb));
 9001:     return '';
 9002: }
 9003: 
 9004: sub checkscantron_results {
 9005:     my ($r) = @_;
 9006:     my ($symb)=&get_symb($r);
 9007:     if (!$symb) {return '';}
 9008:     my $grading_menu_button=&show_grading_menu_form($symb);
 9009:     my $cid = $env{'request.course.id'};
 9010:     my %lettdig = &letter_to_digits();
 9011:     my $numletts = scalar(keys(%lettdig));
 9012:     my $cnum = $env{'course.'.$cid.'.num'};
 9013:     my $cdom = $env{'course.'.$cid.'.domain'};
 9014:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9015:     my %record;
 9016:     my %scantron_config =
 9017:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9018:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9019:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9020:     my $classlist=&Apache::loncoursedata::get_classlist();
 9021:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9022:     my $navmap=Apache::lonnavmaps::navmap->new();
 9023:     unless (ref($navmap)) {
 9024:         $r->print(&navmap_errormsg());
 9025:         return '';
 9026:     }
 9027:     my $map=$navmap->getResourceByUrl($sequence);
 9028:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9029:         %grader_randomlists_by_symb,%orderedforcode);
 9030:     if (ref($map)) {
 9031:         $randomorder=$map->randomorder();
 9032:         $randompick=$map->randompick();
 9033:     }
 9034:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9035:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9036:     if ($nav_error) {
 9037:         $r->print(&navmap_errormsg());
 9038:         return '';
 9039:     }
 9040:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9041:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9042:     my ($uname,$udom);
 9043:     my (%scandata,%lastname,%bylast);
 9044:     $r->print('
 9045: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9046: 
 9047:     my @delayqueue;
 9048:     my %completedstudents;
 9049: 
 9050:     my $count=&get_todo_count($scanlines,$scan_data);
 9051:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9052:     my ($username,$domain,$started,%ordered);
 9053:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9054:     if ($nav_error) {
 9055:         $r->print(&navmap_errormsg());
 9056:         return '';
 9057:     }
 9058: 
 9059:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9060:                                           'Processing first student');
 9061:     my $start=&Time::HiRes::time();
 9062:     my $i=-1;
 9063: 
 9064:     while ($i<$scanlines->{'count'}) {
 9065:         ($username,$domain,$uname)=('','','');
 9066:         $i++;
 9067:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9068:         if ($line=~/^[\s\cz]*$/) { next; }
 9069:         if ($started) {
 9070:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9071:                                                      'last student');
 9072:         }
 9073:         $started=1;
 9074:         my $scan_record=
 9075:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9076:                                                      $scan_data);
 9077:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9078:                                               \%idmap,$i)) {
 9079:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9080:                                 'Unable to find a student that matches',1);
 9081:             next;
 9082:         }
 9083:         if (exists $completedstudents{$uname}) {
 9084:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9085:                                 'Student '.$uname.' has multiple sheets',2);
 9086:             next;
 9087:         }
 9088:         my $pid = $scan_record->{'scantron.ID'};
 9089:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9090:         push(@{$bylast{$lastname{$pid}}},$pid);
 9091:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9092:         my $user = $uname.':'.$usec;
 9093:         ($username,$domain)=split(/:/,$uname);
 9094: 
 9095:         my $scancode;
 9096:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9097:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9098:             $scancode = $scan_record->{'scantron.CODE'};
 9099:         } else {
 9100:             $scancode = '';
 9101:         }
 9102: 
 9103:         my @mapresources = @resources;
 9104:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9105:         my %respnumlookup=();
 9106:         my %startline=();
 9107:         if ($randomorder || $randompick) {
 9108:             @mapresources =
 9109:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9110:                              \%orderedforcode);
 9111:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9112:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9113:                                              \%grader_partids_by_symb,\%orderedforcode,
 9114:                                              \%respnumlookup,\%startline);
 9115:             if ($randompick && $total) {
 9116:                 $lastpos = $total*$scantron_config{'Qlength'};
 9117:             }
 9118:         }
 9119:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9120:         chomp($scandata{$pid});
 9121:         $scandata{$pid} =~ s/\r$//;
 9122: 
 9123:         my $counter = -1;
 9124:         foreach my $resource (@mapresources) {
 9125:             my $parts;
 9126:             my $ressymb = $resource->symb();
 9127:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9128:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9129:                 (my $analysis,$parts) =
 9130:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9131:                                               $username,$domain,undef,
 9132:                                               $bubbles_per_row);
 9133:             } else {
 9134:                 $parts = $grader_partids_by_symb{$ressymb};
 9135:             }
 9136:             ($counter,my $recording) =
 9137:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9138:                                          $scandata{$pid},$parts,
 9139:                                          \%scantron_config,\%lettdig,$numletts,
 9140:                                          $randomorder,$randompick,
 9141:                                          \%respnumlookup,\%startline);
 9142:             $record{$pid} .= $recording;
 9143:         }
 9144:     }
 9145:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9146:     $r->print('<br />');
 9147:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9148:     $passed = 0;
 9149:     $failed = 0;
 9150:     $numstudents = 0;
 9151:     foreach my $last (sort(keys(%bylast))) {
 9152:         if (ref($bylast{$last}) eq 'ARRAY') {
 9153:             foreach my $pid (sort(@{$bylast{$last}})) {
 9154:                 my $showscandata = $scandata{$pid};
 9155:                 my $showrecord = $record{$pid};
 9156:                 $showscandata =~ s/\s/&nbsp;/g;
 9157:                 $showrecord =~ s/\s/&nbsp;/g;
 9158:                 if ($scandata{$pid} eq $record{$pid}) {
 9159:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9160:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9161: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9162: '</tr>'."\n".
 9163: '<tr class="'.$css_class.'">'."\n".
 9164: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 9165:                     $passed ++;
 9166:                 } else {
 9167:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9168:                     $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".
 9169: '</tr>'."\n".
 9170: '<tr class="'.$css_class.'">'."\n".
 9171: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9172: '</tr>'."\n";
 9173:                     $failed ++;
 9174:                 }
 9175:                 $numstudents ++;
 9176:             }
 9177:         }
 9178:     }
 9179:     $r->print('<p>'.
 9180:               &mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
 9181:                   '<b>',
 9182:                   $numstudents,
 9183:                   '</b>',
 9184:                   $env{'form.scantron_maxbubble'}).
 9185:               '</p>'
 9186:     );
 9187:     $r->print('<p>'
 9188:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9189:              .'<br />'
 9190:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9191:              .'</p>');
 9192:     if ($passed) {
 9193:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9194:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9195:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9196:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9197:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9198:                  $okstudents."\n".
 9199:                  &Apache::loncommon::end_data_table().'<br />');
 9200:     }
 9201:     if ($failed) {
 9202:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9203:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9204:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9205:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9206:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9207:                  $badstudents."\n".
 9208:                  &Apache::loncommon::end_data_table()).'<br />'.
 9209:                  &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.');  
 9210:     }
 9211:     $r->print('</form><br />'.$grading_menu_button);
 9212:     return;
 9213: }
 9214: 
 9215: sub verify_scantron_grading {
 9216:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9217:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9218:         $respnumlookup,$startline) = @_;
 9219:     my ($record,%expected,%startpos);
 9220:     return ($counter,$record) if (!ref($resource));
 9221:     return ($counter,$record) if (!$resource->is_problem());
 9222:     my $symb = $resource->symb();
 9223:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9224:     foreach my $part_id (@{$partids}) {
 9225:         $counter ++;
 9226:         $expected{$part_id} = 0;
 9227:         my $respnum = $counter;
 9228:         if ($randomorder || $randompick) {
 9229:             $respnum = $respnumlookup->{$counter};
 9230:             $startpos{$part_id} = $startline->{$counter} + 1;
 9231:         } else {
 9232:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9233:         }
 9234:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9235:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9236:             foreach my $item (@sub_lines) {
 9237:                 $expected{$part_id} += $item;
 9238:             }
 9239:         } else {
 9240:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9241:         }
 9242:     }
 9243:     if ($symb) {
 9244:         my %recorded;
 9245:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9246:         if ($returnhash{'version'}) {
 9247:             my %lasthash=();
 9248:             my $version;
 9249:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9250:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9251:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9252:                 }
 9253:             }
 9254:             foreach my $key (keys(%lasthash)) {
 9255:                 if ($key =~ /\.scantron$/) {
 9256:                     my $value = &unescape($lasthash{$key});
 9257:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9258:                     if ($value eq '') {
 9259:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9260:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9261:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9262:                             }
 9263:                         }
 9264:                     } else {
 9265:                         my @tocheck;
 9266:                         my @items = split(//,$value);
 9267:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9268:                             ($scantron_config->{'Qon'} eq 'number')) {
 9269:                             if (@items < $expected{$part_id}) {
 9270:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9271:                                 my @singles = split(//,$fragment);
 9272:                                 foreach my $pos (@singles) {
 9273:                                     if ($pos eq ' ') {
 9274:                                         push(@tocheck,$pos);
 9275:                                     } else {
 9276:                                         my $next = shift(@items);
 9277:                                         push(@tocheck,$next);
 9278:                                     }
 9279:                                 }
 9280:                             } else {
 9281:                                 @tocheck = @items;
 9282:                             }
 9283:                             foreach my $letter (@tocheck) {
 9284:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9285:                                     if ($letter !~ /^[A-J]$/) {
 9286:                                         $letter = $scantron_config->{'Qoff'};
 9287:                                     }
 9288:                                     $recorded{$part_id} .= $letter;
 9289:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9290:                                     my $digit;
 9291:                                     if ($letter !~ /^[A-J]$/) {
 9292:                                         $digit = $scantron_config->{'Qoff'};
 9293:                                     } else {
 9294:                                         $digit = $lettdig->{$letter};
 9295:                                     }
 9296:                                     $recorded{$part_id} .= $digit;
 9297:                                 }
 9298:                             }
 9299:                         } else {
 9300:                             @tocheck = @items;
 9301:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9302:                                 my $curr_sub = shift(@tocheck);
 9303:                                 my $digit;
 9304:                                 if ($curr_sub =~ /^[A-J]$/) {
 9305:                                     $digit = $lettdig->{$curr_sub}-1;
 9306:                                 }
 9307:                                 if ($curr_sub eq 'J') {
 9308:                                     $digit += scalar($numletts);
 9309:                                 }
 9310:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9311:                                     if ($j == $digit) {
 9312:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9313:                                     } else {
 9314:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9315:                                     }
 9316:                                 }
 9317:                             }
 9318:                         }
 9319:                     }
 9320:                 }
 9321:             }
 9322:         }
 9323:         foreach my $part_id (@{$partids}) {
 9324:             if ($recorded{$part_id} eq '') {
 9325:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9326:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9327:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9328:                     }
 9329:                 }
 9330:             }
 9331:             $record .= $recorded{$part_id};
 9332:         }
 9333:     }
 9334:     return ($counter,$record);
 9335: }
 9336: 
 9337: sub letter_to_digits {
 9338:     my %lettdig = (
 9339:                     A => 1,
 9340:                     B => 2,
 9341:                     C => 3,
 9342:                     D => 4,
 9343:                     E => 5,
 9344:                     F => 6,
 9345:                     G => 7,
 9346:                     H => 8,
 9347:                     I => 9,
 9348:                     J => 0,
 9349:                   );
 9350:     return %lettdig;
 9351: }
 9352: 
 9353: 
 9354: #-------- end of section for handling grading scantron forms -------
 9355: #
 9356: #-------------------------------------------------------------------
 9357: 
 9358: #-------------------------- Menu interface -------------------------
 9359: #
 9360: #--- Show a Grading Menu button - Calls the next routine ---
 9361: sub show_grading_menu_form {
 9362:     my ($symb)=@_;
 9363:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9364: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9365: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9366: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9367: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9368: 	'</form>'."\n";
 9369:     return $result;
 9370: }
 9371: 
 9372: # -- Retrieve choices for grading form
 9373: sub savedState {
 9374:     my %savedState = ();
 9375:     if ($env{'form.saveState'}) {
 9376: 	foreach (split(/:/,$env{'form.saveState'})) {
 9377: 	    my ($key,$value) = split(/=/,$_,2);
 9378: 	    $savedState{$key} = $value;
 9379: 	}
 9380:     }
 9381:     return \%savedState;
 9382: }
 9383: 
 9384: #--- Href with symb and command ---
 9385: 
 9386: sub href_symb_cmd {
 9387:     my ($symb,$cmd)=@_;
 9388:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9389: }
 9390: 
 9391: sub grading_menu {
 9392:     my ($request) = @_;
 9393:     my ($symb)=&get_symb($request);
 9394:     if (!$symb) {return '';}
 9395:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9396:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9397: 
 9398:     $request->print($table);
 9399:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9400:                   'handgrade'=>$hdgrade,
 9401:                   'probTitle'=>$probTitle,
 9402:                   'command'=>'submit_options',
 9403:                   'saveState'=>"",
 9404:                   'gradingMenu'=>1,
 9405:                   'showgrading'=>"yes");
 9406:     
 9407:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9408:     
 9409:     $fields{'command'} = 'csvform';
 9410:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9411:     
 9412:     $fields{'command'} = 'processclicker';
 9413:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9414:     
 9415:     $fields{'command'} = 'scantron_selectphase';
 9416:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9417:     
 9418:     my @menu = ({	categorytitle=>'Course Grading',
 9419:             items =>[
 9420:                         {	linktext => 'Manual Grading/View Submissions',
 9421:                     		url => $url1,
 9422:                     		permission => 'F',
 9423:                     		icon => 'edit-find-replace.png',
 9424:                     		linktitle => 'Start the process of hand grading submissions.'
 9425:                         },
 9426:                 	    {	linktext => 'Upload Scores',
 9427:                     		url => $url2,
 9428:                     		permission => 'F',
 9429:                     		icon => 'uploadscores.png',
 9430:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9431:                 	    },
 9432:                 	    {	linktext => 'Process Clicker',
 9433:                     		url => $url3,
 9434:                     		permission => 'F',
 9435:                     		icon => 'addClickerInfoFile.png',
 9436:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9437:                 	    },
 9438:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9439:                     		url => $url4,
 9440:                     		permission => 'F',
 9441:                     		icon => 'stat.png',
 9442:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9443:                 	    }
 9444:                     ]
 9445:             });
 9446: 
 9447:     #$fields{'command'} = 'verify';
 9448:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9449:     #
 9450:     # Create the menu
 9451:     my $Str;
 9452:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9453:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9454:     $Str .= '<input type="hidden" name="command" value="" />'.
 9455:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9456: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9457: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9458: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9459: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9460: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9461: 
 9462:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9463:     #$menudata->{'jscript'}
 9464:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9465:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9466:         ' /> '.
 9467:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9468:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9469: 
 9470:     $Str .="</form>\n";
 9471:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9472:     $request->print(<<GRADINGMENUJS);
 9473: <script type="text/javascript" language="javascript">
 9474:     function checkChoice(formname,val,cmdx) {
 9475: 	if (val <= 2) {
 9476: 	    var cmd = radioSelection(formname.radioChoice);
 9477: 	    var cmdsave = cmd;
 9478: 	} else {
 9479: 	    cmd = cmdx;
 9480: 	    cmdsave = 'submission';
 9481: 	}
 9482: 	formname.command.value = cmd;
 9483: 	if (val < 5) formname.submit();
 9484: 	if (val == 5) {
 9485: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9486: 	        return false;
 9487: 	    } else {
 9488: 	        formname.submit();
 9489: 	    }
 9490: 	}
 9491:     }
 9492: 
 9493:     function checkReceiptNo(formname,nospace) {
 9494: 	var receiptNo = formname.receipt.value;
 9495: 	var checkOpt = false;
 9496: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9497: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9498: 	if (checkOpt) {
 9499: 	    alert("$receiptalert");
 9500: 	    formname.receipt.value = "";
 9501: 	    formname.receipt.focus();
 9502: 	    return false;
 9503: 	}
 9504: 	return true;
 9505:     }
 9506: </script>
 9507: GRADINGMENUJS
 9508:     &commonJSfunctions($request);
 9509:     return $Str;    
 9510: }
 9511: 
 9512: 
 9513: #--- Displays the submissions first page -------
 9514: sub submit_options {
 9515:     my ($request) = @_;
 9516:     my ($symb)=&get_symb($request);
 9517:     if (!$symb) {return '';}
 9518:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9519: 
 9520:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9521:     $request->print(<<GRADINGMENUJS);
 9522: <script type="text/javascript" language="javascript">
 9523:     function checkChoice(formname,val,cmdx) {
 9524: 	if (val <= 2) {
 9525: 	    var cmd = radioSelection(formname.radioChoice);
 9526: 	    var cmdsave = cmd;
 9527: 	} else {
 9528: 	    cmd = cmdx;
 9529: 	    cmdsave = 'submission';
 9530: 	}
 9531: 	formname.command.value = cmd;
 9532: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9533: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9534: 	if (val < 5) formname.submit();
 9535: 	if (val == 5) {
 9536: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9537: 	    formname.submit();
 9538: 	}
 9539: 	if (val < 7) formname.submit();
 9540:     }
 9541: 
 9542:     function checkReceiptNo(formname,nospace) {
 9543: 	var receiptNo = formname.receipt.value;
 9544: 	var checkOpt = false;
 9545: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9546: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9547: 	if (checkOpt) {
 9548: 	    alert("$receiptalert");
 9549: 	    formname.receipt.value = "";
 9550: 	    formname.receipt.focus();
 9551: 	    return false;
 9552: 	}
 9553: 	return true;
 9554:     }
 9555: </script>
 9556: GRADINGMENUJS
 9557:     &commonJSfunctions($request);
 9558:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9559:     my $result;
 9560:     my (undef,$sections) = &getclasslist('all','0');
 9561:     my $savedState = &savedState();
 9562:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9563:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9564:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9565:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9566: 
 9567:     # Preselect sections
 9568:     my $selsec="";
 9569:     if (ref($sections)) {
 9570:         foreach my $section (sort(@$sections)) {
 9571:             $selsec.='<option value="'.$section.'" '.
 9572:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9573:         }
 9574:     }
 9575: 
 9576:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9577: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9578: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9579: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9580: 	'<input type="hidden" name="command"     value="" />'."\n".
 9581: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9582: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9583: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9584: 
 9585:     $result.='
 9586: <h2>
 9587:   '.&mt('Grade Current Resource').'
 9588: </h2>
 9589: <div>
 9590:   '.$table.'
 9591: </div>
 9592: 
 9593: <div class="LC_columnSection">
 9594:   
 9595:     <fieldset>
 9596:       <legend>
 9597:        '.&mt('Sections').'
 9598:       </legend>
 9599:       <select name="section" multiple="multiple" size="5">'."\n";
 9600:     $result.= $selsec;
 9601:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9602:     $result.='
 9603:     </fieldset>
 9604:   
 9605:     <fieldset>
 9606:       <legend>
 9607:         '.&mt('Groups').'
 9608:       </legend>
 9609:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9610:     </fieldset>
 9611:   
 9612:     <fieldset>
 9613:       <legend>
 9614:         '.&mt('Access Status').'
 9615:       </legend>
 9616:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9617:     </fieldset>
 9618:   
 9619:     <fieldset>
 9620:       <legend>
 9621:         '.&mt('Submission Status').'
 9622:       </legend>
 9623:       <select name="submitonly" size="5">
 9624: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9625: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9626: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9627: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9628:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9629:       </select>
 9630:     </fieldset>
 9631:   
 9632: </div>
 9633: 
 9634: <br />
 9635:           <div>
 9636:             <div>
 9637:               <label>
 9638:                 <input type="radio" name="radioChoice" value="submission" '.
 9639:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9640:              &mt('Select individual students to grade and view submissions.').'
 9641: 	      </label> 
 9642:             </div>
 9643:             <div>
 9644: 	      <label>
 9645:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9646:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 9647:                     &mt('Grade all selected students in a grading table.').'
 9648:               </label>
 9649:             </div>
 9650:             <div>
 9651: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9652:             </div>
 9653:           </div>
 9654: 
 9655: 
 9656:         <h2>
 9657:          '.&mt('Grade Complete Folder for One Student').'
 9658:         </h2>
 9659:         <div>
 9660:             <div>
 9661:               <label>
 9662:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 9663: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 9664:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 9665:               </label>
 9666:             </div>
 9667:             <div>
 9668: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9669:             </div>
 9670:         </div>
 9671:   </form>';
 9672:     $result .= &show_grading_menu_form($symb);
 9673:     return $result;
 9674: }
 9675: 
 9676: sub reset_perm {
 9677:     undef(%perm);
 9678: }
 9679: 
 9680: sub init_perm {
 9681:     &reset_perm();
 9682:     foreach my $test_perm ('vgr','mgr','opa') {
 9683: 
 9684: 	my $scope = $env{'request.course.id'};
 9685: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9686: 
 9687: 	    $scope .= '/'.$env{'request.course.sec'};
 9688: 	    if ( $perm{$test_perm}=
 9689: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9690: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9691: 	    } else {
 9692: 		delete($perm{$test_perm});
 9693: 	    }
 9694: 	}
 9695:     }
 9696: }
 9697: 
 9698: sub init_old_essays {
 9699:     my ($symb,$apath,$adom,$aname) = @_;
 9700:     if ($symb ne '') {
 9701:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9702:         if (keys(%essays) > 0) {
 9703:             $old_essays{$symb} = \%essays;
 9704:         }
 9705:     }
 9706:     return;
 9707: }
 9708: 
 9709: sub reset_old_essays {
 9710:     undef(%old_essays);
 9711: }
 9712: 
 9713: sub gather_clicker_ids {
 9714:     my %clicker_ids;
 9715: 
 9716:     my $classlist = &Apache::loncoursedata::get_classlist();
 9717: 
 9718:     # Set up a couple variables.
 9719:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9720:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9721:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9722: 
 9723:     foreach my $student (keys(%$classlist)) {
 9724:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9725:         my $username = $classlist->{$student}->[$username_idx];
 9726:         my $domain   = $classlist->{$student}->[$domain_idx];
 9727:         my $clickers =
 9728: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9729:         foreach my $id (split(/\,/,$clickers)) {
 9730:             $id=~s/^[\#0]+//;
 9731:             $id=~s/[\-\:]//g;
 9732:             if (exists($clicker_ids{$id})) {
 9733: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9734:             } else {
 9735: 		$clicker_ids{$id}=$username.':'.$domain;
 9736:             }
 9737:         }
 9738:     }
 9739:     return %clicker_ids;
 9740: }
 9741: 
 9742: sub gather_adv_clicker_ids {
 9743:     my %clicker_ids;
 9744:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9745:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9746:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9747:     foreach my $element (sort(keys(%coursepersonnel))) {
 9748:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9749:             my ($puname,$pudom)=split(/\:/,$person);
 9750:             my $clickers =
 9751: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9752:             foreach my $id (split(/\,/,$clickers)) {
 9753: 		$id=~s/^[\#0]+//;
 9754:                 $id=~s/[\-\:]//g;
 9755: 		if (exists($clicker_ids{$id})) {
 9756: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9757: 		} else {
 9758: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9759: 		}
 9760:             }
 9761:         }
 9762:     }
 9763:     return %clicker_ids;
 9764: }
 9765: 
 9766: sub clicker_grading_parameters {
 9767:     return ('gradingmechanism' => 'scalar',
 9768:             'upfiletype' => 'scalar',
 9769:             'specificid' => 'scalar',
 9770:             'pcorrect' => 'scalar',
 9771:             'pincorrect' => 'scalar');
 9772: }
 9773: 
 9774: sub process_clicker {
 9775:     my ($r)=@_;
 9776:     my ($symb)=&get_symb($r);
 9777:     if (!$symb) {return '';}
 9778:     my $result=&checkforfile_js();
 9779:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 9780:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 9781:     $result.=$table;
 9782:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 9783:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 9784:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 9785:         '</b></td></tr>'."\n";
 9786:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 9787: # Attempt to restore parameters from last session, set defaults if not present
 9788:     my %Saveable_Parameters=&clicker_grading_parameters();
 9789:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9790:                                                  \%Saveable_Parameters);
 9791:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9792:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9793:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9794:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9795: 
 9796:     my %checked;
 9797:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9798:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9799:           $checked{$gradingmechanism}=' checked="checked"';
 9800:        }
 9801:     }
 9802: 
 9803:     my $upload=&mt("Upload File");
 9804:     my $type=&mt("Type");
 9805:     my $attendance=&mt("Award points just for participation");
 9806:     my $personnel=&mt("Correctness determined from response by course personnel");
 9807:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9808:     my $given=&mt("Correctness determined from given list of answers").' '.
 9809:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9810:     my $pcorrect=&mt("Percentage points for correct solution");
 9811:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9812:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9813:                                                    {'iclicker' => 'i>clicker',
 9814:                                                     'interwrite' => 'interwrite PRS',
 9815:                                                     'turning' => 'Turning Technologies'});
 9816:     $symb = &Apache::lonenc::check_encrypt($symb);
 9817:     $result.=<<ENDUPFORM;
 9818: <script type="text/javascript">
 9819: function sanitycheck() {
 9820: // Accept only integer percentages
 9821:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9822:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9823: // Find out grading choice
 9824:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9825:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9826:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9827:       }
 9828:    }
 9829: // By default, new choice equals user selection
 9830:    newgradingchoice=gradingchoice;
 9831: // Not good to give more points for false answers than correct ones
 9832:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9833:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9834:    }
 9835: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9836:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9837:       document.forms.gradesupload.pcorrect.value=100;
 9838:       document.forms.gradesupload.pincorrect.value=100;
 9839:    }
 9840: // If the values are different, cannot be attendance only
 9841:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9842:        (gradingchoice=='attendance')) {
 9843:        newgradingchoice='personnel';
 9844:    }
 9845: // Change grading choice to new one
 9846:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9847:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9848:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9849:       } else {
 9850:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9851:       }
 9852:    }
 9853: // Remember the old state
 9854:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9855: }
 9856: </script>
 9857: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9858: <input type="hidden" name="symb" value="$symb" />
 9859: <input type="hidden" name="command" value="processclickerfile" />
 9860: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9861: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9862: <input type="file" name="upfile" size="50" />
 9863: <br /><label>$type: $selectform</label>
 9864: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9865: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9866: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9867: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9868: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9869: <br />&nbsp;&nbsp;&nbsp;
 9870: <input type="text" name="givenanswer" size="50" />
 9871: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9872: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9873: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9874: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9875: </form>
 9876: ENDUPFORM
 9877:     $result.='</td></tr></table>'."\n".
 9878:              '</td></tr></table><br /><br />'."\n";
 9879:     $result.=&show_grading_menu_form($symb);
 9880:     return $result;
 9881: }
 9882: 
 9883: sub process_clicker_file {
 9884:     my ($r)=@_;
 9885:     my ($symb)=&get_symb($r);
 9886:     if (!$symb) {return '';}
 9887: 
 9888:     my %Saveable_Parameters=&clicker_grading_parameters();
 9889:     &Apache::loncommon::store_course_settings('grades_clicker',
 9890:                                               \%Saveable_Parameters);
 9891: 
 9892:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9893:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9894: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9895: 	return $result.&show_grading_menu_form($symb);
 9896:     }
 9897:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9898:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9899:         return $result.&show_grading_menu_form($symb);
 9900:     }
 9901:     my $foundgiven=0;
 9902:     if ($env{'form.gradingmechanism'} eq 'given') {
 9903:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9904:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9905:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9906:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9907:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9908:         $foundgiven=$#answers+1;
 9909:     }
 9910:     my %clicker_ids=&gather_clicker_ids();
 9911:     my %correct_ids;
 9912:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9913: 	%correct_ids=&gather_adv_clicker_ids();
 9914:     }
 9915:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9916: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9917: 	   $correct_id=~tr/a-z/A-Z/;
 9918: 	   $correct_id=~s/\s//gs;
 9919: 	   $correct_id=~s/^[\#0]+//;
 9920:            $correct_id=~s/[\-\:]//g;
 9921:            if ($correct_id) {
 9922: 	      $correct_ids{$correct_id}='specified';
 9923:            }
 9924:         }
 9925:     }
 9926:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9927: 	$result.=&mt('Score based on attendance only');
 9928:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9929:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9930:     } else {
 9931: 	my $number=0;
 9932: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9933: 	foreach my $id (sort(keys(%correct_ids))) {
 9934: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9935: 	    if ($correct_ids{$id} eq 'specified') {
 9936: 		$result.=&mt('specified');
 9937: 	    } else {
 9938: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9939: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9940: 	    }
 9941: 	    $number++;
 9942: 	}
 9943:         $result.="</p>\n";
 9944: 	if ($number==0) {
 9945: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9946: 	    return $result.&show_grading_menu_form($symb);
 9947: 	}
 9948:     }
 9949:     if (length($env{'form.upfile'}) < 2) {
 9950:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9951: 		     '<span class="LC_error">',
 9952: 		     '</span>',
 9953: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9954:         return $result.&show_grading_menu_form($symb);
 9955:     }
 9956: 
 9957: # Were able to get all the info needed, now analyze the file
 9958: 
 9959:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9960:     $symb = &Apache::lonenc::check_encrypt($symb);
 9961:     my $heading=&mt('Scanning clicker file');
 9962:     $result.=(<<ENDHEADER);
 9963: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9964: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9965: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
 9966: <form method="post" action="/adm/grades" name="clickeranalysis">
 9967: <input type="hidden" name="symb" value="$symb" />
 9968: <input type="hidden" name="command" value="assignclickergrades" />
 9969: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9970: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9971: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9972: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9973: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9974: ENDHEADER
 9975:     if ($env{'form.gradingmechanism'} eq 'given') {
 9976:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9977:     } 
 9978:     my %responses;
 9979:     my @questiontitles;
 9980:     my $errormsg='';
 9981:     my $number=0;
 9982:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9983: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9984:     }
 9985:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9986:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9987:     }
 9988:     if ($env{'form.upfiletype'} eq 'turning') {
 9989:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9990:     }
 9991:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9992:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9993:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9994:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9995:              '<br />';
 9996:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9997:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9998:        return $result.&show_grading_menu_form($symb);
 9999:     } 
10000: # Remember Question Titles
10001: # FIXME: Possibly need delimiter other than ":"
10002:     for (my $i=0;$i<$number;$i++) {
10003:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10004:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10005:     }
10006:     my $correct_count=0;
10007:     my $student_count=0;
10008:     my $unknown_count=0;
10009: # Match answers with usernames
10010: # FIXME: Possibly need delimiter other than ":"
10011:     foreach my $id (keys(%responses)) {
10012:        if ($correct_ids{$id}) {
10013:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10014:           $correct_count++;
10015:        } elsif ($clicker_ids{$id}) {
10016:           if ($clicker_ids{$id}=~/\,/) {
10017: # More than one user with the same clicker!
10018:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10019:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10020:                            "<select name='multi".$id."'>";
10021:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10022:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10023:              }
10024:              $result.='</select>';
10025:              $unknown_count++;
10026:           } else {
10027: # Good: found one and only one user with the right clicker
10028:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10029:              $student_count++;
10030:           }
10031:        } else {
10032:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10033:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10034:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10035:                    "\n".&mt("Domain").": ".
10036:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10037:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10038:           $unknown_count++;
10039:        }
10040:     }
10041:     $result.='<hr />'.
10042:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10043:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10044:        if ($correct_count==0) {
10045:           $errormsg.="Found no correct answers for grading!";
10046:        } elsif ($correct_count>1) {
10047:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10048:        }
10049:     }
10050:     if ($number<1) {
10051:        $errormsg.="Found no questions.";
10052:     }
10053:     if ($errormsg) {
10054:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10055:     } else {
10056:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10057:     }
10058:     $result.='</form></td></tr></table>'."\n".
10059:              '</td></tr></table><br /><br />'."\n";
10060:     return $result.&show_grading_menu_form($symb);
10061: }
10062: 
10063: sub iclicker_eval {
10064:     my ($questiontitles,$responses)=@_;
10065:     my $number=0;
10066:     my $errormsg='';
10067:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10068:         my %components=&Apache::loncommon::record_sep($line);
10069:         my @entries=map {$components{$_}} (sort(keys(%components)));
10070: 	if ($entries[0] eq 'Question') {
10071: 	    for (my $i=3;$i<$#entries;$i+=6) {
10072: 		$$questiontitles[$number]=$entries[$i];
10073: 		$number++;
10074: 	    }
10075: 	}
10076: 	if ($entries[0]=~/^\#/) {
10077: 	    my $id=$entries[0];
10078: 	    my @idresponses;
10079: 	    $id=~s/^[\#0]+//;
10080: 	    for (my $i=0;$i<$number;$i++) {
10081: 		my $idx=3+$i*6;
10082:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10083: 		push(@idresponses,$entries[$idx]);
10084: 	    }
10085: 	    $$responses{$id}=join(',',@idresponses);
10086: 	}
10087:     }
10088:     return ($errormsg,$number);
10089: }
10090: 
10091: sub interwrite_eval {
10092:     my ($questiontitles,$responses)=@_;
10093:     my $number=0;
10094:     my $errormsg='';
10095:     my $skipline=1;
10096:     my $questionnumber=0;
10097:     my %idresponses=();
10098:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10099:         my %components=&Apache::loncommon::record_sep($line);
10100:         my @entries=map {$components{$_}} (sort(keys(%components)));
10101:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10102:         if ($entries[1] eq 'Response') { $skipline=1; }
10103:         next if $skipline;
10104:         if ($entries[0]!=$questionnumber) {
10105:            $questionnumber=$entries[0];
10106:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10107:            $number++;
10108:         }
10109:         my $id=$entries[4];
10110:         $id=~s/^[\#0]+//;
10111:         $id=~s/^v\d*\://i;
10112:         $id=~s/[\-\:]//g;
10113:         $idresponses{$id}[$number]=$entries[6];
10114:     }
10115:     foreach my $id (keys(%idresponses)) {
10116:        $$responses{$id}=join(',',@{$idresponses{$id}});
10117:        $$responses{$id}=~s/^\s*\,//;
10118:     }
10119:     return ($errormsg,$number);
10120: }
10121: 
10122: sub turning_eval {
10123:     my ($questiontitles,$responses)=@_;
10124:     my $number=0;
10125:     my $errormsg='';
10126:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10127:         my %components=&Apache::loncommon::record_sep($line);
10128:         my @entries=map {$components{$_}} (sort(keys(%components)));
10129:         if ($#entries>$number) { $number=$#entries; }
10130:         my $id=$entries[0];
10131:         my @idresponses;
10132:         $id=~s/^[\#0]+//;
10133:         unless ($id) { next; }
10134:         for (my $idx=1;$idx<=$#entries;$idx++) {
10135:             $entries[$idx]=~s/\,/\;/g;
10136:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10137:             push(@idresponses,$entries[$idx]);
10138:         }
10139:         $$responses{$id}=join(',',@idresponses);
10140:     }
10141:     for (my $i=1; $i<=$number; $i++) {
10142:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10143:     }
10144:     return ($errormsg,$number);
10145: }
10146: 
10147: sub assign_clicker_grades {
10148:     my ($r)=@_;
10149:     my ($symb)=&get_symb($r);
10150:     if (!$symb) {return '';}
10151: # See which part we are saving to
10152:     my $res_error;
10153:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10154:     if ($res_error) {
10155:         return &navmap_errormsg();
10156:     }
10157: # FIXME: This should probably look for the first handgradeable part
10158:     my $part=$$partlist[0];
10159: # Start screen output
10160:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10161: 
10162:     $result .= '<br />'.
10163:                &Apache::loncommon::start_data_table().
10164:                &Apache::loncommon::start_data_table_header_row().
10165:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10166:                &Apache::loncommon::end_data_table_header_row().
10167:                &Apache::loncommon::start_data_table_row().'<td>';
10168: 
10169: # Get correct result
10170: # FIXME: Possibly need delimiter other than ":"
10171:     my @correct=();
10172:     my $gradingmechanism=$env{'form.gradingmechanism'};
10173:     my $number=$env{'form.number'};
10174:     if ($gradingmechanism ne 'attendance') {
10175:        foreach my $key (keys(%env)) {
10176:           if ($key=~/^form\.correct\:/) {
10177:              my @input=split(/\,/,$env{$key});
10178:              for (my $i=0;$i<=$#input;$i++) {
10179:                  if (($correct[$i]) && ($input[$i]) &&
10180:                      ($correct[$i] ne $input[$i])) {
10181:                     $result.='<br /><span class="LC_warning">'.
10182:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10183:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10184:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10185:                     $correct[$i]=$input[$i];
10186:                  }
10187:              }
10188:           }
10189:        }
10190:        for (my $i=0;$i<$number;$i++) {
10191:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10192:              $result.='<br /><span class="LC_error">'.
10193:                       &mt('No correct result given for question "[_1]"!',
10194:                           $env{'form.question:'.$i}).'</span>';
10195:           }
10196:        }
10197:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10198:     }
10199: # Start grading
10200:     my $pcorrect=$env{'form.pcorrect'};
10201:     my $pincorrect=$env{'form.pincorrect'};
10202:     my $storecount=0;
10203:     my %users=();
10204:     foreach my $key (keys(%env)) {
10205:        my $user='';
10206:        if ($key=~/^form\.student\:(.*)$/) {
10207:           $user=$1;
10208:        }
10209:        if ($key=~/^form\.unknown\:(.*)$/) {
10210:           my $id=$1;
10211:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10212:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10213:           } elsif ($env{'form.multi'.$id}) {
10214:              $user=$env{'form.multi'.$id};
10215:           }
10216:        }
10217:        if ($user) {
10218:           if ($users{$user}) {
10219:              $result.='<br /><span class="LC_warning">'.
10220:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10221:                       '</span><br />';
10222:           }
10223:           $users{$user}=1;
10224:           my @answer=split(/\,/,$env{$key});
10225:           my $sum=0;
10226:           my $realnumber=$number;
10227:           for (my $i=0;$i<$number;$i++) {
10228:              if  ($correct[$i] eq '-') {
10229:                 $realnumber--;
10230:              } elsif ($answer[$i]) {
10231:                 if ($gradingmechanism eq 'attendance') {
10232:                    $sum+=$pcorrect;
10233:                 } elsif ($correct[$i] eq '*') {
10234:                    $sum+=$pcorrect;
10235:                 } else {
10236: # We actually grade if correct or not
10237:                    my $increment=$pincorrect;
10238: # Special case: numerical answer "0"
10239:                    if ($correct[$i] eq '0') {
10240:                       if ($answer[$i]=~/^[0\.]+$/) {
10241:                          $increment=$pcorrect;
10242:                       }
10243: # General numerical answer, both evaluate to something non-zero
10244:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10245:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10246:                          $increment=$pcorrect;
10247:                       }
10248: # Must be just alphanumeric
10249:                    } elsif ($answer[$i] eq $correct[$i]) {
10250:                       $increment=$pcorrect;
10251:                    }
10252:                    $sum+=$increment;
10253:                 }
10254:              }
10255:           }
10256:           my $ave=$sum/(100*$realnumber);
10257: # Store
10258:           my ($username,$domain)=split(/\:/,$user);
10259:           my %grades=();
10260:           $grades{"resource.$part.solved"}='correct_by_override';
10261:           $grades{"resource.$part.awarded"}=$ave;
10262:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10263:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10264:                                                  $env{'request.course.id'},
10265:                                                  $domain,$username);
10266:           if ($returncode ne 'ok') {
10267:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10268:           } else {
10269:              $storecount++;
10270:           }
10271:        }
10272:     }
10273: # We are done
10274:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10275:              '</td>'.
10276:              &Apache::loncommon::end_data_table_row().
10277:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10278:     return $result.&show_grading_menu_form($symb);
10279: }
10280: 
10281: sub navmap_errormsg {
10282:     return '<div class="LC_error">'.
10283:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10284:            &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>').
10285:            '</div>';
10286: }
10287: 
10288: sub startpage {
10289:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10290:     if ($nomenu) {
10291:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10292:     } else {
10293:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10294:                                                  {'bread_crumbs' => $crumbs}));
10295:     }
10296:     unless ($nodisplayflag) {
10297:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10298:     }
10299: }
10300: 
10301: sub handler {
10302:     my $request=$_[0];
10303:     &reset_caches();
10304:     if ($request->header_only) {
10305:         &Apache::loncommon::content_type($request,'text/html');
10306:         $request->send_http_header;
10307:         return OK;
10308:     }
10309:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10310: 
10311:     my $symb=&get_symb($request,1);
10312:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10313:     my $command=$commands[0];
10314: 
10315:     if ($#commands > 0) {
10316: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10317:     }
10318: 
10319:     $ssi_error = 0;
10320:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10321:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10322:                                                     {'bread_crumbs' => $brcrum});
10323:     if ($symb eq '' && $command eq '') {
10324: 	if ($env{'user.adv'}) {
10325:             &Apache::loncommon::content_type($request,'text/html');
10326:             $request->send_http_header;
10327:             $request->print($start_page);
10328: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10329: 		($env{'form.codethree'})) {
10330: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10331: 		    $env{'form.codethree'};
10332: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10333: 		    &Apache::lonnet::checkin($token);
10334: 		if ($tsymb) {
10335: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10336: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10337: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10338: 					  ('grade_username' => $tuname,
10339: 					   'grade_domain' => $tudom,
10340: 					   'grade_courseid' => $tcrsid,
10341: 					   'grade_symb' => $tsymb)));
10342: 		    } else {
10343: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10344: 		    }
10345: 		} else {
10346: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10347: 		}
10348: 	    } else {
10349: 		$request->print(&Apache::lonxml::tokeninputfield());
10350: 	    }
10351:         } elsif ($env{'request.course.id'}) {
10352:             &init_perm(); 
10353:             if (!%perm) {
10354:                 $request->internal_redirect('/adm/quickgrades');
10355:                 return OK;
10356:             } else {
10357:                 &Apache::loncommon::content_type($request,'text/html');
10358:                 $request->send_http_header;
10359:                 $request->print($start_page);
10360:             }
10361:         }
10362:     } else {
10363:         &init_perm();
10364:         if (!$env{'request.course.id'}) {
10365:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10366:                     ($command =~ /^scantronupload/)) {
10367:                 # Not in a course.
10368:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10369:                 return HTTP_NOT_ACCEPTABLE;
10370:             }
10371:         } elsif (!%perm) {
10372:             $request->internal_redirect('/adm/quickgrades');
10373:         }
10374:         &Apache::loncommon::content_type($request,'text/html');
10375:         $request->send_http_header;
10376:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10377:             $request->print($start_page); 
10378:         }
10379: 	if ($command eq 'submission' && $perm{'vgr'}) {
10380:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10381:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10382:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10383:                     &choose_task_version_form($symb,$env{'form.student'},
10384:                                               $env{'form.userdom'});
10385:             }
10386:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10387:             if ($versionform) {
10388:                 $request->print($versionform);
10389:             }
10390:             $request->print('<br clear="all" />');
10391: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10392:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10393:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10394:                 &choose_task_version_form($symb,$env{'form.student'},
10395:                                           $env{'form.userdom'},
10396:                                           $env{'form.inhibitmenu'});
10397:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10398:             if ($versionform) {
10399:                 $request->print($versionform);
10400:             }
10401:             $request->print('<br clear="all" />');
10402:             $request->print(&show_previous_task_version($request,$symb));
10403: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10404: 	    &pickStudentPage($request);
10405: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10406: 	    &displayPage($request);
10407: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10408: 	    &updateGradeByPage($request);
10409: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10410: 	    &processGroup($request);
10411: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10412: 	    $request->print(&grading_menu($request));
10413: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10414: 	    $request->print(&submit_options($request));
10415: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10416: 	    $request->print(&viewgrades($request));
10417: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10418: 	    $request->print(&processHandGrade($request));
10419: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10420: 	    $request->print(&editgrades($request));
10421: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10422: 	    $request->print(&verifyreceipt($request));
10423:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10424:             $request->print(&process_clicker($request));
10425:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10426:             $request->print(&process_clicker_file($request));
10427:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10428:             $request->print(&assign_clicker_grades($request));
10429: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10430: 	    $request->print(&upcsvScores_form($request));
10431: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10432: 	    $request->print(&csvupload($request));
10433: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10434: 	    $request->print(&csvuploadmap($request));
10435: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10436: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10437: 		$request->print(&csvuploadoptions($request));
10438: 	    } else {
10439: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10440: 		    $env{'form.upfile_associate'} = 'reverse';
10441: 		} else {
10442: 		    $env{'form.upfile_associate'} = 'forward';
10443: 		}
10444: 		$request->print(&csvuploadmap($request));
10445: 	    }
10446: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10447: 	    $request->print(&csvuploadassign($request));
10448: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10449: 	    $request->print(&scantron_selectphase($request));
10450:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10451:  	    $request->print(&scantron_do_warning($request));
10452: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10453: 	    $request->print(&scantron_validate_file($request));
10454: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10455: 	    $request->print(&scantron_process_students($request));
10456:  	} elsif ($command eq 'scantronupload' && 
10457:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10458: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10459:  	    $request->print(&scantron_upload_scantron_data($request)); 
10460:  	} elsif ($command eq 'scantronupload_save' &&
10461:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10462: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10463:  	    $request->print(&scantron_upload_scantron_data_save($request));
10464:  	} elsif ($command eq 'scantron_download' &&
10465: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10466:  	    $request->print(&scantron_download_scantron_data($request));
10467:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10468:             $request->print(&checkscantron_results($request));     
10469: 	} elsif ($command) {
10470: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10471: 	}
10472:     }
10473:     if ($ssi_error) {
10474: 	&ssi_print_error($request);
10475:     }
10476:     $request->print(&Apache::loncommon::end_page());
10477:     &reset_caches();
10478:     return OK;
10479: }
10480: 
10481: 1;
10482: 
10483: __END__;
10484: 
10485: 
10486: =head1 NAME
10487: 
10488: Apache::grades
10489: 
10490: =head1 SYNOPSIS
10491: 
10492: Handles the viewing of grades.
10493: 
10494: This is part of the LearningOnline Network with CAPA project
10495: described at http://www.lon-capa.org.
10496: 
10497: =head1 OVERVIEW
10498: 
10499: Do an ssi with retries:
10500: While I'd love to factor out this with the vesrion in lonprintout,
10501: 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
10502: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10503: 
10504: At least the logic that drives this has been pulled out into loncommon.
10505: 
10506: 
10507: 
10508: ssi_with_retries - Does the server side include of a resource.
10509:                      if the ssi call returns an error we'll retry it up to
10510:                      the number of times requested by the caller.
10511:                      If we still have a proble, no text is appended to the
10512:                      output and we set some global variables.
10513:                      to indicate to the caller an SSI error occurred.  
10514:                      All of this is supposed to deal with the issues described
10515:                      in LonCAPA BZ 5631 see:
10516:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10517:                      by informing the user that this happened.
10518: 
10519: Parameters:
10520:   resource   - The resource to include.  This is passed directly, without
10521:                interpretation to lonnet::ssi.
10522:   form       - The form hash parameters that guide the interpretation of the resource
10523:                
10524:   retries    - Number of retries allowed before giving up completely.
10525: Returns:
10526:   On success, returns the rendered resource identified by the resource parameter.
10527: Side Effects:
10528:   The following global variables can be set:
10529:    ssi_error                - If an unrecoverable error occurred this becomes true.
10530:                               It is up to the caller to initialize this to false
10531:                               if desired.
10532:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10533:                               of the resource that could not be rendered by the ssi
10534:                               call.
10535:    ssi_error_message   - The error string fetched from the ssi response
10536:                               in the event of an error.
10537: 
10538: 
10539: =head1 HANDLER SUBROUTINE
10540: 
10541: ssi_with_retries()
10542: 
10543: =head1 SUBROUTINES
10544: 
10545: =over
10546: 
10547: =item scantron_get_correction() : 
10548: 
10549:    Builds the interface screen to interact with the operator to fix a
10550:    specific error condition in a specific scanline
10551: 
10552:  Arguments:
10553:     $r           - Apache request object
10554:     $i           - number of the current scanline
10555:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10556:     $scan_config - hash ref as returned from &get_scantron_config()
10557:     $line        - full contents of the current scanline
10558:     $error       - error condition, valid values are
10559:                    'incorrectCODE', 'duplicateCODE',
10560:                    'doublebubble', 'missingbubble',
10561:                    'duplicateID', 'incorrectID'
10562:     $arg         - extra information needed
10563:        For errors:
10564:          - duplicateID   - paper number that this studentID was seen before on
10565:          - duplicateCODE - array ref of the paper numbers this CODE was
10566:                            seen on before
10567:          - incorrectCODE - current incorrect CODE 
10568:          - doublebubble  - array ref of the bubble lines that have double
10569:                            bubble errors
10570:          - missingbubble - array ref of the bubble lines that have missing
10571:                            bubble errors
10572: 
10573:    $randomorder - True if exam folder has randomorder set
10574:    $randompick  - True if exam folder has randompick set
10575:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10576:                      for current line to question number used for same question
10577:                      in "Master Seqence" (as seen by Course Coordinator).
10578:    $startline   - Reference to hash where key is question number (0 is first)
10579:                   and value is number of first bubble line for current student
10580:                   or code-based randompick and/or randomorder.
10581: 
10582: 
10583: =item  scantron_get_maxbubble() : 
10584: 
10585:    Arguments:
10586:        $nav_error  - Reference to scalar which is a flag to indicate a
10587:                       failure to retrieve a navmap object.
10588:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10589:        calling routine should trap the error condition and display the warning
10590:        found in &navmap_errormsg().
10591: 
10592:        $scantron_config - Reference to bubblesheet format configuration hash.
10593: 
10594:    Returns the maximum number of bubble lines that are expected to
10595:    occur. Does this by walking the selected sequence rendering the
10596:    resource and then checking &Apache::lonxml::get_problem_counter()
10597:    for what the current value of the problem counter is.
10598: 
10599:    Caches the results to $env{'form.scantron_maxbubble'},
10600:    $env{'form.scantron.bubble_lines.n'}, 
10601:    $env{'form.scantron.first_bubble_line.n'} and
10602:    $env{"form.scantron.sub_bubblelines.n"}
10603:    which are the total number of bubble lines, the number of bubble
10604:    lines for response n and number of the first bubble line for response n,
10605:    and a comma separated list of numbers of bubble lines for sub-questions
10606:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10607: 
10608: 
10609: =item  scantron_validate_missingbubbles() : 
10610: 
10611:    Validates all scanlines in the selected file to not have any
10612:     answers that don't have bubbles that have not been verified
10613:     to be bubble free.
10614: 
10615: =item  scantron_process_students() : 
10616: 
10617:    Routine that does the actual grading of the bubblesheet information.
10618: 
10619:    The parsed scanline hash is added to %env 
10620: 
10621:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10622:    foreach resource , with the form data of
10623: 
10624: 	'submitted'     =>'scantron' 
10625: 	'grade_target'  =>'grade',
10626: 	'grade_username'=> username of student
10627: 	'grade_domain'  => domain of student
10628: 	'grade_courseid'=> of course
10629: 	'grade_symb'    => symb of resource to grade
10630: 
10631:     This triggers a grading pass. The problem grading code takes care
10632:     of converting the bubbled letter information (now in %env) into a
10633:     valid submission.
10634: 
10635: =item  scantron_upload_scantron_data() :
10636: 
10637:     Creates the screen for adding a new bubblesheet data file to a course.
10638: 
10639: =item  scantron_upload_scantron_data_save() : 
10640: 
10641:    Adds a provided bubble information data file to the course if user
10642:    has the correct privileges to do so. 
10643: 
10644: =item  valid_file() :
10645: 
10646:    Validates that the requested bubble data file exists in the course.
10647: 
10648: =item  scantron_download_scantron_data() : 
10649: 
10650:    Shows a list of the three internal files (original, corrected,
10651:    skipped) for a specific bubblesheet data file that exists in the
10652:    course.
10653: 
10654: =item  scantron_validate_ID() : 
10655: 
10656:    Validates all scanlines in the selected file to not have any
10657:    invalid or underspecified student/employee IDs
10658: 
10659: =item navmap_errormsg() :
10660: 
10661:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10662:    Should be called whenever the request to instantiate a navmap object fails.  
10663: 
10664: =back
10665: 
10666: =cut

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