File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.30: download - view: text, annotated - select for diffs
Mon Aug 25 22:17:54 2014 UTC (9 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.724, 1.725

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.30 2014/08/25 22:17: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 @answer = %answer;
  395:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  396: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  397: 	my ($toprow,$bottomrow);
  398: 	foreach my $foil (@$order) {
  399: 	    if ($grading{$foil} == 1) {
  400: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  401: 	    } else {
  402: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  403: 	    }
  404: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  405: 	}
  406: 	return '<blockquote><table border="1">'.
  407: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  408: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  409: 	    $bottomrow.'</tr></table></blockquote>';
  410:     } elsif ($response eq 'match') {
  411: 	my %answer=&Apache::lonnet::str2hash($answer);
  412:         my @answer = %answer;
  413:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  414: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  415: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  416: 	my ($toprow,$middlerow,$bottomrow);
  417: 	foreach my $foil (@$order) {
  418: 	    my $item=shift(@items);
  419: 	    if ($grading{$foil} == 1) {
  420: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  421: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  422: 	    } else {
  423: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  424: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  425: 	    }
  426: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  427: 	}
  428: 	return '<blockquote><table border="1">'.
  429: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  430: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  431: 	    $middlerow.'</tr>'.
  432: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  433: 	    $bottomrow.'</tr></table></blockquote>';
  434:     } elsif ($response eq 'radiobutton') {
  435: 	my %answer=&Apache::lonnet::str2hash($answer);
  436: 	my ($toprow,$bottomrow);
  437: 	my $correct = 
  438: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  439: 	foreach my $foil (@$order) {
  440: 	    if (exists($answer{$foil})) {
  441: 		if ($foil eq $correct) {
  442: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  443: 		} else {
  444: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  445: 		}
  446: 	    } else {
  447: 		$toprow.='<td>'.&mt('false').'</td>';
  448: 	    }
  449: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  450: 	}
  451: 	return '<blockquote><table border="1">'.
  452: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  453: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  454: 	    $bottomrow.'</tr></table></blockquote>';
  455:     } elsif ($response eq 'essay') {
  456: 	if (! exists ($env{'form.'.$symb})) {
  457: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  458: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  459: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  460: 
  461: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  462: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  463: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  464: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  465: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  466: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  467: 	}
  468: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight(&HTML::Entities::encode($answer, '"<>&')).'</tt></blockquote>';
  469:     } elsif ( $response eq 'organic') {
  470:         my $result=&mt('Smile representation: [_1]',
  471:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  472: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  473: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  474: 	return $result;
  475:     } elsif ( $response eq 'Task') {
  476: 	if ( $answer eq 'SUBMITTED') {
  477: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  478: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  479: 	    return $result;
  480: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  481: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  482: 			       keys(%{$record}));
  483: 	    return join('<br />',($version,@matches));
  484: 			       
  485: 			       
  486: 	} else {
  487: 	    my $result =
  488: 		'<p>'
  489: 		.&mt('Overall result: [_1]',
  490: 		     $record->{$version."resource.$respid.$partid.status"})
  491: 		.'</p>';
  492: 	    
  493: 	    $result .= '<ul>';
  494: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  495: 			     keys(%{$record}));
  496: 	    foreach my $grade (sort(@grade)) {
  497: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  498: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  499: 				     $dim, $record->{$grade}).
  500: 			  '</li>';
  501: 	    }
  502: 	    $result.='</ul>';
  503: 	    return $result;
  504: 	}
  505:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  506:         # Respect multiple input fields, see Bug #5409 
  507: 	$answer = 
  508: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  509: 							      $answer);
  510:         return $answer;
  511:     }
  512:     return &HTML::Entities::encode($answer, '"<>&');
  513: }
  514: 
  515: #-- A couple of common js functions
  516: sub commonJSfunctions {
  517:     my $request = shift;
  518:     $request->print(<<COMMONJSFUNCTIONS);
  519: <script type="text/javascript" language="javascript">
  520:     function radioSelection(radioButton) {
  521: 	var selection=null;
  522: 	if (radioButton.length > 1) {
  523: 	    for (var i=0; i<radioButton.length; i++) {
  524: 		if (radioButton[i].checked) {
  525: 		    return radioButton[i].value;
  526: 		}
  527: 	    }
  528: 	} else {
  529: 	    if (radioButton.checked) return radioButton.value;
  530: 	}
  531: 	return selection;
  532:     }
  533: 
  534:     function pullDownSelection(selectOne) {
  535: 	var selection="";
  536: 	if (selectOne.length > 1) {
  537: 	    for (var i=0; i<selectOne.length; i++) {
  538: 		if (selectOne[i].selected) {
  539: 		    return selectOne[i].value;
  540: 		}
  541: 	    }
  542: 	} else {
  543:             // only one value it must be the selected one
  544: 	    return selectOne.value;
  545: 	}
  546:     }
  547: </script>
  548: COMMONJSFUNCTIONS
  549: }
  550: 
  551: #--- Dumps the class list with usernames,list of sections,
  552: #--- section, ids and fullnames for each user.
  553: sub getclasslist {
  554:     my ($getsec,$filterlist,$getgroup) = @_;
  555:     my @getsec;
  556:     my @getgroup;
  557:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  558:     if (!ref($getsec)) {
  559: 	if ($getsec ne '' && $getsec ne 'all') {
  560: 	    @getsec=($getsec);
  561: 	}
  562:     } else {
  563: 	@getsec=@{$getsec};
  564:     }
  565:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  566:     if (!ref($getgroup)) {
  567: 	if ($getgroup ne '' && $getgroup ne 'all') {
  568: 	    @getgroup=($getgroup);
  569: 	}
  570:     } else {
  571: 	@getgroup=@{$getgroup};
  572:     }
  573:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  574: 
  575:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  576:     # Bail out if we were unable to get the classlist
  577:     return if (! defined($classlist));
  578:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  579:     #
  580:     my %sections;
  581:     my %fullnames;
  582:     foreach my $student (keys(%$classlist)) {
  583:         my $end      = 
  584:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  585:         my $start    = 
  586:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  587:         my $id       = 
  588:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  589:         my $section  = 
  590:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  591:         my $fullname = 
  592:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  593:         my $status   = 
  594:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  595:         my $group   = 
  596:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  597: 	# filter students according to status selected
  598: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  599: 	    if (!($stu_status =~ $status)) {
  600: 		delete($classlist->{$student});
  601: 		next;
  602: 	    }
  603: 	}
  604: 	# filter students according to groups selected
  605: 	my @stu_groups = split(/,/,$group);
  606: 	if (@getgroup) {
  607: 	    my $exclude = 1;
  608: 	    foreach my $grp (@getgroup) {
  609: 	        foreach my $stu_group (@stu_groups) {
  610: 	            if ($stu_group eq $grp) {
  611: 	                $exclude = 0;
  612:     	            } 
  613: 	        }
  614:     	        if (($grp eq 'none') && !$group) {
  615:         	        $exclude = 0;
  616:         	}
  617: 	    }
  618: 	    if ($exclude) {
  619: 	        delete($classlist->{$student});
  620: 	    }
  621: 	}
  622: 	$section = ($section ne '' ? $section : 'none');
  623: 	if (&canview($section)) {
  624: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  625: 		$sections{$section}++;
  626: 		if ($classlist->{$student}) {
  627: 		    $fullnames{$student}=$fullname;
  628: 		}
  629: 	    } else {
  630: 		delete($classlist->{$student});
  631: 	    }
  632: 	} else {
  633: 	    delete($classlist->{$student});
  634: 	}
  635:     }
  636:     my %seen = ();
  637:     my @sections = sort(keys(%sections));
  638:     return ($classlist,\@sections,\%fullnames);
  639: }
  640: 
  641: sub canmodify {
  642:     my ($sec)=@_;
  643:     if ($perm{'mgr'}) {
  644: 	if (!defined($perm{'mgr_section'})) {
  645: 	    # can modify whole class
  646: 	    return 1;
  647: 	} else {
  648: 	    if ($sec eq $perm{'mgr_section'}) {
  649: 		#can modify the requested section
  650: 		return 1;
  651: 	    } else {
  652: 		# can't modify the request section
  653: 		return 0;
  654: 	    }
  655: 	}
  656:     }
  657:     #can't modify
  658:     return 0;
  659: }
  660: 
  661: sub canview {
  662:     my ($sec)=@_;
  663:     if ($perm{'vgr'}) {
  664: 	if (!defined($perm{'vgr_section'})) {
  665: 	    # can modify whole class
  666: 	    return 1;
  667: 	} else {
  668: 	    if ($sec eq $perm{'vgr_section'}) {
  669: 		#can modify the requested section
  670: 		return 1;
  671: 	    } else {
  672: 		# can't modify the request section
  673: 		return 0;
  674: 	    }
  675: 	}
  676:     }
  677:     #can't modify
  678:     return 0;
  679: }
  680: 
  681: #--- Retrieve the grade status of a student for all the parts
  682: sub student_gradeStatus {
  683:     my ($symb,$udom,$uname,$partlist) = @_;
  684:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  685:     my %partstatus = ();
  686:     foreach (@$partlist) {
  687: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  688: 	$status              = 'nothing' if ($status eq '');
  689: 	$partstatus{$_}      = $status;
  690: 	my $subkey           = "resource.$_.submitted_by";
  691: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  692:     }
  693:     return %partstatus;
  694: }
  695: 
  696: # hidden form and javascript that calls the form
  697: # Use by verifyscript and viewgrades
  698: # Shows a student's view of problem and submission
  699: sub jscriptNform {
  700:     my ($symb) = @_;
  701:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  702:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  703: 	'    function viewOneStudent(user,domain) {'."\n".
  704: 	'	document.onestudent.student.value = user;'."\n".
  705: 	'	document.onestudent.userdom.value = domain;'."\n".
  706: 	'	document.onestudent.submit();'."\n".
  707: 	'    }'."\n".
  708: 	'</script>'."\n";
  709:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  710: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  711: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  712: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  713: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  714: 	'<input type="hidden" name="command" value="submission" />'."\n".
  715: 	'<input type="hidden" name="student" value="" />'."\n".
  716: 	'<input type="hidden" name="userdom" value="" />'."\n".
  717: 	'</form>'."\n";
  718:     return $jscript;
  719: }
  720: 
  721: 
  722: 
  723: # Given the score (as a number [0-1] and the weight) what is the final
  724: # point value? This function will round to the nearest tenth, third,
  725: # or quarter if one of those is within the tolerance of .00001.
  726: sub compute_points {
  727:     my ($score, $weight) = @_;
  728:     
  729:     my $tolerance = .00001;
  730:     my $points = $score * $weight;
  731: 
  732:     # Check for nearness to 1/x.
  733:     my $check_for_nearness = sub {
  734:         my ($factor) = @_;
  735:         my $num = ($points * $factor) + $tolerance;
  736:         my $floored_num = floor($num);
  737:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  738:             return $floored_num / $factor;
  739:         }
  740:         return $points;
  741:     };
  742: 
  743:     $points = $check_for_nearness->(10);
  744:     $points = $check_for_nearness->(3);
  745:     $points = $check_for_nearness->(4);
  746:     
  747:     return $points;
  748: }
  749: 
  750: #------------------ End of general use routines --------------------
  751: 
  752: #
  753: # Find most similar essay
  754: #
  755: 
  756: sub most_similar {
  757:     my ($uname,$udom,$symb,$uessay)=@_;
  758: 
  759:     unless ($symb) { return ''; }
  760: 
  761:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  762: 
  763: # ignore spaces and punctuation
  764: 
  765:     $uessay=~s/\W+/ /gs;
  766: 
  767: # ignore empty submissions (occuring when only files are sent)
  768: 
  769:     unless ($uessay=~/\w+/s) { return ''; }
  770: 
  771: # these will be returned. Do not care if not at least 50 percent similar
  772:     my $limit=0.6;
  773:     my $sname='';
  774:     my $sdom='';
  775:     my $scrsid='';
  776:     my $sessay='';
  777: # go through all essays ...
  778:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  779: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  780: # ... except the same student
  781:         next if (($tname eq $uname) && ($tdom eq $udom));
  782: 	my $tessay=$old_essays{$symb}{$tkey};
  783: 	$tessay=~s/\W+/ /gs;
  784: # String similarity gives up if not even limit
  785: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  786: # Found one
  787: 	if ($tsimilar>$limit) {
  788: 	    $limit=$tsimilar;
  789: 	    $sname=$tname;
  790: 	    $sdom=$tdom;
  791: 	    $scrsid=$tcrsid;
  792: 	    $sessay=$old_essays{$symb}{$tkey};
  793: 	}
  794:     }
  795:     if ($limit>0.6) {
  796:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  797:     } else {
  798:        return ('','','','',0);
  799:     }
  800: }
  801: 
  802: #-------------------------------------------------------------------
  803: 
  804: #------------------------------------ Receipt Verification Routines
  805: #
  806: #--- Check whether a receipt number is valid.---
  807: sub verifyreceipt {
  808:     my $request  = shift;
  809: 
  810:     my $courseid = $env{'request.course.id'};
  811:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  812: 	$env{'form.receipt'};
  813:     $receipt     =~ s/[^\-\d]//g;
  814:     my ($symb)   = &get_symb($request);
  815: 
  816:     my $title.=
  817: 	'<h3><span class="LC_info">'.
  818: 	&mt('Verifying Receipt No. [_1]',$receipt).
  819: 	'</span></h3>'."\n".
  820: 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
  821: 	'</h4>'."\n";
  822: 
  823:     my ($string,$contents,$matches) = ('','',0);
  824:     my (undef,undef,$fullname) = &getclasslist('all','0');
  825:     
  826:     my $receiptparts=0;
  827:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  828: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  829:     my $parts=['0'];
  830:     if ($receiptparts) {
  831:         my $res_error; 
  832:         ($parts)=&response_type($symb,\$res_error);
  833:         if ($res_error) {
  834:             return &navmap_errormsg();
  835:         } 
  836:     }
  837:     
  838:     my $header = 
  839: 	&Apache::loncommon::start_data_table().
  840: 	&Apache::loncommon::start_data_table_header_row().
  841: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  842: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  843: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  844:     if ($receiptparts) {
  845: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  846:     }
  847:     $header.=
  848: 	&Apache::loncommon::end_data_table_header_row();
  849: 
  850:     foreach (sort 
  851: 	     {
  852: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  853: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  854: 		 }
  855: 		 return $a cmp $b;
  856: 	     } (keys(%$fullname))) {
  857: 	my ($uname,$udom)=split(/\:/);
  858: 	foreach my $part (@$parts) {
  859: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  860: 		$contents.=
  861: 		    &Apache::loncommon::start_data_table_row().
  862: 		    '<td>&nbsp;'."\n".
  863: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  864: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  865: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  866: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  867: 		if ($receiptparts) {
  868: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  869: 		}
  870: 		$contents.= 
  871: 		    &Apache::loncommon::end_data_table_row()."\n";
  872: 		
  873: 		$matches++;
  874: 	    }
  875: 	}
  876:     }
  877:     if ($matches == 0) {
  878:         $string = $title
  879:                  .'<p class="LC_warning">'
  880:                  .&mt('No match found for the above receipt number.')
  881:                  .'</p>';
  882:     } else {
  883: 	$string = &jscriptNform($symb).$title.
  884: 	    '<p>'.
  885: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  886: 	    '</p>'.
  887: 	    $header.
  888: 	    $contents.
  889: 	    &Apache::loncommon::end_data_table()."\n";
  890:     }
  891:     return $string.&show_grading_menu_form($symb);
  892: }
  893: 
  894: #--- This is called by a number of programs.
  895: #--- Called from the Grading Menu - View/Grade an individual student
  896: #--- Also called directly when one clicks on the subm button 
  897: #    on the problem page.
  898: sub listStudents {
  899:     my ($request) = shift;
  900: 
  901:     my ($symb) = &get_symb($request);
  902:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  903:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  904:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  905:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  906:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  907:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  908:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  909: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  910: 
  911:     my $result='<h3><span class="LC_info">&nbsp;'
  912: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  913: 	.'</span></h3>';
  914: 
  915:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  916: 
  917:     my %lt = &Apache::lonlocal::texthash (
  918: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  919: 		'single'   => 'Please select the student before clicking on the Next button.',
  920: 	     );
  921:     $request->print(<<LISTJAVASCRIPT);
  922: <script type="text/javascript" language="javascript">
  923:     function checkSelect(checkBox) {
  924: 	var ctr=0;
  925: 	var sense="";
  926: 	if (checkBox.length > 1) {
  927: 	    for (var i=0; i<checkBox.length; i++) {
  928: 		if (checkBox[i].checked) {
  929: 		    ctr++;
  930: 		}
  931: 	    }
  932: 	    sense = '$lt{'multiple'}';
  933: 	} else {
  934: 	    if (checkBox.checked) {
  935: 		ctr = 1;
  936: 	    }
  937: 	    sense = '$lt{'single'}';
  938: 	}
  939: 	if (ctr == 0) {
  940: 	    alert(sense);
  941: 	    return false;
  942: 	}
  943: 	document.gradesub.submit();
  944:     }
  945: 
  946:     function reLoadList(formname) {
  947: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  948: 	formname.command.value = 'submission';
  949: 	formname.submit();
  950:     }
  951: </script>
  952: LISTJAVASCRIPT
  953: 
  954:     &commonJSfunctions($request);
  955:     $request->print($result);
  956: 
  957:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  958:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  959:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  960: 	"\n".$table;
  961: 	
  962:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  963:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  964:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  965:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  966:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  967:                   .&Apache::lonhtmlcommon::row_closure();
  968:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  969:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  970:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  971:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  972:                   .&Apache::lonhtmlcommon::row_closure();
  973: 
  974:     my $submission_options;
  975:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  976: 	$submission_options.=
  977: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  978:     }
  979:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  980:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  981:     $env{'form.Status'} = $saveStatus;
  982:     $submission_options.=
  983:         '<span class="LC_nobreak">'.
  984:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  985:         &mt('last submission only').' </label></span>'."\n".
  986:         '<span class="LC_nobreak">'.
  987:         '<label><input type="radio" name="lastSub" value="last" /> '.
  988:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  989:         '<span class="LC_nobreak">'.
  990:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  991:         &mt('by dates and submissions').'</label></span>'."\n".
  992:         '<span class="LC_nobreak">'.
  993:         '<label><input type="radio" name="lastSub" value="all" /> '.
  994:         &mt('all details').'</label></span>';
  995:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  996:                   .$submission_options
  997:                   .&Apache::lonhtmlcommon::row_closure();
  998: 
  999:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1000:                   .'<select name="increment">'
 1001:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1002:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1003:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1004:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1005:                   .'</select>'
 1006:                   .&Apache::lonhtmlcommon::row_closure();
 1007: 
 1008:     $gradeTable .= 
 1009:         &build_section_inputs().
 1010: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1011: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1012: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1013: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1014: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1015: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1016: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1017: 
 1018:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1019: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1020:     } else {
 1021:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1022:                       .&Apache::lonhtmlcommon::StatusOptions(
 1023:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1024:                       .&Apache::lonhtmlcommon::row_closure();
 1025:     }
 1026: 
 1027:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1028:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1029:                   .&Apache::lonhtmlcommon::row_closure(1)
 1030:                   .&Apache::lonhtmlcommon::end_pick_box();
 1031: 
 1032:     $gradeTable .= '<p>'
 1033:                   .&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"
 1034:                   .'<input type="hidden" name="command" value="processGroup" />'
 1035:                   .'</p>';
 1036: 
 1037: # checkall buttons
 1038:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1039:     $gradeTable.='<input type="button" '."\n".
 1040:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1041:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1042:     $gradeTable.=&check_buttons();
 1043:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1044:     $gradeTable.= &Apache::loncommon::start_data_table().
 1045: 	&Apache::loncommon::start_data_table_header_row();
 1046:     my $loop = 0;
 1047:     while ($loop < 2) {
 1048: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1049: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1050: 	if ($env{'form.showgrading'} eq 'yes' 
 1051: 	    && $submitonly ne 'queued'
 1052: 	    && $submitonly ne 'all') {
 1053: 	    foreach my $part (sort(@$partlist)) {
 1054: 		my $display_part=
 1055: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1056: 		$gradeTable.=
 1057: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1058: 	    }
 1059: 	} elsif ($submitonly eq 'queued') {
 1060: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1061: 	}
 1062: 	$loop++;
 1063: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1064:     }
 1065:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1066: 
 1067:     my $ctr = 0;
 1068:     foreach my $student (sort 
 1069: 			 {
 1070: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1071: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1072: 			     }
 1073: 			     return $a cmp $b;
 1074: 			 }
 1075: 			 (keys(%$fullname))) {
 1076: 	my ($uname,$udom) = split(/:/,$student);
 1077: 
 1078: 	my %status = ();
 1079: 
 1080: 	if ($submitonly eq 'queued') {
 1081: 	    my %queue_status = 
 1082: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1083: 							$udom,$uname);
 1084: 	    next if (!defined($queue_status{'gradingqueue'}));
 1085: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1086: 	}
 1087: 
 1088: 	if ($env{'form.showgrading'} eq 'yes' 
 1089: 	    && $submitonly ne 'queued'
 1090: 	    && $submitonly ne 'all') {
 1091: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1092: 	    my $submitted = 0;
 1093: 	    my $graded = 0;
 1094: 	    my $incorrect = 0;
 1095: 	    foreach (keys(%status)) {
 1096: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1097: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1098: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1099: 		
 1100: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1101: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1102: 		    $submitted = 0;
 1103: 		    my ($part)=split(/\./,$partid);
 1104: 		    $gradeTable.='<input type="hidden" name="'.
 1105: 			$student.':'.$part.':submitted_by" value="'.
 1106: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1107: 		}
 1108: 	    }
 1109: 	    
 1110: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1111: 				     $submitonly eq 'incorrect' ||
 1112: 				     $submitonly eq 'graded'));
 1113: 	    next if (!$graded && ($submitonly eq 'graded'));
 1114: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1115: 	}
 1116: 
 1117: 	$ctr++;
 1118: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1119:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1120: 	if ( $perm{'vgr'} eq 'F' ) {
 1121: 	    if ($ctr%2 ==1) {
 1122: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1123: 	    }
 1124: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1125:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1126:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1127: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1128: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1129: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1130: 
 1131: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1132: 		foreach (sort(keys(%status))) {
 1133: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1134: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1135: 		}
 1136: 	    }
 1137: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1138: 	    if ($ctr%2 ==0) {
 1139: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1140: 	    }
 1141: 	}
 1142:     }
 1143:     if ($ctr%2 ==1) {
 1144: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1145: 	    if ($env{'form.showgrading'} eq 'yes' 
 1146: 		&& $submitonly ne 'queued'
 1147: 		&& $submitonly ne 'all') {
 1148: 		foreach (@$partlist) {
 1149: 		    $gradeTable.='<td>&nbsp;</td>';
 1150: 		}
 1151: 	    } elsif ($submitonly eq 'queued') {
 1152: 		$gradeTable.='<td>&nbsp;</td>';
 1153: 	    }
 1154: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1155:     }
 1156: 
 1157:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1158:         '<input type="button" '.
 1159:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1160:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1161:     if ($ctr == 0) {
 1162: 	my $num_students=(scalar(keys(%$fullname)));
 1163: 	if ($num_students eq 0) {
 1164: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1165: 	} else {
 1166: 	    my $submissions='submissions';
 1167: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1168: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1169: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1170: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1171: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1172: 		    $num_students).
 1173: 		'</span><br />';
 1174: 	}
 1175:     } elsif ($ctr == 1) {
 1176: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1177:     }
 1178:     $gradeTable.=&show_grading_menu_form($symb);
 1179:     $request->print($gradeTable);
 1180:     return '';
 1181: }
 1182: 
 1183: #---- Called from the listStudents routine
 1184: 
 1185: sub check_script {
 1186:     my ($form, $type)=@_;
 1187:     my $chkallscript='<script type="text/javascript">
 1188:     function checkall() {
 1189:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1190:             ele = document.forms.'.$form.'.elements[i];
 1191:             if (ele.name == "'.$type.'") {
 1192:             document.forms.'.$form.'.elements[i].checked=true;
 1193:                                        }
 1194:         }
 1195:     }
 1196: 
 1197:     function checksec() {
 1198:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1199:             ele = document.forms.'.$form.'.elements[i];
 1200:            string = document.forms.'.$form.'.chksec.value;
 1201:            if
 1202:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1203:               document.forms.'.$form.'.elements[i].checked=true;
 1204:             }
 1205:         }
 1206:     }
 1207: 
 1208: 
 1209:     function uncheckall() {
 1210:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1211:             ele = document.forms.'.$form.'.elements[i];
 1212:             if (ele.name == "'.$type.'") {
 1213:             document.forms.'.$form.'.elements[i].checked=false;
 1214:                                        }
 1215:         }
 1216:     }
 1217: 
 1218: </script>'."\n";
 1219:     return $chkallscript;
 1220: }
 1221: 
 1222: sub check_buttons {
 1223:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1224:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1225:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1226:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1227:     return $buttons;
 1228: }
 1229: 
 1230: #     Displays the submissions for one student or a group of students
 1231: sub processGroup {
 1232:     my ($request)  = shift;
 1233:     my $ctr        = 0;
 1234:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1235:     my $total      = scalar(@stuchecked)-1;
 1236: 
 1237:     foreach my $student (@stuchecked) {
 1238: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1239: 	$env{'form.student'}        = $uname;
 1240: 	$env{'form.userdom'}        = $udom;
 1241: 	$env{'form.fullname'}       = $fullname;
 1242: 	&submission($request,$ctr,$total);
 1243: 	$ctr++;
 1244:     }
 1245:     return '';
 1246: }
 1247: 
 1248: #------------------------------------------------------------------------------------
 1249: #
 1250: #-------------------------- Next few routines handles grading by student, essentially
 1251: #                           handles essay response type problem/part
 1252: #
 1253: #--- Javascript to handle the submission page functionality ---
 1254: sub sub_page_js {
 1255:     my $request = shift;
 1256: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1257:     $request->print(<<SUBJAVASCRIPT);
 1258: <script type="text/javascript" language="javascript">
 1259:     function updateRadio(formname,id,weight) {
 1260: 	var gradeBox = formname["GD_BOX"+id];
 1261: 	var radioButton = formname["RADVAL"+id];
 1262: 	var oldpts = formname["oldpts"+id].value;
 1263: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1264: 	gradeBox.value = pts;
 1265: 	var resetbox = false;
 1266: 	if (isNaN(pts) || pts < 0) {
 1267: 	    alert("$alertmsg"+pts);
 1268: 	    for (var i=0; i<radioButton.length; i++) {
 1269: 		if (radioButton[i].checked) {
 1270: 		    gradeBox.value = i;
 1271: 		    resetbox = true;
 1272: 		}
 1273: 	    }
 1274: 	    if (!resetbox) {
 1275: 		formtextbox.value = "";
 1276: 	    }
 1277: 	    return;
 1278: 	}
 1279: 
 1280: 	if (pts > weight) {
 1281: 	    var resp = confirm("You entered a value ("+pts+
 1282: 			       ") greater than the weight for the part. Accept?");
 1283: 	    if (resp == false) {
 1284: 		gradeBox.value = oldpts;
 1285: 		return;
 1286: 	    }
 1287: 	}
 1288: 
 1289: 	for (var i=0; i<radioButton.length; i++) {
 1290: 	    radioButton[i].checked=false;
 1291: 	    if (pts == i && pts != "") {
 1292: 		radioButton[i].checked=true;
 1293: 	    }
 1294: 	}
 1295: 	updateSelect(formname,id);
 1296: 	formname["stores"+id].value = "0";
 1297:     }
 1298: 
 1299:     function writeBox(formname,id,pts) {
 1300: 	var gradeBox = formname["GD_BOX"+id];
 1301: 	if (checkSolved(formname,id) == 'update') {
 1302: 	    gradeBox.value = pts;
 1303: 	} else {
 1304: 	    var oldpts = formname["oldpts"+id].value;
 1305: 	    gradeBox.value = oldpts;
 1306: 	    var radioButton = formname["RADVAL"+id];
 1307: 	    for (var i=0; i<radioButton.length; i++) {
 1308: 		radioButton[i].checked=false;
 1309: 		if (i == oldpts) {
 1310: 		    radioButton[i].checked=true;
 1311: 		}
 1312: 	    }
 1313: 	}
 1314: 	formname["stores"+id].value = "0";
 1315: 	updateSelect(formname,id);
 1316: 	return;
 1317:     }
 1318: 
 1319:     function clearRadBox(formname,id) {
 1320: 	if (checkSolved(formname,id) == 'noupdate') {
 1321: 	    updateSelect(formname,id);
 1322: 	    return;
 1323: 	}
 1324: 	gradeSelect = formname["GD_SEL"+id];
 1325: 	for (var i=0; i<gradeSelect.length; i++) {
 1326: 	    if (gradeSelect[i].selected) {
 1327: 		var selectx=i;
 1328: 	    }
 1329: 	}
 1330: 	var stores = formname["stores"+id];
 1331: 	if (selectx == stores.value) { return };
 1332: 	var gradeBox = formname["GD_BOX"+id];
 1333: 	gradeBox.value = "";
 1334: 	var radioButton = formname["RADVAL"+id];
 1335: 	for (var i=0; i<radioButton.length; i++) {
 1336: 	    radioButton[i].checked=false;
 1337: 	}
 1338: 	stores.value = selectx;
 1339:     }
 1340: 
 1341:     function checkSolved(formname,id) {
 1342: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1343: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1344: 	    if (!reply) {return "noupdate";}
 1345: 	    formname.overRideScore.value = 'yes';
 1346: 	}
 1347: 	return "update";
 1348:     }
 1349: 
 1350:     function updateSelect(formname,id) {
 1351: 	formname["GD_SEL"+id][0].selected = true;
 1352: 	return;
 1353:     }
 1354: 
 1355: //=========== Check that a point is assigned for all the parts  ============
 1356:     function checksubmit(formname,val,total,parttot) {
 1357: 	formname.gradeOpt.value = val;
 1358: 	if (val == "Save & Next") {
 1359: 	    for (i=0;i<=total;i++) {
 1360: 		for (j=0;j<parttot;j++) {
 1361: 		    var partid = formname["partid"+i+"_"+j].value;
 1362: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1363: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1364: 			if (points == "") {
 1365: 			    var name = formname["name"+i].value;
 1366: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1367: 			    var resp = confirm("You did not assign a score for "+studentID+
 1368: 					       ", part "+partid+". Continue?");
 1369: 			    if (resp == false) {
 1370: 				formname["GD_BOX"+i+"_"+partid].focus();
 1371: 				return false;
 1372: 			    }
 1373: 			}
 1374: 		    }
 1375: 		    
 1376: 		}
 1377: 	    }
 1378: 	    
 1379: 	}
 1380: 	if (val == "Grade Student") {
 1381: 	    formname.showgrading.value = "yes";
 1382: 	    if (formname.Status.value == "") {
 1383: 		formname.Status.value = "Active";
 1384: 	    }
 1385: 	    formname.studentNo.value = total;
 1386: 	}
 1387: 	formname.submit();
 1388:     }
 1389: 
 1390: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1391:     function checkSubmitPage(formname,total) {
 1392: 	noscore = new Array(100);
 1393: 	var ptr = 0;
 1394: 	for (i=1;i<total;i++) {
 1395: 	    var partid = formname["q_"+i].value;
 1396: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1397: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1398: 		var status = formname["solved"+i+"_"+partid].value;
 1399: 		if (points == "" && status != "correct_by_student") {
 1400: 		    noscore[ptr] = i;
 1401: 		    ptr++;
 1402: 		}
 1403: 	    }
 1404: 	}
 1405: 	if (ptr != 0) {
 1406: 	    var sense = ptr == 1 ? ": " : "s: ";
 1407: 	    var prolist = "";
 1408: 	    if (ptr == 1) {
 1409: 		prolist = noscore[0];
 1410: 	    } else {
 1411: 		var i = 0;
 1412: 		while (i < ptr-1) {
 1413: 		    prolist += noscore[i]+", ";
 1414: 		    i++;
 1415: 		}
 1416: 		prolist += "and "+noscore[i];
 1417: 	    }
 1418: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1419: 	    if (resp == false) {
 1420: 		return false;
 1421: 	    }
 1422: 	}
 1423: 
 1424: 	formname.submit();
 1425:     }
 1426: </script>
 1427: SUBJAVASCRIPT
 1428: }
 1429: 
 1430: #--- javascript for essay type problem --
 1431: sub sub_page_kw_js {
 1432:     my $request = shift;
 1433:     my $iconpath = $request->dir_config('lonIconsURL');
 1434:     &commonJSfunctions($request);
 1435: 
 1436:     my $inner_js_msg_central=<<INNERJS;
 1437:     <script text="text/javascript">
 1438:     function checkInput() {
 1439:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1440:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1441:       var usrctr = document.msgcenter.usrctr.value;
 1442:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1443:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1444: 
 1445:       var msgchk = "";
 1446:       if (document.msgcenter.subchk.checked) {
 1447:          msgchk = "msgsub,";
 1448:       }
 1449:       var includemsg = 0;
 1450:       for (var i=1; i<=nmsg; i++) {
 1451:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1452:           var frmmsg = document.msgcenter["msg"+i];
 1453:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1454:           var showflg = opener.document.SCORE["shownOnce"+i];
 1455:           showflg.value = "1";
 1456:           var chkbox = document.msgcenter["msgn"+i];
 1457:           if (chkbox.checked) {
 1458:              msgchk += "savemsg"+i+",";
 1459:              includemsg = 1;
 1460:           }
 1461:       }
 1462:       if (document.msgcenter.newmsgchk.checked) {
 1463:          msgchk += "newmsg"+usrctr;
 1464:          includemsg = 1;
 1465:       }
 1466:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1467:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1468:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1469:       includemsg.value = msgchk;
 1470: 
 1471:       self.close()
 1472: 
 1473:     }
 1474:     </script>
 1475: INNERJS
 1476: 
 1477:     my $inner_js_highlight_central=<<INNERJS;
 1478:  <script type="text/javascript">
 1479:     function updateChoice(flag) {
 1480:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1481:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1482:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1483:       opener.document.SCORE.refresh.value = "on";
 1484:       if (opener.document.SCORE.keywords.value!=""){
 1485:          opener.document.SCORE.submit();
 1486:       }
 1487:       self.close()
 1488:     }
 1489: </script>
 1490: INNERJS
 1491: 
 1492:     my $start_page_msg_central = 
 1493:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1494: 				       {'js_ready'  => 1,
 1495: 					'only_body' => 1,
 1496: 					'bgcolor'   =>'#FFFFFF',});
 1497:     my $end_page_msg_central = 
 1498: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1499: 
 1500: 
 1501:     my $start_page_highlight_central = 
 1502:         &Apache::loncommon::start_page('Highlight Central',
 1503: 				       $inner_js_highlight_central,
 1504: 				       {'js_ready'  => 1,
 1505: 					'only_body' => 1,
 1506: 					'bgcolor'   =>'#FFFFFF',});
 1507:     my $end_page_highlight_central = 
 1508: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1509: 
 1510:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1511:     $docopen=~s/^document\.//;
 1512:     my %lt = &Apache::lonlocal::texthash(
 1513:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1514:                 plse => 'Please select a word or group of words from document and then click this link.',
 1515:                 adds => 'Add selection to keyword list? Edit if desired.',
 1516:                 comp => 'Compose Message for: ',
 1517:                 incl => 'Include',
 1518:                 type => 'Type',
 1519:                 subj => 'Subject',
 1520:                 mesa => 'Message',
 1521:                 new  => 'New',
 1522:                 save => 'Save',
 1523:                 canc => 'Cancel',
 1524:                 kehi => 'Keyword Highlight Options',
 1525:                 txtc => 'Text Color',
 1526:                 font => 'Font Size',
 1527:                 fnst => 'Font Style',
 1528:                 col1 => 'red',
 1529:                 col2 => 'green',
 1530:                 col3 => 'blue',
 1531:                 siz1 => 'normal',
 1532:                 siz2 => '+1',
 1533:                 siz3 => '+2',
 1534:                 sty1 => 'normal',
 1535:                 sty2 => 'italic',
 1536:                 sty3 => 'bold',
 1537:              );
 1538:     $request->print(<<SUBJAVASCRIPT);
 1539: <script type="text/javascript" language="javascript">
 1540: 
 1541: //===================== Show list of keywords ====================
 1542:   function keywords(formname) {
 1543:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1544:     if (nret==null) return;
 1545:     formname.keywords.value = nret;
 1546: 
 1547:     if (formname.keywords.value != "") {
 1548: 	formname.refresh.value = "on";
 1549: 	formname.submit();
 1550:     }
 1551:     return;
 1552:   }
 1553: 
 1554: //===================== Script to view submitted by ==================
 1555:   function viewSubmitter(submitter) {
 1556:     document.SCORE.refresh.value = "on";
 1557:     document.SCORE.NCT.value = "1";
 1558:     document.SCORE.unamedom0.value = submitter;
 1559:     document.SCORE.submit();
 1560:     return;
 1561:   }
 1562: 
 1563: //===================== Script to add keyword(s) ==================
 1564:   function getSel() {
 1565:     if (document.getSelection) txt = document.getSelection();
 1566:     else if (document.selection) txt = document.selection.createRange().text;
 1567:     else return;
 1568:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1569:     if (cleantxt=="") {
 1570: 	alert("$lt{'plse'}");
 1571: 	return;
 1572:     }
 1573:     var nret = prompt("$lt{'adds'}",cleantxt);
 1574:     if (nret==null) return;
 1575:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1576:     if (document.SCORE.keywords.value != "") {
 1577: 	document.SCORE.refresh.value = "on";
 1578: 	document.SCORE.submit();
 1579:     }
 1580:     return;
 1581:   }
 1582: 
 1583: //====================== Script for composing message ==============
 1584:    // preload images
 1585:    img1 = new Image();
 1586:    img1.src = "$iconpath/mailbkgrd.gif";
 1587:    img2 = new Image();
 1588:    img2.src = "$iconpath/mailto.gif";
 1589: 
 1590:   function msgCenter(msgform,usrctr,fullname) {
 1591:     var Nmsg  = msgform.savemsgN.value;
 1592:     savedMsgHeader(Nmsg,usrctr,fullname);
 1593:     var subject = msgform.msgsub.value;
 1594:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1595:     re = /msgsub/;
 1596:     var shwsel = "";
 1597:     if (re.test(msgchk)) { shwsel = "checked" }
 1598:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1599:     displaySubject(checkEntities(subject),shwsel);
 1600:     for (var i=1; i<=Nmsg; i++) {
 1601: 	var testmsg = "savemsg"+i+",";
 1602: 	re = new RegExp(testmsg,"g");
 1603: 	shwsel = "";
 1604: 	if (re.test(msgchk)) { shwsel = "checked" }
 1605: 	var message = document.SCORE["savemsg"+i].value;
 1606: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1607: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1608: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1609:     }
 1610:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1611:     shwsel = "";
 1612:     re = /newmsg/;
 1613:     if (re.test(msgchk)) { shwsel = "checked" }
 1614:     newMsg(newmsg,shwsel);
 1615:     msgTail(); 
 1616:     return;
 1617:   }
 1618: 
 1619:   function checkEntities(strx) {
 1620:     if (strx.length == 0) return strx;
 1621:     var orgStr = ["&", "<", ">", '"']; 
 1622:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1623:     var counter = 0;
 1624:     while (counter < 4) {
 1625: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1626: 	counter++;
 1627:     }
 1628:     return strx;
 1629:   }
 1630: 
 1631:   function strReplace(strx, orgStr, newStr) {
 1632:     return strx.split(orgStr).join(newStr);
 1633:   }
 1634: 
 1635:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1636:     var height = 70*Nmsg+250;
 1637:     if (height > 600) {
 1638: 	height = 600;
 1639:     }
 1640:     var xpos = (screen.width-600)/2;
 1641:     xpos = (xpos < 0) ? '0' : xpos;
 1642:     var ypos = (screen.height-height)/2-30;
 1643:     ypos = (ypos < 0) ? '0' : ypos;
 1644: 
 1645:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1646:     pWin.focus();
 1647:     pDoc = pWin.document;
 1648:     pDoc.$docopen;
 1649:     pDoc.write('$start_page_msg_central');
 1650: 
 1651:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1652:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1653:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1654: 
 1655:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1656:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1657:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1658: }
 1659:     function displaySubject(msg,shwsel) {
 1660:     pDoc = pWin.document;
 1661:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1662:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1663:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1664:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1665: }
 1666: 
 1667:   function displaySavedMsg(ctr,msg,shwsel) {
 1668:     pDoc = pWin.document;
 1669:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1670:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1671:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1672:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1673: }
 1674: 
 1675:   function newMsg(newmsg,shwsel) {
 1676:     pDoc = pWin.document;
 1677:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1678:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1679:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1680:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1681: }
 1682: 
 1683:   function msgTail() {
 1684:     pDoc = pWin.document;
 1685:     pDoc.write("<\\/table>");
 1686:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1687:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1688:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1689:     pDoc.write("<\\/form>");
 1690:     pDoc.write('$end_page_msg_central');
 1691:     pDoc.close();
 1692: }
 1693: 
 1694: //====================== Script for keyword highlight options ==============
 1695:   function kwhighlight() {
 1696:     var kwclr    = document.SCORE.kwclr.value;
 1697:     var kwsize   = document.SCORE.kwsize.value;
 1698:     var kwstyle  = document.SCORE.kwstyle.value;
 1699:     var redsel = "";
 1700:     var grnsel = "";
 1701:     var blusel = "";
 1702:     var txtcol1 = "$lt{'col1'}";
 1703:     var txtcol2 = "$lt{'col2'}";
 1704:     var txtcol3 = "$lt{'col3'}";
 1705:     var txtsiz1 = "$lt{'siz1'}";
 1706:     var txtsiz2 = "$lt{'siz2'}";
 1707:     var txtsiz3 = "$lt{'siz3'}";
 1708:     var txtsty1 = "$lt{'sty1'}";
 1709:     var txtsty2 = "$lt{'sty2'}";
 1710:     var txtsty3 = "$lt{'sty3'}";
 1711:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1712:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1713:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1714:     var sznsel = "";
 1715:     var sz1sel = "";
 1716:     var sz2sel = "";
 1717:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1718:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1719:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1720:     var synsel = "";
 1721:     var syisel = "";
 1722:     var sybsel = "";
 1723:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1724:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1725:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1726:     highlightCentral();
 1727:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1728:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1729:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1730:     highlightend();
 1731:     return;
 1732:   }
 1733: 
 1734:   function highlightCentral() {
 1735: //    if (window.hwdWin) window.hwdWin.close();
 1736:     var xpos = (screen.width-400)/2;
 1737:     xpos = (xpos < 0) ? '0' : xpos;
 1738:     var ypos = (screen.height-330)/2-30;
 1739:     ypos = (ypos < 0) ? '0' : ypos;
 1740: 
 1741:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1742:     hwdWin.focus();
 1743:     var hDoc = hwdWin.document;
 1744:     hDoc.$docopen;
 1745:     hDoc.write('$start_page_highlight_central');
 1746:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1747:     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
 1748: 
 1749:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1750:     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
 1751:   }
 1752: 
 1753:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1754:     var hDoc = hwdWin.document;
 1755:     hDoc.write("<tr>");
 1756:     hDoc.write("<td align=\\"left\\">");
 1757:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1758:     hDoc.write("<td align=\\"left\\">");
 1759:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1760:     hDoc.write("<td align=\\"left\\">");
 1761:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1762:     hDoc.write("<\\/tr>");
 1763:   }
 1764: 
 1765:   function highlightend() { 
 1766:     var hDoc = hwdWin.document;
 1767:     hDoc.write("<\\/table><br \\/>");
 1768:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1769:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1770:     hDoc.write("<\\/form>");
 1771:     hDoc.write('$end_page_highlight_central');
 1772:     hDoc.close();
 1773:   }
 1774: 
 1775: </script>
 1776: SUBJAVASCRIPT
 1777: }
 1778: 
 1779: sub get_increment {
 1780:     my $increment = $env{'form.increment'};
 1781:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1782:         $increment != .1) {
 1783:         $increment = 1;
 1784:     }
 1785:     return $increment;
 1786: }
 1787: 
 1788: sub gradeBox_start {
 1789:     return (
 1790:         &Apache::loncommon::start_data_table()
 1791:        .&Apache::loncommon::start_data_table_header_row()
 1792:        .'<th>'.&mt('Part').'</th>'
 1793:        .'<th>'.&mt('Points').'</th>'
 1794:        .'<th>&nbsp;</th>'
 1795:        .'<th>'.&mt('Assign Grade').'</th>'
 1796:        .'<th>'.&mt('Weight').'</th>'
 1797:        .'<th>'.&mt('Grade Status').'</th>'
 1798:        .&Apache::loncommon::end_data_table_header_row()
 1799:     );
 1800: }
 1801: 
 1802: sub gradeBox_end {
 1803:     return (
 1804:         &Apache::loncommon::end_data_table()
 1805:     );
 1806: }
 1807: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1808: sub gradeBox {
 1809:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1810:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1811: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1812:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1813:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1814:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1815:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1816:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1817: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1818:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1819:     my $display_part= &get_display_part($partid,$symb);
 1820:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1821: 				       [$partid]);
 1822:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1823:     if ($last_resets{$partid}) {
 1824:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1825:     }
 1826:     my $result=&Apache::loncommon::start_data_table_row();
 1827:     my $ctr = 0;
 1828:     my $thisweight = 0;
 1829:     my $increment = &get_increment();
 1830: 
 1831:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1832:     while ($thisweight<=$wgt) {
 1833: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1834:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1835: 	    $thisweight.')" value="'.$thisweight.'" '.
 1836: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1837: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1838:         $thisweight += $increment;
 1839: 	$ctr++;
 1840:     }
 1841:     $radio.='</tr></table>';
 1842: 
 1843:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1844: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1845: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1846: 	$wgt.')" /></td>'."\n";
 1847:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1848: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1849: 	' </td>'."\n";
 1850:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1851: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1852:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1853: 	$line.='<option></option>'.
 1854: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1855:     } else {
 1856: 	$line.='<option selected="selected"></option>'.
 1857: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1858:     }
 1859:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1860: 
 1861: 
 1862:     $result .= 
 1863: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1864:     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
 1865:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1866: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1867: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1868: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1869:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1870:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1871:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1872:         $aggtries.'" />'."\n";
 1873:     my $res_error;
 1874:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1875:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1876:     if ($res_error) {
 1877:         return &navmap_errormsg();
 1878:     }
 1879:     return $result;
 1880: }
 1881: 
 1882: sub handback_box {
 1883:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1884:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1885:     my (@respids);
 1886:     my @part_response_id = &flatten_responseType($responseType);
 1887:     foreach my $part_response_id (@part_response_id) {
 1888:     	my ($part,$resp) = @{ $part_response_id };
 1889:         if ($part eq $partid) {
 1890:             push(@respids,$resp);
 1891:         }
 1892:     }
 1893:     my $result;
 1894:     foreach my $respid (@respids) {
 1895: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1896: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1897: 	next if (!@$files);
 1898: 	my $file_counter = 0;
 1899: 	foreach my $file (@$files) {
 1900: 	    if ($file =~ /\/portfolio\//) {
 1901:                 $file_counter++;
 1902:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1903:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1904:     	        $file_disp = "$name.$ext";
 1905:     	        $file = $file_path.$file_disp;
 1906:     	        $result.=&mt('Return commented version of [_1] to student.',
 1907:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1908:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1909:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1910: 	    }
 1911: 	}
 1912:         if ($file_counter) {
 1913:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1914:                        '<span class="LC_info">'.
 1915:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1916:         }
 1917:     }
 1918:     return $result;    
 1919: }
 1920: 
 1921: sub show_problem {
 1922:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1923:     my $rendered;
 1924:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1925:     &Apache::lonxml::remember_problem_counter();
 1926:     if ($mode eq 'both' or $mode eq 'text') {
 1927: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1928: 						       $env{'request.course.id'},
 1929: 						       undef,\%form);
 1930:     }
 1931:     if ($removeform) {
 1932: 	$rendered=~s|<form(.*?)>||g;
 1933: 	$rendered=~s|</form>||g;
 1934: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1935:     }
 1936:     my $companswer;
 1937:     if ($mode eq 'both' or $mode eq 'answer') {
 1938: 	&Apache::lonxml::restore_problem_counter();
 1939: 	$companswer=
 1940: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1941: 						    $env{'request.course.id'},
 1942: 						    %form);
 1943:     }
 1944:     if ($removeform) {
 1945: 	$companswer=~s|<form(.*?)>||g;
 1946: 	$companswer=~s|</form>||g;
 1947: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1948:     }
 1949:     my $renderheading = &mt('View of the problem');
 1950:     my $answerheading = &mt('Correct answer');
 1951:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1952:         my $stu_fullname = $env{'form.fullname'};
 1953:         if ($stu_fullname eq '') {
 1954:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1955:         }
 1956:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1957:         if ($forwhom ne '') {
 1958:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1959:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1960:         }
 1961:     }
 1962:     $rendered=
 1963:         '<div class="LC_Box">'
 1964:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1965:        .$rendered
 1966:        .'</div>';
 1967:     $companswer=
 1968:         '<div class="LC_Box">'
 1969:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1970:        .$companswer
 1971:        .'</div>';
 1972:     my $result;
 1973:     if ($mode eq 'both') {
 1974:         $result=$rendered.$companswer;
 1975:     } elsif ($mode eq 'text') {
 1976:         $result=$rendered;
 1977:     } elsif ($mode eq 'answer') {
 1978:         $result=$companswer;
 1979:     }
 1980:     return $result;
 1981: }
 1982: 
 1983: sub files_exist {
 1984:     my ($r, $symb) = @_;
 1985:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1986: 
 1987:     foreach my $student (@students) {
 1988:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1989:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1990: 					      $udom,$uname);
 1991:         my ($string,$timestamp)= &get_last_submission(\%record);
 1992:         foreach my $submission (@$string) {
 1993:             my ($partid,$respid) =
 1994: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1995:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1996: 					   \%record);
 1997:             return 1 if (@$files);
 1998:         }
 1999:     }
 2000:     return 0;
 2001: }
 2002: 
 2003: sub download_all_link {
 2004:     my ($r,$symb) = @_;
 2005:     my $all_students = 
 2006: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2007: 
 2008:     my $parts =
 2009: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2010: 
 2011:     my $identifier = &Apache::loncommon::get_cgi_id();
 2012:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2013:                              'cgi.'.$identifier.'.symb' => $symb,
 2014:                              'cgi.'.$identifier.'.parts' => $parts,});
 2015:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2016: 	      &mt('Download All Submitted Documents').'</a>');
 2017:     return
 2018: }
 2019: 
 2020: sub build_section_inputs {
 2021:     my $section_inputs;
 2022:     if ($env{'form.section'} eq '') {
 2023:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2024:     } else {
 2025:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2026:         foreach my $section (@sections) {
 2027:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2028:         }
 2029:     }
 2030:     return $section_inputs;
 2031: }
 2032: 
 2033: # --------------------------- show submissions of a student, option to grade 
 2034: sub submission {
 2035:     my ($request,$counter,$total) = @_;
 2036:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2037:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2038:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2039:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2040:     my ($symb) = &get_symb($request); 
 2041:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2042: 
 2043:     if (!&canview($usec)) {
 2044:         $request->print(
 2045:             '<span class="LC_warning">'.
 2046:             &mt('Unable to view requested student.').
 2047:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2048:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2049:             '</span>');
 2050: 	$request->print(&show_grading_menu_form($symb));
 2051: 	return;
 2052:     }
 2053: 
 2054:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2055:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2056:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2057:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2058:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2059: 	'" src="'.$request->dir_config('lonIconsURL').
 2060: 	'/check.gif" height="16" border="0" />';
 2061: 
 2062:     # header info
 2063:     if ($counter == 0) {
 2064: 	&sub_page_js($request);
 2065: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2066: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2067: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2068: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2069: 	    &download_all_link($request, $symb);
 2070: 	}
 2071: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2072: 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
 2073: 
 2074: 	# option to display problem, only once else it cause problems 
 2075:         # with the form later since the problem has a form.
 2076: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2077: 	    my $mode;
 2078: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2079: 		$mode='both';
 2080: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2081: 		$mode='text';
 2082: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2083: 		$mode='answer';
 2084: 	    }
 2085: 	    &Apache::lonxml::clear_problem_counter();
 2086: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2087: 	}
 2088: 
 2089: 	# kwclr is the only variable that is guaranteed not to be blank 
 2090:         # if this subroutine has been called once.
 2091: 	my %keyhash = ();
 2092: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2093: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2094: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2095: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2096: 
 2097: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2098: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2099: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2100: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2101: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2102: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2103: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2104: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2105: 	}
 2106: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2107: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2108: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2109: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2110: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2111: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2112: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2113: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2114: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2115: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2116: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2117: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2118: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2119: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2120: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2121: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2122: 			&build_section_inputs().
 2123: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2124: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2125: 			'<input type="hidden" name="NCT"'.
 2126: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2127: 	if ($env{'form.handgrade'} eq 'yes') {
 2128: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2129: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2130: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2131: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2132: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2133: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2134: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2135: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2136: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2137: 	    }
 2138: 	}
 2139: 	
 2140: 	my ($cts,$prnmsg) = (1,'');
 2141: 	while ($cts <= $env{'form.savemsgN'}) {
 2142: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2143: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2144: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2145: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2146: 		'" />'."\n".
 2147: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2148: 	    $cts++;
 2149: 	}
 2150: 	$request->print($prnmsg);
 2151: 
 2152: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2153: 
 2154:             my %lt = &Apache::lonlocal::texthash(
 2155:                           keyh => 'Keyword Highlighting for Essays',
 2156:                           keyw => 'Keyword Options',
 2157:                           list => 'List',
 2158:                           past => 'Paste Selection to List',
 2159:                           high => 'Highlight Attribute',
 2160:                      );
 2161: #
 2162: # Print out the keyword options line
 2163: #
 2164:             $request->print(
 2165:                 '<div class="LC_columnSection">'
 2166:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2167:                .&Apache::lonhtmlcommon::funclist_from_array(
 2168:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2169:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2170:  class="page">'.$lt{'past'}.'</a>',
 2171:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2172:                     {legend => $lt{'keyw'}})
 2173:                .'</fieldset></div>'
 2174:             );
 2175: 
 2176: #
 2177: # Load the other essays for similarity check
 2178: #
 2179:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2180: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2181: 	    $apath=&escape($apath);
 2182: 	    $apath=~s/\W/\_/gs;
 2183:             &init_old_essays($symb,$apath,$adom,$aname);
 2184:         }
 2185:     }
 2186: 
 2187: # This is where output for one specific student would start
 2188:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2189:     $request->print(
 2190:         "\n\n"
 2191:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2192:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2193:        ."\n"
 2194:     );
 2195: 
 2196:     # Show additional functions if allowed
 2197:     if ($perm{'vgr'}) {
 2198:         $request->print(
 2199:             &Apache::loncommon::track_student_link(
 2200:                 'View recent activity',
 2201:                 $uname,$udom,'check')
 2202:            .' '
 2203:         );
 2204:     }
 2205:     if ($perm{'opa'}) {
 2206:         $request->print(
 2207:             &Apache::loncommon::pprmlink(
 2208:                 &mt('Set/Change parameters'),
 2209:                 $uname,$udom,$symb,'check'));
 2210:     }
 2211: 
 2212:     # Show Problem
 2213:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2214: 	my $mode;
 2215: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2216: 	    $mode='both';
 2217: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2218: 	    $mode='text';
 2219: 	} elsif ($env{'form.vAns'} eq 'all') {
 2220: 	    $mode='answer';
 2221: 	}
 2222: 	&Apache::lonxml::clear_problem_counter();
 2223: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2224:     }
 2225: 
 2226:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2227:     my $res_error;
 2228:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2229:     if ($res_error) {
 2230:         $request->print(&navmap_errormsg());
 2231:         return;
 2232:     }
 2233: 
 2234:     # Display student info
 2235:     $request->print(($counter == 0 ? '' : '<br />'));
 2236: 
 2237:     my $result='<div class="LC_Box">'
 2238:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2239:     $result.='<input type="hidden" name="name'.$counter.
 2240:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2241:     if ($env{'form.handgrade'} eq 'no') {
 2242:         $result.='<p class="LC_info">'
 2243:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2244:                 ."</p>\n";
 2245:     }
 2246: 
 2247:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2248:     my $fullname;
 2249:     my $col_fullnames = [];
 2250:     if ($env{'form.handgrade'} eq 'yes') {
 2251: 	(my $sub_result,$fullname,$col_fullnames)=
 2252: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2253: 				 $counter);
 2254: 	$result.=$sub_result;
 2255:     }
 2256:     $request->print($result."\n");
 2257: 
 2258:     # print student answer/submission
 2259:     # Options are (1) Handgraded submission only
 2260:     #             (2) Last submission, includes submission that is not handgraded 
 2261:     #                  (for multi-response type part)
 2262:     #             (3) Last submission plus the parts info
 2263:     #             (4) The whole record for this student
 2264: 
 2265: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2266: 	
 2267: 	my $lastsubonly;
 2268: 
 2269:         if ($$timestamp eq '') {
 2270:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2271:         } else {
 2272:             $lastsubonly =
 2273:                 '<div class="LC_grade_submissions_body">'
 2274:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2275: 
 2276: 	    my %seenparts;
 2277: 	    my @part_response_id = &flatten_responseType($responseType);
 2278: 	    foreach my $part (@part_response_id) {
 2279: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2280: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2281: 
 2282: 		my ($partid,$respid) = @{ $part };
 2283: 		my $display_part=&get_display_part($partid,$symb);
 2284: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2285: 		    if (exists($seenparts{$partid})) { next; }
 2286: 		    $seenparts{$partid}=1;
 2287:                     $request->print(
 2288:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2289:                         ' <b>'.&mt('Collaborative submission by: [_1]',
 2290:                                    '<a href="javascript:viewSubmitter(\''.
 2291:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
 2292:                                    '\');" target="_self">'.
 2293:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2294:                         '<br />');
 2295: 		    next;
 2296: 		}
 2297: 		my $responsetype = $responseType->{$partid}->{$respid};
 2298: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2299:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2300:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2301:                         ' <span class="LC_internal_info">'.
 2302:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2303:                         '</span>&nbsp; &nbsp;'.
 2304: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2305: 		    next;
 2306: 		}
 2307: 		foreach my $submission (@$string) {
 2308: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2309: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2310: 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2311: 		    # Similarity check
 2312: 		    my $similar='';
 2313:                     my ($type,$trial,$rndseed);
 2314:                     if ($hide eq 'rand') {
 2315:                         $type = 'randomizetry';
 2316:                         $trial = $record{"resource.$partid.tries"};
 2317:                         $rndseed = $record{"resource.$partid.rndseed"};
 2318:                     }
 2319: 		    if ($env{'form.checkPlag'}) {
 2320: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2321: 			    &most_similar($uname,$udom,$symb,$subval);
 2322: 			if ($osim) {
 2323: 			    $osim=int($osim*100.0);
 2324: 			    my %old_course_desc = 
 2325: 				&Apache::lonnet::coursedescription($ocrsid,
 2326: 								   {'one_time' => 1});
 2327: 
 2328:                             if ($hide eq 'anon') {
 2329:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2330:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2331:                             } else {
 2332: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2333: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2334: 				        $osim,
 2335: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2336: 				        $old_course_desc{'description'},
 2337: 				        $old_course_desc{'num'},
 2338: 				        $old_course_desc{'domain'}).
 2339: 				    '</span></h3><blockquote><i>'.
 2340: 				    &keywords_highlight($oessay).
 2341: 				    '</i></blockquote><hr />';
 2342:                             }
 2343: 			}
 2344: 		    }
 2345: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2346:                                          undef,$type,$trial,$rndseed);
 2347:                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
 2348:                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2349: 			my $display_part=&get_display_part($partid,$symb);
 2350:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2351:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2352:                             ' <span class="LC_internal_info">'.
 2353:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2354:                             '</span>&nbsp; &nbsp;';
 2355: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2356: 			if (@$files) {
 2357:                             if ($hide eq 'anon') {
 2358:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2359:                             } else {
 2360:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2361:                                             .'<br /><span class="LC_warning">';
 2362:                                 if(@$files == 1) {
 2363:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2364:                                 } else {
 2365:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2366:                                 }
 2367:                                 $lastsubonly .= '</span>';
 2368: 
 2369:                                 foreach my $file (@$files) {
 2370:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2371:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2372:                                 }
 2373:                             }
 2374: 			    $lastsubonly.='<br />';
 2375: 			}
 2376:                         if ($hide eq 'anon') {
 2377:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2378:                         } else {
 2379: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2380:                             if ($draft) {
 2381:                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2382:                             }
 2383:                             $subval =
 2384: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2385: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2386:                             if ($responsetype eq 'essay') {
 2387:                                 $subval =~ s{\n}{<br />}g;
 2388:                             }
 2389:                             $lastsubonly.=$subval."\n";
 2390:                         }
 2391: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2392: 			$lastsubonly.='</div>';
 2393: 		    }
 2394: 		}
 2395: 	    }
 2396: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2397: 	}
 2398: 	$request->print($lastsubonly);
 2399:    if ($env{'form.lastSub'} eq 'datesub') {
 2400: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2401: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2402:     }
 2403:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2404: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2405: 								 $env{'request.course.id'},
 2406: 								 $last,'.submission',
 2407: 								 'Apache::grades::keywords_highlight'));
 2408:     }
 2409: 
 2410:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2411: 	.$udom.'" />'."\n");
 2412:     # return if view submission with no grading option
 2413:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2414: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2415: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2416: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2417: 	$toGrade.='</div>'."\n";
 2418: 	if (($env{'form.command'} eq 'submission') || 
 2419: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2420: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2421: 	}
 2422: 	$request->print($toGrade);
 2423: 	return;
 2424:     } else {
 2425: 	$request->print('</div>'."\n");
 2426:     }
 2427: 
 2428:     # essay grading message center
 2429:     if ($env{'form.handgrade'} eq 'yes') {
 2430: 	my $result='<div class="LC_grade_message_center">';
 2431:     
 2432: 	$result.='<div class="LC_grade_message_center_header">'.
 2433: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2434: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2435: 	my $msgfor = $givenn.' '.$lastname;
 2436: 	if (scalar(@$col_fullnames) > 0) {
 2437: 	    my $lastone = pop(@$col_fullnames);
 2438: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2439: 	}
 2440: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2441: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2442: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2443: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2444: 	    ',\''.$msgfor.'\');" target="_self">'.
 2445: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2446: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2447: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2448: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2449: 	    '<br />&nbsp;('.
 2450: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2451: 	$result.='</div></div>';
 2452: 	$request->print($result);
 2453:     }
 2454: 
 2455:     my %seen = ();
 2456:     my @partlist;
 2457:     my @gradePartRespid;
 2458:     my @part_response_id = &flatten_responseType($responseType);
 2459:     $request->print(
 2460:         '<div class="LC_Box">'
 2461:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2462:     );
 2463:     $request->print(&gradeBox_start());
 2464:     foreach my $part_response_id (@part_response_id) {
 2465:     	my ($partid,$respid) = @{ $part_response_id };
 2466: 	my $part_resp = join('_',@{ $part_response_id });
 2467: 	next if ($seen{$partid} > 0);
 2468: 	$seen{$partid}++;
 2469: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2470: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2471: 	push(@partlist,$partid);
 2472: 	push(@gradePartRespid,$partid.'.'.$respid);
 2473: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2474:     }
 2475:     $request->print(&gradeBox_end()); # </div>
 2476:     $request->print('</div>');
 2477: 
 2478:     $request->print('<div class="LC_grade_info_links">');
 2479:     $request->print('</div>');
 2480: 
 2481:     $result='<input type="hidden" name="partlist'.$counter.
 2482: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2483:     $result.='<input type="hidden" name="gradePartRespid'.
 2484: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2485:     my $ctr = 0;
 2486:     while ($ctr < scalar(@partlist)) {
 2487: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2488: 	    $partlist[$ctr].'" />'."\n";
 2489: 	$ctr++;
 2490:     }
 2491:     $request->print($result.''."\n");
 2492: 
 2493: # Done with printing info for one student
 2494: 
 2495:     $request->print('</div>');#LC_grade_show_user
 2496: 
 2497: 
 2498:     # print end of form
 2499:     if ($counter == $total) {
 2500:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2501: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2502: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2503: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2504: 	my $ntstu ='<select name="NTSTU">'.
 2505: 	    '<option>1</option><option>2</option>'.
 2506: 	    '<option>3</option><option>5</option>'.
 2507: 	    '<option>7</option><option>10</option></select>'."\n";
 2508: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2509: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2510:         $endform.=&mt('[_1]student(s)',$ntstu);
 2511: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2512: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2513: 	    '<input type="button" value="'.&mt('Next').'" '.
 2514: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2515:         $endform.='<span class="LC_warning">'.
 2516:                   &mt('(Next and Previous (student) do not save the scores.)').
 2517:                   '</span>'."\n" ;
 2518:         $endform.="<input type='hidden' value='".&get_increment().
 2519:             "' name='increment' />";
 2520: 	$endform.='</td></tr></table></form>';
 2521: 	$endform.=&show_grading_menu_form($symb);
 2522: 	$request->print($endform);
 2523:     }
 2524:     return '';
 2525: }
 2526: 
 2527: sub check_collaborators {
 2528:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2529:     my ($result,@col_fullnames);
 2530:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2531:     foreach my $part (keys(%$handgrade)) {
 2532: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2533: 					'.maxcollaborators',
 2534: 					$symb,$udom,$uname);
 2535: 	next if ($ncol <= 0);
 2536: 	$part =~ s/\_/\./g;
 2537: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2538: 	my (@good_collaborators, @bad_collaborators);
 2539: 	foreach my $possible_collaborator
 2540: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2541: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2542: 	    next if ($possible_collaborator eq '');
 2543: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2544: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2545: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2546: 	    # Doing this grep allows 'fuzzy' specification
 2547: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2548: 			       keys(%$classlist));
 2549: 	    if (! scalar(@matches)) {
 2550: 		push(@bad_collaborators, $possible_collaborator);
 2551: 	    } else {
 2552: 		push(@good_collaborators, @matches);
 2553: 	    }
 2554: 	}
 2555: 	if (scalar(@good_collaborators) != 0) {
 2556: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2557: 	    foreach my $name (@good_collaborators) {
 2558: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2559: 		push(@col_fullnames, $givenn.' '.$lastname);
 2560: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2561: 	    }
 2562: 	    $result.='</ol><br />'."\n";
 2563: 	    my ($part)=split(/\./,$part);
 2564: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2565: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2566: 		"\n";
 2567: 	}
 2568: 	if (scalar(@bad_collaborators) > 0) {
 2569: 	    $result.='<div class="LC_warning">';
 2570: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2571: 	    $result .= '</div>';
 2572: 	}         
 2573: 	if (scalar(@bad_collaborators > $ncol)) {
 2574: 	    $result .= '<div class="LC_warning">';
 2575: 	    $result .= &mt('This student has submitted too many '.
 2576: 		'collaborators.  Maximum is [_1].',$ncol);
 2577: 	    $result .= '</div>';
 2578: 	}
 2579:     }
 2580:     return ($result,$fullname,\@col_fullnames);
 2581: }
 2582: 
 2583: #--- Retrieve the last submission for all the parts
 2584: sub get_last_submission {
 2585:     my ($returnhash)=@_;
 2586:     my (@string,$timestamp,%lasthidden);
 2587:     if ($$returnhash{'version'}) {
 2588: 	my %lasthash=();
 2589: 	my ($version);
 2590: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2591: 	    foreach my $key (sort(split(/\:/,
 2592: 					$$returnhash{$version.':keys'}))) {
 2593: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2594: 		$timestamp = 
 2595: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2596: 	    }
 2597: 	}
 2598:         my (%typeparts,%randombytry);
 2599:         my $showsurv = 
 2600:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2601:         foreach my $key (sort(keys(%lasthash))) {
 2602:             if ($key =~ /\.type$/) {
 2603:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2604:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2605:                     ($lasthash{$key} eq 'randomizetry')) {
 2606:                     my ($ign,@parts) = split(/\./,$key);
 2607:                     pop(@parts);
 2608:                     my $id = join('.',@parts);
 2609:                     if ($lasthash{$key} eq 'randomizetry') {
 2610:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2611:                     } else {
 2612:                         unless ($showsurv) {
 2613:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2614:                         }
 2615:                     }
 2616:                     delete($lasthash{$key});
 2617:                 }
 2618:             }
 2619:         }
 2620:         my @hidden = keys(%typeparts);
 2621:         my @randomize = keys(%randombytry);
 2622: 	foreach my $key (keys(%lasthash)) {
 2623: 	    next if ($key !~ /\.submission$/);
 2624:             my $hide;
 2625:             if (@hidden) {
 2626:                 foreach my $id (@hidden) {
 2627:                     if ($key =~ /^\Q$id\E/) {
 2628:                         $hide = 'anon';
 2629:                         last;
 2630:                     }
 2631:                 }
 2632:             }
 2633:             unless ($hide) {
 2634:                 if (@randomize) {
 2635:                     foreach my $id (@hidden) {
 2636:                         if ($key =~ /^\Q$id\E/) {
 2637:                             $hide = 'rand';
 2638:                             last;
 2639:                         }
 2640:                     }
 2641:                 }
 2642:             }
 2643: 	    my ($partid,$foo) = split(/submission$/,$key);
 2644: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
 2645:             push(@string, join(':', $key, $hide, $draft, (
 2646:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2647:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2648: 	}
 2649:     }
 2650:     if (!@string) {
 2651: 	$string[0] =
 2652: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2653:     }
 2654:     return (\@string,\$timestamp);
 2655: }
 2656: 
 2657: #--- High light keywords, with style choosen by user.
 2658: sub keywords_highlight {
 2659:     my $string    = shift;
 2660:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2661:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2662:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2663:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2664:     foreach my $keyword (@keylist) {
 2665: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2666:     }
 2667:     return $string;
 2668: }
 2669: 
 2670: # For Tasks provide a mechanism to display previous version for one specific student
 2671: 
 2672: sub show_previous_task_version {
 2673:     my ($request,$symb) = @_;
 2674:     if ($symb eq '') {
 2675:         $request->print(
 2676:             '<span class="LC_error">'.
 2677:             &mt('Unable to handle ambiguous references.').
 2678:             '</span>');
 2679:         return '';
 2680:     }
 2681:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2682:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2683:     if (!&canview($usec)) {
 2684:         $request->print('<span class="LC_warning">'.
 2685:                         &mt('Unable to view previous version for requested student.').
 2686:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2687:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2688:                         '</span>');
 2689:         return;
 2690:     }
 2691:     my $mode = 'both';
 2692:     my $isTask = ($symb =~/\.task$/);
 2693:     if ($isTask) {
 2694:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2695:             if ($env{'form.fullname'} eq '') {
 2696:                 $env{'form.fullname'} =
 2697:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2698:             }
 2699:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2700:             $request->print("\n\n".
 2701:                             '<div class="LC_grade_show_user">'.
 2702:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2703:                             '</h2>'."\n");
 2704:             &Apache::lonxml::clear_problem_counter();
 2705:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2706:                             {'previousversion' => $env{'form.previousversion'} }));
 2707:             $request->print("\n</div>");
 2708:         }
 2709:     }
 2710:     return;
 2711: }
 2712: 
 2713: sub choose_task_version_form {
 2714:     my ($symb,$uname,$udom,$nomenu) = @_;
 2715:     my $isTask = ($symb =~/\.task$/);
 2716:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2717:     if ($isTask) {
 2718:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2719:                                               $udom,$uname);
 2720:         if (($record{'resource.0.version'} eq '') ||
 2721:             ($record{'resource.0.version'} < 2)) {
 2722:             return ($record{'resource.0.version'},
 2723:                     $record{'resource.0.version'},$result,$js);
 2724:         } else {
 2725:             $current = $record{'resource.0.version'};
 2726:         }
 2727:         if ($env{'form.previousversion'}) {
 2728:             $displayed = $env{'form.previousversion'};
 2729:             $rowtitle = &mt('Choose another version:')
 2730:         } else {
 2731:             $displayed = $current;
 2732:             $rowtitle = &mt('Show earlier version:');
 2733:         }
 2734:         $result = '<div class="LC_left_float">';
 2735:         my $list;
 2736:         my $numversions = 0;
 2737:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2738:             if ($i == $current) {
 2739:                 if (!$env{'form.previousversion'} || $nomenu) {
 2740:                     next;
 2741:                 } else {
 2742:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2743:                     $numversions ++;
 2744:                 }
 2745:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2746:                 unless ($i == $env{'form.previousversion'}) {
 2747:                     $numversions ++;
 2748:                 }
 2749:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2750:             }
 2751:         }
 2752:         if ($numversions) {
 2753:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2754:             $result .=
 2755:                 '<form name="getprev" method="post" action=""'.
 2756:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2757:                 &Apache::loncommon::start_data_table().
 2758:                 &Apache::loncommon::start_data_table_row().
 2759:                 '<th align="left">'.$rowtitle.'</th>'.
 2760:                 '<td><select name="version">'.
 2761:                 '<option>'.&mt('Select').'</option>'.
 2762:                 $list.
 2763:                 '</select></td>'.
 2764:                 &Apache::loncommon::end_data_table_row();
 2765:             unless ($nomenu) {
 2766:                 $result .= &Apache::loncommon::start_data_table_row().
 2767:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2768:                 '<td><span class="LC_nobreak">'.
 2769:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2770:                 &mt('Yes').'</label>'.
 2771:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2772:                 '</span></td>'.
 2773:                 &Apache::loncommon::end_data_table_row();
 2774:             }
 2775:             $result .=
 2776:                 &Apache::loncommon::start_data_table_row().
 2777:                 '<th align="left">&nbsp;</th>'.
 2778:                 '<td>'.
 2779:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2780:                 '</td>'.
 2781:                 &Apache::loncommon::end_data_table_row().
 2782:                 &Apache::loncommon::end_data_table().
 2783:                 '</form>';
 2784:             $js = &previous_display_javascript($nomenu,$current);
 2785:         } elsif ($displayed && $nomenu) {
 2786:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2787:         } else {
 2788:             $result .= &mt('No previous versions to show for this student');
 2789:         }
 2790:         $result .= '</div>';
 2791:     }
 2792:     return ($current,$displayed,$result,$js);
 2793: }
 2794: 
 2795: sub previous_display_javascript {
 2796:     my ($nomenu,$current) = @_;
 2797:     my $js = <<"JSONE";
 2798: <script type="text/javascript">
 2799: // <![CDATA[
 2800: function previousVersion(uname,udom,symb) {
 2801:     var current = '$current';
 2802:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2803:     var prevstr = new RegExp("^\\\\d+\$");
 2804:     if (!prevstr.test(version)) {
 2805:         return false;
 2806:     }
 2807:     var url = '';
 2808:     if (version == current) {
 2809:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2810:     } else {
 2811:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2812:     }
 2813: JSONE
 2814:     if ($nomenu) {
 2815:         $js .= <<"JSTWO";
 2816:     document.location.href = url;
 2817: JSTWO
 2818:     } else {
 2819:         $js .= <<"JSTHREE";
 2820:     var newwin = 0;
 2821:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2822:         if (document.getprev.prevwin[i].checked == true) {
 2823:             newwin = document.getprev.prevwin[i].value;
 2824:         }
 2825:     }
 2826:     if (newwin == 1) {
 2827:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2828:         url = url+'&inhibitmenu=yes';
 2829:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2830:             previousWin = window.open(url,'',options,1);
 2831:         } else {
 2832:             previousWin.location.href = url;
 2833:         }
 2834:         previousWin.focus();
 2835:         return false;
 2836:     } else {
 2837:         document.location.href = url;
 2838:         return false;
 2839:     }
 2840: JSTHREE
 2841:     }
 2842:     $js .= <<"ENDJS";
 2843:     return false;
 2844: }
 2845: // ]]>
 2846: </script>
 2847: ENDJS
 2848: 
 2849: }
 2850: 
 2851: #--- Called from submission routine
 2852: sub processHandGrade {
 2853:     my ($request) = shift;
 2854:     my ($symb)   = &get_symb($request);
 2855:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2856:     my $button = $env{'form.gradeOpt'};
 2857:     my $ngrade = $env{'form.NCT'};
 2858:     my $ntstu  = $env{'form.NTSTU'};
 2859:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2860:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2861: 
 2862:     if ($button eq 'Save & Next') {
 2863: 	my $ctr = 0;
 2864: 	while ($ctr < $ngrade) {
 2865: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2866: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2867: 	    if ($errorflag eq 'no_score') {
 2868: 		$ctr++;
 2869: 		next;
 2870: 	    }
 2871: 	    if ($errorflag eq 'not_allowed') {
 2872:                 $request->print(
 2873:                     '<span class="LC_error">'
 2874:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2875:                    .'</span>');
 2876: 		$ctr++;
 2877: 		next;
 2878: 	    }
 2879: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2880: 	    my ($subject,$message,$msgstatus) = ('','','');
 2881: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2882:             my ($feedurl,$showsymb) =
 2883: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2884: 	    my $messagetail;
 2885: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2886: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2887: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2888: 		$subject.=' ['.$restitle.']';
 2889: 		my (@msgnum) = split(/,/,$includemsg);
 2890: 		foreach (@msgnum) {
 2891: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2892: 		}
 2893: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2894: 		if ($env{'form.withgrades'.$ctr}) {
 2895: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2896: 		    $messagetail = " for <a href=\"".
 2897: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2898: 		}
 2899: 		$msgstatus = 
 2900:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2901: 						     $message.$messagetail,
 2902:                                                      undef,$feedurl,undef,
 2903:                                                      undef,undef,$showsymb,
 2904:                                                      $restitle);
 2905: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2906: 				$msgstatus.'<br />');
 2907: 	    }
 2908: 	    if ($env{'form.collaborator'.$ctr}) {
 2909: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2910: 		foreach my $collabstr (@collabstrs) {
 2911: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2912: 		    foreach my $collaborator (@collaborators) {
 2913: 			my ($errorflag,$pts,$wgt) = 
 2914: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2915: 					   $env{'form.unamedom'.$ctr},$part);
 2916: 			if ($errorflag eq 'not_allowed') {
 2917: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2918: 			    next;
 2919: 			} elsif ($message ne '') {
 2920: 			    my ($baseurl,$showsymb) = 
 2921: 				&get_feedurl_and_symb($symb,$collaborator,
 2922: 						      $udom);
 2923: 			    if ($env{'form.withgrades'.$ctr}) {
 2924: 				$messagetail = " for <a href=\"".
 2925:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2926: 			    }
 2927: 			    $msgstatus = 
 2928: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2929: 			}
 2930: 		    }
 2931: 		}
 2932: 	    }
 2933: 	    $ctr++;
 2934: 	}
 2935:     }
 2936: 
 2937:     if ($env{'form.handgrade'} eq 'yes') {
 2938: 	# Keywords sorted in alphabatical order
 2939: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2940: 	my %keyhash = ();
 2941: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2942: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2943: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2944: 	$env{'form.keywords'} = join(' ',@keywords);
 2945: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2946: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2947: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2948: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2949: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2950: 
 2951: 	# message center - Order of message gets changed. Blank line is eliminated.
 2952: 	# New messages are saved in env for the next student.
 2953: 	# All messages are saved in nohist_handgrade.db
 2954: 	my ($ctr,$idx) = (1,1);
 2955: 	while ($ctr <= $env{'form.savemsgN'}) {
 2956: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2957: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2958: 		$idx++;
 2959: 	    }
 2960: 	    $ctr++;
 2961: 	}
 2962: 	$ctr = 0;
 2963: 	while ($ctr < $ngrade) {
 2964: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2965: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2966: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2967: 		$idx++;
 2968: 	    }
 2969: 	    $ctr++;
 2970: 	}
 2971: 	$env{'form.savemsgN'} = --$idx;
 2972: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2973: 	my $putresult = &Apache::lonnet::put
 2974: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2975:     }
 2976:     # Called by Save & Refresh from Highlight Attribute Window
 2977:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2978:     if ($env{'form.refresh'} eq 'on') {
 2979: 	my ($ctr,$total) = (0,0);
 2980: 	while ($ctr < $ngrade) {
 2981: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2982: 	    $ctr++;
 2983: 	}
 2984: 	$env{'form.NTSTU'}=$ngrade;
 2985: 	$ctr = 0;
 2986: 	while ($ctr < $total) {
 2987: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2988: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2989: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2990: 	    &submission($request,$ctr,$total-1);
 2991: 	    $ctr++;
 2992: 	}
 2993: 	return '';
 2994:     }
 2995: 
 2996: # Go directly to grade student - from submission or link from chart page
 2997:     if ($button eq 'Grade Student') {
 2998: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2999: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 3000: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3001: 	$env{'form.fullname'} = $$fullname{$processUser};
 3002: 	&submission($request,0,0);
 3003: 	return '';
 3004:     }
 3005: 
 3006:     # Get the next/previous one or group of students
 3007:     my $firststu = $env{'form.unamedom0'};
 3008:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3009:     my $ctr = 2;
 3010:     while ($laststu eq '') {
 3011: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3012: 	$ctr++;
 3013: 	$laststu = $firststu if ($ctr > $ngrade);
 3014:     }
 3015: 
 3016:     my (@parsedlist,@nextlist);
 3017:     my ($nextflg) = 0;
 3018:     foreach my $item (sort 
 3019: 	     {
 3020: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3021: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3022: 		 }
 3023: 		 return $a cmp $b;
 3024: 	     } (keys(%$fullname))) {
 3025: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3026: 	    push(@parsedlist,$item);
 3027: 	}
 3028: 	$nextflg = 1 if ($item eq $laststu);
 3029: 	if ($button eq 'Previous') {
 3030: 	    last if ($item eq $firststu);
 3031: 	    push(@parsedlist,$item);
 3032: 	}
 3033:     }
 3034:     $ctr = 0;
 3035:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3036:     my $res_error;
 3037:     my ($partlist) = &response_type($symb,\$res_error);
 3038:     if ($res_error) {
 3039:         $request->print(&navmap_errormsg());
 3040:         return;
 3041:     }
 3042:     foreach my $student (@parsedlist) {
 3043: 	my $submitonly=$env{'form.submitonly'};
 3044: 	my ($uname,$udom) = split(/:/,$student);
 3045: 	
 3046: 	if ($submitonly eq 'queued') {
 3047: 	    my %queue_status = 
 3048: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3049: 							$udom,$uname);
 3050: 	    next if (!defined($queue_status{'gradingqueue'}));
 3051: 	}
 3052: 
 3053: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3054: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3055: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3056: 	    my $submitted = 0;
 3057: 	    my $ungraded = 0;
 3058: 	    my $incorrect = 0;
 3059: 	    foreach my $item (keys(%status)) {
 3060: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3061: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3062: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3063: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3064: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3065: 		    $submitted = 0;
 3066: 		}
 3067: 	    }
 3068: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3069: 				     $submitonly eq 'incorrect' ||
 3070: 				     $submitonly eq 'graded'));
 3071: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3072: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3073: 	}
 3074: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3075: 	last if ($ctr == $ntstu);
 3076: 	$ctr++;
 3077:     }
 3078: 
 3079:     $ctr = 0;
 3080:     my $total = scalar(@nextlist)-1;
 3081: 
 3082:     foreach (sort(@nextlist)) {
 3083: 	my ($uname,$udom,$submitter) = split(/:/);
 3084: 	$env{'form.student'}  = $uname;
 3085: 	$env{'form.userdom'}  = $udom;
 3086: 	$env{'form.fullname'} = $$fullname{$_};
 3087: 	&submission($request,$ctr,$total);
 3088: 	$ctr++;
 3089:     }
 3090:     if ($total < 0) {
 3091: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3092: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3093: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3094: 	$the_end.=&show_grading_menu_form($symb);
 3095: 	$request->print($the_end);
 3096:     }
 3097:     return '';
 3098: }
 3099: 
 3100: #---- Save the score and award for each student, if changed
 3101: sub saveHandGrade {
 3102:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3103:     my @version_parts;
 3104:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3105: 					   $env{'request.course.id'});
 3106:     if (!&canmodify($usec)) { return('not_allowed'); }
 3107:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3108:     my @parts_graded;
 3109:     my %newrecord  = ();
 3110:     my ($pts,$wgt) = ('','');
 3111:     my %aggregate = ();
 3112:     my $aggregateflag = 0;
 3113:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3114:     foreach my $new_part (@parts) {
 3115: 	#collaborator ($submi may vary for different parts
 3116: 	if ($submitter && $new_part ne $part) { next; }
 3117: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3118: 	if ($dropMenu eq 'excused') {
 3119: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3120: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3121: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3122: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3123: 		}
 3124: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3125: 	    }
 3126: 	} elsif ($dropMenu eq 'reset status'
 3127: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3128: 	    foreach my $key (keys(%record)) {
 3129: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3130: 	    }
 3131: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3132: 		"$env{'user.name'}:$env{'user.domain'}";
 3133:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3134: 
 3135:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3136: 					       [$new_part]);
 3137:             my $aggtries =$totaltries;
 3138:             if ($last_resets{$new_part}) {
 3139:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3140: 					   $new_part);
 3141:             }
 3142: 
 3143:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3144:             if ($aggtries > 0) {
 3145:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3146:                 $aggregateflag = 1;
 3147:             }
 3148: 	} elsif ($dropMenu eq '') {
 3149: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3150: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3151: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3152: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3153: 		next;
 3154: 	    }
 3155: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3156: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3157: 	    my $partial= $pts/$wgt;
 3158: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3159: 		#do not update score for part if not changed.
 3160:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3161: 		next;
 3162: 	    } else {
 3163: 	        push(@parts_graded,$new_part);
 3164: 	    }
 3165: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3166: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3167: 	    }
 3168: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3169: 	    if ($partial == 0) {
 3170: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3171: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3172: 		}
 3173: 	    } else {
 3174: 		if ($record{$reckey} ne 'correct_by_override') {
 3175: 		    $newrecord{$reckey} = 'correct_by_override';
 3176: 		}
 3177: 	    }	    
 3178: 	    if ($submitter && 
 3179: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3180: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3181: 	    }
 3182: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3183: 		"$env{'user.name'}:$env{'user.domain'}";
 3184: 	}
 3185: 	# unless problem has been graded, set flag to version the submitted files
 3186: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3187: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3188: 	        $dropMenu eq 'reset status')
 3189: 	   {
 3190: 	    push(@version_parts,$new_part);
 3191: 	}
 3192:     }
 3193:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3194:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3195: 
 3196:     if (%newrecord) {
 3197:         if (@version_parts) {
 3198:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3199:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3200: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3201: 	    foreach my $new_part (@version_parts) {
 3202: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3203: 				$new_part,\%newrecord);
 3204: 	    }
 3205:         }
 3206: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3207: 				$env{'request.course.id'},$domain,$stuname);
 3208: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3209: 				     $cdom,$cnum,$domain,$stuname);
 3210:     }
 3211:     if ($aggregateflag) {
 3212:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3213: 			      $cdom,$cnum);
 3214:     }
 3215:     return ('',$pts,$wgt);
 3216: }
 3217: 
 3218: sub check_and_remove_from_queue {
 3219:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3220:     my @ungraded_parts;
 3221:     foreach my $part (@{$parts}) {
 3222: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3223: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3224: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3225: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3226: 		) {
 3227: 	    push(@ungraded_parts, $part);
 3228: 	}
 3229:     }
 3230:     if ( !@ungraded_parts ) {
 3231: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3232: 					       $cnum,$domain,$stuname);
 3233:     }
 3234: }
 3235: 
 3236: sub handback_files {
 3237:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3238:     my $portfolio_root = '/userfiles/portfolio';
 3239:     my $res_error;
 3240:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3241:     if ($res_error) {
 3242:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3243:         return;
 3244:     }
 3245:     my @handedback;
 3246:     my $file_msg;
 3247:     my @part_response_id = &flatten_responseType($responseType);
 3248:     foreach my $part_response_id (@part_response_id) {
 3249:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3250: 	my $part_resp = join('_',@{ $part_response_id });
 3251:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3252:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3253:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3254: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3255:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3256:                     my ($directory,$answer_file) = 
 3257:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3258:                     my ($answer_name,$answer_ver,$answer_ext) =
 3259: 		        &file_name_version_ext($answer_file);
 3260: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3261:                     my $getpropath = 1;
 3262:                     my ($dir_list,$listerror) =
 3263:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3264:                                                  $domain,$stuname,$getpropath);
 3265: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3266:                     # fix filename
 3267:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3268:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3269:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3270:             	                                $save_file_name);
 3271:                     if ($result !~ m|^/uploaded/|) {
 3272:                         $request->print('<br /><span class="LC_error">'.
 3273:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3274:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3275:                                         '</span>');
 3276:                     } else {
 3277:                         # mark the file as read only
 3278:                         push(@handedback,$save_file_name);
 3279: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3280: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3281: 			}
 3282:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3283: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3284: 
 3285:                     }
 3286:                     $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>'));
 3287:                 }
 3288:             }
 3289:         }
 3290:     }
 3291:     if (@handedback > 0) {
 3292:         $request->print('<br />');
 3293:         my @what = ($symb,$env{'request.course.id'},'handback');
 3294:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3295:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3296:         my ($subject,$message);
 3297:         if (scalar(@handedback) == 1) {
 3298:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3299:         } else {
 3300:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3301:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3302:         }
 3303:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3304:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3305:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3306:         my ($feedurl,$showsymb) =
 3307:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3308:         my $restitle = &Apache::lonnet::gettitle($symb);
 3309:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3310:         my $msgstatus =
 3311:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3312:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3313:                  $restitle);
 3314:         if ($msgstatus) {
 3315:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3316:         }
 3317:     }
 3318:     return;
 3319: }
 3320: 
 3321: sub get_feedurl_and_symb {
 3322:     my ($symb,$uname,$udom) = @_;
 3323:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3324:     $url = &Apache::lonnet::clutter($url);
 3325:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3326: 					$symb,$udom,$uname);
 3327:     if ($encrypturl =~ /^yes$/i) {
 3328: 	&Apache::lonenc::encrypted(\$url,1);
 3329: 	&Apache::lonenc::encrypted(\$symb,1);
 3330:     }
 3331:     return ($url,$symb);
 3332: }
 3333: 
 3334: sub get_submitted_files {
 3335:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3336:     my @files;
 3337:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3338:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3339:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3340:     	    push(@files,$file_url.$file);
 3341:         }
 3342:     }
 3343:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3344:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3345:     }
 3346:     return (\@files);
 3347: }
 3348: 
 3349: # ----------- Provides number of tries since last reset.
 3350: sub get_num_tries {
 3351:     my ($record,$last_reset,$part) = @_;
 3352:     my $timestamp = '';
 3353:     my $num_tries = 0;
 3354:     if ($$record{'version'}) {
 3355:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3356:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3357:                 $timestamp = $$record{$version.':timestamp'};
 3358:                 if ($timestamp > $last_reset) {
 3359:                     $num_tries ++;
 3360:                 } else {
 3361:                     last;
 3362:                 }
 3363:             }
 3364:         }
 3365:     }
 3366:     return $num_tries;
 3367: }
 3368: 
 3369: # ----------- Determine decrements required in aggregate totals 
 3370: sub decrement_aggs {
 3371:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3372:     my %decrement = (
 3373:                         attempts => 0,
 3374:                         users => 0,
 3375:                         correct => 0
 3376:                     );
 3377:     $decrement{'attempts'} = $aggtries;
 3378:     if ($solvedstatus =~ /^correct/) {
 3379:         $decrement{'correct'} = 1;
 3380:     }
 3381:     if ($aggtries == $totaltries) {
 3382:         $decrement{'users'} = 1;
 3383:     }
 3384:     foreach my $type (keys(%decrement)) {
 3385:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3386:     }
 3387:     return;
 3388: }
 3389: 
 3390: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3391: sub get_last_resets {
 3392:     my ($symb,$courseid,$partids) =@_;
 3393:     my %last_resets;
 3394:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3395:     my $cname = $env{'course.'.$courseid.'.num'};
 3396:     my @keys;
 3397:     foreach my $part (@{$partids}) {
 3398: 	push(@keys,"$symb\0$part\0resettime");
 3399:     }
 3400:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3401: 				     $cdom,$cname);
 3402:     foreach my $part (@{$partids}) {
 3403: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3404:     }
 3405:     return %last_resets;
 3406: }
 3407: 
 3408: # ----------- Handles creating versions for portfolio files as answers
 3409: sub version_portfiles {
 3410:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3411:     my $version_parts = join('|',@$v_flag);
 3412:     my @returned_keys;
 3413:     my $parts = join('|', @$parts_graded);
 3414:     my $portfolio_root = '/userfiles/portfolio';
 3415:     foreach my $key (keys(%$record)) {
 3416:         my $new_portfiles;
 3417:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3418:             my @versioned_portfiles;
 3419:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3420:             foreach my $file (@portfiles) {
 3421:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3422:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3423: 		my ($answer_name,$answer_ver,$answer_ext) =
 3424: 		    &file_name_version_ext($answer_file);
 3425:                 my $getpropath = 1;
 3426:                 my ($dir_list,$listerror) =
 3427:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3428:                                              $stu_name,$getpropath);
 3429:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3430:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3431:                 if ($new_answer ne 'problem getting file') {
 3432:                     push(@versioned_portfiles, $directory.$new_answer);
 3433:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3434:                         [$directory.$new_answer],
 3435:                         [$symb,$env{'request.course.id'},'graded']);
 3436:                 }
 3437:             }
 3438:             $$record{$key} = join(',',@versioned_portfiles);
 3439:             push(@returned_keys,$key);
 3440:         }
 3441:     } 
 3442:     return (@returned_keys);   
 3443: }
 3444: 
 3445: sub get_next_version {
 3446:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3447:     my $version;
 3448:     if (ref($dir_list) eq 'ARRAY') {
 3449:         foreach my $row (@{$dir_list}) {
 3450:             my ($file) = split(/\&/,$row,2);
 3451:             my ($file_name,$file_version,$file_ext) =
 3452: 	        &file_name_version_ext($file);
 3453:             if (($file_name eq $answer_name) && 
 3454: 	        ($file_ext eq $answer_ext)) {
 3455:                 # gets here if filename and extension match, 
 3456:                 # regardless of version
 3457:                 if ($file_version ne '') {
 3458:                     # a versioned file is found  so save it for later
 3459:                     if ($file_version > $version) {
 3460: 		        $version = $file_version;
 3461:                     }
 3462: 	        }
 3463:             }
 3464:         }
 3465:     }
 3466:     $version ++;
 3467:     return($version);
 3468: }
 3469: 
 3470: sub version_selected_portfile {
 3471:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3472:     my ($answer_name,$answer_ver,$answer_ext) =
 3473:         &file_name_version_ext($file_name);
 3474:     my $new_answer;
 3475:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3476:     if($env{'form.copy'} eq '-1') {
 3477:         $new_answer = 'problem getting file';
 3478:     } else {
 3479:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3480:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3481:                             $stu_name,$domain,'copy',
 3482: 		        '/portfolio'.$directory.$new_answer);
 3483:     }    
 3484:     return ($new_answer);
 3485: }
 3486: 
 3487: sub file_name_version_ext {
 3488:     my ($file)=@_;
 3489:     my @file_parts = split(/\./, $file);
 3490:     my ($name,$version,$ext);
 3491:     if (@file_parts > 1) {
 3492: 	$ext=pop(@file_parts);
 3493: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3494: 	    $version=pop(@file_parts);
 3495: 	}
 3496: 	$name=join('.',@file_parts);
 3497:     } else {
 3498: 	$name=join('.',@file_parts);
 3499:     }
 3500:     return($name,$version,$ext);
 3501: }
 3502: 
 3503: #--------------------------------------------------------------------------------------
 3504: #
 3505: #-------------------------- Next few routines handles grading by section or whole class
 3506: #
 3507: #--- Javascript to handle grading by section or whole class
 3508: sub viewgrades_js {
 3509:     my ($request) = shift;
 3510: 
 3511:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3512:     $request->print(<<VIEWJAVASCRIPT);
 3513: <script type="text/javascript" language="javascript">
 3514:    function writePoint(partid,weight,point) {
 3515: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3516: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3517: 	if (point == "textval") {
 3518: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3519: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3520: 		alert("$alertmsg"+parseFloat(point));
 3521: 		var resetbox = false;
 3522: 		for (var i=0; i<radioButton.length; i++) {
 3523: 		    if (radioButton[i].checked) {
 3524: 			textbox.value = i;
 3525: 			resetbox = true;
 3526: 		    }
 3527: 		}
 3528: 		if (!resetbox) {
 3529: 		    textbox.value = "";
 3530: 		}
 3531: 		return;
 3532: 	    }
 3533: 	    if (parseFloat(point) > parseFloat(weight)) {
 3534: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3535: 				   ") greater than the weight for the part. Accept?");
 3536: 		if (resp == false) {
 3537: 		    textbox.value = "";
 3538: 		    return;
 3539: 		}
 3540: 	    }
 3541: 	    for (var i=0; i<radioButton.length; i++) {
 3542: 		radioButton[i].checked=false;
 3543: 		if (parseFloat(point) == i) {
 3544: 		    radioButton[i].checked=true;
 3545: 		}
 3546: 	    }
 3547: 
 3548: 	} else {
 3549: 	    textbox.value = parseFloat(point);
 3550: 	}
 3551: 	for (i=0;i<document.classgrade.total.value;i++) {
 3552: 	    var user = document.classgrade["ctr"+i].value;
 3553: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3554: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3555: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3556: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3557: 	    if (saveval != "correct") {
 3558: 		scorename.value = point;
 3559: 		if (selname[0].selected != true) {
 3560: 		    selname[0].selected = true;
 3561: 		}
 3562: 	    }
 3563: 	}
 3564: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3565:     }
 3566: 
 3567:     function writeRadText(partid,weight) {
 3568: 	var selval   = document.classgrade["SELVAL_"+partid];
 3569: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3570:         var override = document.classgrade["FORCE_"+partid].checked;
 3571: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3572: 	if (selval[1].selected || selval[2].selected) {
 3573: 	    for (var i=0; i<radioButton.length; i++) {
 3574: 		radioButton[i].checked=false;
 3575: 
 3576: 	    }
 3577: 	    textbox.value = "";
 3578: 
 3579: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3580: 		var user = document.classgrade["ctr"+i].value;
 3581: 		user = user.replace(new RegExp(':', 'g'),"_");
 3582: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3583: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3584: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3585: 		if ((saveval != "correct") || override) {
 3586: 		    scorename.value = "";
 3587: 		    if (selval[1].selected) {
 3588: 			selname[1].selected = true;
 3589: 		    } else {
 3590: 			selname[2].selected = true;
 3591: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3592: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3593: 		    }
 3594: 		}
 3595: 	    }
 3596: 	} else {
 3597: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3598: 		var user = document.classgrade["ctr"+i].value;
 3599: 		user = user.replace(new RegExp(':', 'g'),"_");
 3600: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3601: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3602: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3603: 		if ((saveval != "correct") || override) {
 3604: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3605: 		    selname[0].selected = true;
 3606: 		}
 3607: 	    }
 3608: 	}	    
 3609:     }
 3610: 
 3611:     function changeSelect(partid,user) {
 3612: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3613: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3614: 	var point  = textbox.value;
 3615: 	var weight = document.classgrade["weight_"+partid].value;
 3616: 
 3617: 	if (isNaN(point) || parseFloat(point) < 0) {
 3618: 	    alert("$alertmsg"+parseFloat(point));
 3619: 	    textbox.value = "";
 3620: 	    return;
 3621: 	}
 3622: 	if (parseFloat(point) > parseFloat(weight)) {
 3623: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3624: 			       ") greater than the weight of the part. Accept?");
 3625: 	    if (resp == false) {
 3626: 		textbox.value = "";
 3627: 		return;
 3628: 	    }
 3629: 	}
 3630: 	selval[0].selected = true;
 3631:     }
 3632: 
 3633:     function changeOneScore(partid,user) {
 3634: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3635: 	if (selval[1].selected || selval[2].selected) {
 3636: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3637: 	    if (selval[2].selected) {
 3638: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3639: 	    }
 3640:         }
 3641:     }
 3642: 
 3643:     function resetEntry(numpart) {
 3644: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3645: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3646: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3647: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3648: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3649: 	    for (var i=0; i<radioButton.length; i++) {
 3650: 		radioButton[i].checked=false;
 3651: 
 3652: 	    }
 3653: 	    textbox.value = "";
 3654: 	    selval[0].selected = true;
 3655: 
 3656: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3657: 		var user = document.classgrade["ctr"+i].value;
 3658: 		user = user.replace(new RegExp(':', 'g'),"_");
 3659: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3660: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3661: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3662: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3663: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3664: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3665: 		if (saveselval == "excused") {
 3666: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3667: 		} else {
 3668: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3669: 		}
 3670: 	    }
 3671: 	}
 3672:     }
 3673: 
 3674: </script>
 3675: VIEWJAVASCRIPT
 3676: }
 3677: 
 3678: #--- show scores for a section or whole class w/ option to change/update a score
 3679: sub viewgrades {
 3680:     my ($request) = shift;
 3681:     &viewgrades_js($request);
 3682: 
 3683:     my ($symb) = &get_symb($request);
 3684:     #need to make sure we have the correct data for later EXT calls, 
 3685:     #thus invalidate the cache
 3686:     &Apache::lonnet::devalidatecourseresdata(
 3687:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3688:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3689:     &Apache::lonnet::clear_EXT_cache_status();
 3690: 
 3691:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3692:     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3693: 
 3694:     #view individual student submission form - called using Javascript viewOneStudent
 3695:     $result.=&jscriptNform($symb);
 3696: 
 3697:     #beginning of class grading form
 3698:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3699:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3700: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3701: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3702: 	&build_section_inputs().
 3703: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3704: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3705: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3706: 
 3707:     my ($common_header,$specific_header);
 3708:     if ($env{'form.section'} eq 'all') {
 3709: 	$common_header = &mt('Assign Common Grade to Class');
 3710:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3711:     } elsif ($env{'form.section'} eq 'none') {
 3712:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3713: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3714:     } else {
 3715:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3716:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3717: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3718:     }
 3719:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3720:     #radio buttons/text box for assigning points for a section or class.
 3721:     #handles different parts of a problem
 3722:     my $res_error;
 3723:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3724:     if ($res_error) {
 3725:         return &navmap_errormsg();
 3726:     }
 3727:     my %weight = ();
 3728:     my $ctsparts = 0;
 3729:     my %seen = ();
 3730:     my @part_response_id = &flatten_responseType($responseType);
 3731:     foreach my $part_response_id (@part_response_id) {
 3732:     	my ($partid,$respid) = @{ $part_response_id };
 3733: 	my $part_resp = join('_',@{ $part_response_id });
 3734: 	next if $seen{$partid};
 3735: 	$seen{$partid}++;
 3736: 	my $handgrade=$$handgrade{$part_resp};
 3737: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3738: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3739: 
 3740: 	my $display_part=&get_display_part($partid,$symb);
 3741: 	my $radio.='<table border="0"><tr>';  
 3742: 	my $ctr = 0;
 3743: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3744: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3745: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3746: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3747: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3748: 	    $ctr++;
 3749: 	}
 3750: 	$radio.='</tr></table>';
 3751: 	my $line = '<input type="text" name="TEXTVAL_'.
 3752: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3753: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3754: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3755: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3756:                 '<select name="SELVAL_'.$partid.'" '.
 3757: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 3758: 		$weight{$partid}.')"> '.
 3759: 	    '<option selected="selected"> </option>'.
 3760: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3761: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3762: 	    '</select></td>'.
 3763:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3764: 	$line.='<input type="hidden" name="partid_'.
 3765: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3766: 	$line.='<input type="hidden" name="weight_'.
 3767: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3768: 
 3769: 	$result.=
 3770: 	    &Apache::loncommon::start_data_table_row()."\n".
 3771: 	    '<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>'.
 3772: 	    &Apache::loncommon::end_data_table_row()."\n";
 3773: 	$ctsparts++;
 3774:     }
 3775:     $result.=&Apache::loncommon::end_data_table()."\n".
 3776: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3777:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3778: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3779: 
 3780:     #table listing all the students in a section/class
 3781:     #header of table
 3782:     $result.= '<h3>'.$specific_header.'</h3>'.
 3783:               &Apache::loncommon::start_data_table().
 3784: 	      &Apache::loncommon::start_data_table_header_row().
 3785: 	      '<th>'.&mt('No.').'</th>'.
 3786: 	      '<th>'.&nameUserString('header')."</th>\n";
 3787:     my $partserror;
 3788:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3789:     if ($partserror) {
 3790:         return &navmap_errormsg();
 3791:     }
 3792:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3793:     my @partids = ();
 3794:     foreach my $part (@parts) {
 3795: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3796:         my $narrowtext = &mt('Tries');
 3797: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3798: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3799: 	my ($partid) = &split_part_type($part);
 3800:         push(@partids,$partid);
 3801: 	my $display_part=&get_display_part($partid,$symb);
 3802: 	if ($display =~ /^Partial Credit Factor/) {
 3803: 	    $result.='<th>'.
 3804:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3805:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3806: 	    next;
 3807: 	    
 3808: 	} else {
 3809: 	    if ($display =~ /Problem Status/) {
 3810: 		my $grade_status_mt = &mt('Grade Status');
 3811: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3812: 	    }
 3813: 	    my $part_mt = &mt('Part:');
 3814: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3815: 	}
 3816: 
 3817: 	$result.='<th>'.$display.'</th>'."\n";
 3818:     }
 3819:     $result.=&Apache::loncommon::end_data_table_header_row();
 3820: 
 3821:     my %last_resets = 
 3822: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3823: 
 3824:     #get info for each student
 3825:     #list all the students - with points and grade status
 3826:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3827:     my $ctr = 0;
 3828:     foreach (sort 
 3829: 	     {
 3830: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3831: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3832: 		 }
 3833: 		 return $a cmp $b;
 3834: 	     } (keys(%$fullname))) {
 3835: 	$ctr++;
 3836: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3837: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3838:     }
 3839:     $result.=&Apache::loncommon::end_data_table();
 3840:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3841:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3842: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3843:     if (scalar(%$fullname) eq 0) {
 3844: 	my $colspan=3+scalar(@parts);
 3845: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3846:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3847: 	$result='<span class="LC_warning">'.
 3848: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3849: 	        $section_display, $stu_status).
 3850: 	    '</span>';
 3851:     }
 3852:     $result.=&show_grading_menu_form($symb);
 3853:     return $result;
 3854: }
 3855: 
 3856: #--- call by previous routine to display each student
 3857: sub viewstudentgrade {
 3858:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3859:     my ($uname,$udom) = split(/:/,$student);
 3860:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3861:     my %aggregates = (); 
 3862:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3863: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3864: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3865: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3866: 	'\');" target="_self">'.$fullname.'</a> '.
 3867: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3868:     $student=~s/:/_/; # colon doen't work in javascript for names
 3869:     foreach my $apart (@$parts) {
 3870: 	my ($part,$type) = &split_part_type($apart);
 3871: 	my $score=$record{"resource.$part.$type"};
 3872:         $result.='<td align="center">';
 3873:         my ($aggtries,$totaltries);
 3874:         unless (exists($aggregates{$part})) {
 3875: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3876: 
 3877: 	    $aggtries = $totaltries;
 3878:             if ($$last_resets{$part}) {  
 3879:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3880: 					   $part);
 3881:             }
 3882:             $result.='<input type="hidden" name="'.
 3883:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3884:             $result.='<input type="hidden" name="'.
 3885:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3886:             $aggregates{$part} = 1;
 3887:         }
 3888: 	if ($type eq 'awarded') {
 3889: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3890: 	    $result.='<input type="hidden" name="'.
 3891: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3892: 	    $result.='<input type="text" name="'.
 3893: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3894:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3895: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3896: 	} elsif ($type eq 'solved') {
 3897: 	    my ($status,$foo)=split(/_/,$score,2);
 3898: 	    $status = 'nothing' if ($status eq '');
 3899: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3900: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3901: 	    $result.='&nbsp;<select name="'.
 3902: 		'GD_'.$student.'_'.$part.'_solved" '.
 3903:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3904: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3905: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3906: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3907: 	    $result.="</select>&nbsp;</td>\n";
 3908: 	} else {
 3909: 	    $result.='<input type="hidden" name="'.
 3910: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3911: 		    "\n";
 3912: 	    $result.='<input type="text" name="'.
 3913: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3914: 		'value="'.$score.'" size="4" /></td>'."\n";
 3915: 	}
 3916:     }
 3917:     $result.=&Apache::loncommon::end_data_table_row();
 3918:     return $result;
 3919: }
 3920: 
 3921: #--- change scores for all the students in a section/class
 3922: #    record does not get update if unchanged
 3923: sub editgrades {
 3924:     my ($request) = @_;
 3925: 
 3926:     my ($symb)=&get_symb($request);
 3927:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3928:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3929:     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3930:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 3931: 
 3932:     my $result= &Apache::loncommon::start_data_table().
 3933: 	&Apache::loncommon::start_data_table_header_row().
 3934: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3935: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3936:     my %scoreptr = (
 3937: 		    'correct'  =>'correct_by_override',
 3938: 		    'incorrect'=>'incorrect_by_override',
 3939: 		    'excused'  =>'excused',
 3940: 		    'ungraded' =>'ungraded_attempted',
 3941:                     'credited' =>'credit_attempted',
 3942: 		    'nothing'  => '',
 3943: 		    );
 3944:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3945: 
 3946:     my (@partid);
 3947:     my %weight = ();
 3948:     my %columns = ();
 3949:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3950: 
 3951:     my $partserror;
 3952:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3953:     if ($partserror) {
 3954:         return &navmap_errormsg();
 3955:     }
 3956:     my $header;
 3957:     while ($ctr < $env{'form.totalparts'}) {
 3958: 	my $partid = $env{'form.partid_'.$ctr};
 3959: 	push(@partid,$partid);
 3960: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3961: 	$ctr++;
 3962:     }
 3963:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3964:     foreach my $partid (@partid) {
 3965: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3966: 	    '<th align="center">'.&mt('New Score').'</th>';
 3967: 	$columns{$partid}=2;
 3968: 	foreach my $stores (@parts) {
 3969: 	    my ($part,$type) = &split_part_type($stores);
 3970: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3971: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3972: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3973: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3974:             my $narrowtext = &mt('Tries');
 3975: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3976: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3977: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3978: 	    $columns{$partid}+=2;
 3979: 	}
 3980:     }
 3981:     foreach my $partid (@partid) {
 3982: 	my $display_part=&get_display_part($partid,$symb);
 3983: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3984: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3985: 	    '</th>';
 3986: 
 3987:     }
 3988:     $result .= &Apache::loncommon::end_data_table_header_row().
 3989: 	&Apache::loncommon::start_data_table_header_row().
 3990: 	$header.
 3991: 	&Apache::loncommon::end_data_table_header_row();
 3992:     my @noupdate;
 3993:     my ($updateCtr,$noupdateCtr) = (1,1);
 3994:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3995: 	my $line;
 3996: 	my $user = $env{'form.ctr'.$i};
 3997: 	my ($uname,$udom)=split(/:/,$user);
 3998: 	my %newrecord;
 3999: 	my $updateflag = 0;
 4000: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4001: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4002: 	if (!&canmodify($usec)) {
 4003: 	    my $numcols=scalar(@partid)*4+2;
 4004: 	    push(@noupdate,
 4005: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 4006: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 4007: 	    next;
 4008: 	}
 4009:         my %aggregate = ();
 4010:         my $aggregateflag = 0;
 4011: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4012: 	foreach (@partid) {
 4013: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4014: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4015: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4016: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4017: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4018: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4019: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4020: 	    my $score;
 4021: 	    if ($partial eq '') {
 4022: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4023: 	    } elsif ($partial > 0) {
 4024: 		$score = 'correct_by_override';
 4025: 	    } elsif ($partial == 0) {
 4026: 		$score = 'incorrect_by_override';
 4027: 	    }
 4028: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4029: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4030: 
 4031: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4032: 		"$env{'user.name'}:$env{'user.domain'}";
 4033: 	    if ($dropMenu eq 'reset status' &&
 4034: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4035: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4036: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4037: 		$newrecord{'resource.'.$_.'.award'} = '';
 4038: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4039: 		$updateflag = 1;
 4040:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4041:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4042:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4043:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4044:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4045:                     $aggregateflag = 1;
 4046:                 }
 4047: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4048: 		$updateflag = 1;
 4049: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4050: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4051: 		$rec_update++;
 4052: 	    }
 4053: 
 4054: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4055: 		'<td align="center">'.$awarded.
 4056: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4057: 
 4058: 
 4059: 	    my $partid=$_;
 4060: 	    foreach my $stores (@parts) {
 4061: 		my ($part,$type) = &split_part_type($stores);
 4062: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4063: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4064: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4065: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4066: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4067: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4068: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4069: 		    $updateflag=1;
 4070: 		}
 4071: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4072: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4073: 	    }
 4074: 	}
 4075: 	$line.="\n";
 4076: 
 4077: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4078: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4079: 
 4080: 	if ($updateflag) {
 4081: 	    $count++;
 4082: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4083: 				    $udom,$uname);
 4084: 
 4085: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4086: 					      $cnum,$udom,$uname)) {
 4087: 		# need to figure out if should be in queue.
 4088: 		my %record =  
 4089: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4090: 					     $udom,$uname);
 4091: 		my $all_graded = 1;
 4092: 		my $none_graded = 1;
 4093: 		foreach my $part (@parts) {
 4094: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4095: 			$all_graded = 0;
 4096: 		    } else {
 4097: 			$none_graded = 0;
 4098: 		    }
 4099: 		}
 4100: 
 4101: 		if ($all_graded || $none_graded) {
 4102: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4103: 							   $symb,$cdom,$cnum,
 4104: 							   $udom,$uname);
 4105: 		}
 4106: 	    }
 4107: 
 4108: 	    $result.=&Apache::loncommon::start_data_table_row().
 4109: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4110: 		&Apache::loncommon::end_data_table_row();
 4111: 	    $updateCtr++;
 4112: 	} else {
 4113: 	    push(@noupdate,
 4114: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4115: 	    $noupdateCtr++;
 4116: 	}
 4117:         if ($aggregateflag) {
 4118:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4119: 				  $cdom,$cnum);
 4120:         }
 4121:     }
 4122:     if (@noupdate) {
 4123: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4124: 	my $numcols=scalar(@partid)*4+2;
 4125: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4126: 	    '<td align="center" colspan="'.$numcols.'">'.
 4127: 	    &mt('No Changes Occurred For the Students Below').
 4128: 	    '</td>'.
 4129: 	    &Apache::loncommon::end_data_table_row();
 4130: 	foreach my $line (@noupdate) {
 4131: 	    $result.=
 4132: 		&Apache::loncommon::start_data_table_row().
 4133: 		$line.
 4134: 		&Apache::loncommon::end_data_table_row();
 4135: 	}
 4136:     }
 4137:     $result .= &Apache::loncommon::end_data_table().
 4138: 	&show_grading_menu_form($symb);
 4139:     my $msg = '<p><b>'.
 4140: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4141: 	    $rec_update,$count).'</b><br />'.
 4142: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4143: 	'</b></p>';
 4144:     return $title.$msg.$result;
 4145: }
 4146: 
 4147: sub split_part_type {
 4148:     my ($partstr) = @_;
 4149:     my ($temp,@allparts)=split(/_/,$partstr);
 4150:     my $type=pop(@allparts);
 4151:     my $part=join('_',@allparts);
 4152:     return ($part,$type);
 4153: }
 4154: 
 4155: #------------- end of section for handling grading by section/class ---------
 4156: #
 4157: #----------------------------------------------------------------------------
 4158: 
 4159: 
 4160: #----------------------------------------------------------------------------
 4161: #
 4162: #-------------------------- Next few routines handles grading by csv upload
 4163: #
 4164: #--- Javascript to handle csv upload
 4165: sub csvupload_javascript_reverse_associate {
 4166:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4167:     my $error2=&mt('You need to specify at least one grading field');
 4168:   return(<<ENDPICK);
 4169:   function verify(vf) {
 4170:     var foundsomething=0;
 4171:     var founduname=0;
 4172:     var foundID=0;
 4173:     for (i=0;i<=vf.nfields.value;i++) {
 4174:       tw=eval('vf.f'+i+'.selectedIndex');
 4175:       if (i==0 && tw!=0) { foundID=1; }
 4176:       if (i==1 && tw!=0) { founduname=1; }
 4177:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4178:     }
 4179:     if (founduname==0 && foundID==0) {
 4180: 	alert('$error1');
 4181: 	return;
 4182:     }
 4183:     if (foundsomething==0) {
 4184: 	alert('$error2');
 4185: 	return;
 4186:     }
 4187:     vf.submit();
 4188:   }
 4189:   function flip(vf,tf) {
 4190:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4191:     var i;
 4192:     for (i=0;i<=vf.nfields.value;i++) {
 4193:       //can not pick the same destination field for both name and domain
 4194:       if (((i ==0)||(i ==1)) && 
 4195:           ((tf==0)||(tf==1)) && 
 4196:           (i!=tf) &&
 4197:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4198:         eval('vf.f'+i+'.selectedIndex=0;')
 4199:       }
 4200:     }
 4201:   }
 4202: ENDPICK
 4203: }
 4204: 
 4205: sub csvupload_javascript_forward_associate {
 4206:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4207:     my $error2=&mt('You need to specify at least one grading field');
 4208:   return(<<ENDPICK);
 4209:   function verify(vf) {
 4210:     var foundsomething=0;
 4211:     var founduname=0;
 4212:     var foundID=0;
 4213:     for (i=0;i<=vf.nfields.value;i++) {
 4214:       tw=eval('vf.f'+i+'.selectedIndex');
 4215:       if (tw==1) { foundID=1; }
 4216:       if (tw==2) { founduname=1; }
 4217:       if (tw>3) { foundsomething=1; }
 4218:     }
 4219:     if (founduname==0 && foundID==0) {
 4220: 	alert('$error1');
 4221: 	return;
 4222:     }
 4223:     if (foundsomething==0) {
 4224: 	alert('$error2');
 4225: 	return;
 4226:     }
 4227:     vf.submit();
 4228:   }
 4229:   function flip(vf,tf) {
 4230:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4231:     var i;
 4232:     //can not pick the same destination field twice
 4233:     for (i=0;i<=vf.nfields.value;i++) {
 4234:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4235:         eval('vf.f'+i+'.selectedIndex=0;')
 4236:       }
 4237:     }
 4238:   }
 4239: ENDPICK
 4240: }
 4241: 
 4242: sub csvuploadmap_header {
 4243:     my ($request,$symb,$datatoken,$distotal)= @_;
 4244:     my $javascript;
 4245:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4246: 	$javascript=&csvupload_javascript_reverse_associate();
 4247:     } else {
 4248: 	$javascript=&csvupload_javascript_forward_associate();
 4249:     }
 4250: 
 4251:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4252:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4253:     my $ignore=&mt('Ignore First Line');
 4254:     $symb = &Apache::lonenc::check_encrypt($symb);
 4255:     $request->print(<<ENDPICK);
 4256: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4257: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4258: $result
 4259: <hr />
 4260: <h3>Identify fields</h3>
 4261: Total number of records found in file: $distotal <hr />
 4262: Enter as many fields as you can. The system will inform you and bring you back
 4263: to this page if the data selected is insufficient to run your class.<hr />
 4264: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4265: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4266: <input type="hidden" name="associate"  value="" />
 4267: <input type="hidden" name="phase"      value="three" />
 4268: <input type="hidden" name="datatoken"  value="$datatoken" />
 4269: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4270: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4271: <input type="hidden" name="upfile_associate" 
 4272:                                        value="$env{'form.upfile_associate'}" />
 4273: <input type="hidden" name="symb"       value="$symb" />
 4274: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4275: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4276: <input type="hidden" name="command"    value="csvuploadoptions" />
 4277: <hr />
 4278: <script type="text/javascript" language="Javascript">
 4279: $javascript
 4280: </script>
 4281: ENDPICK
 4282:     return '';
 4283: 
 4284: }
 4285: 
 4286: sub csvupload_fields {
 4287:     my ($symb,$errorref) = @_;
 4288:     my (@parts) = &getpartlist($symb,$errorref);
 4289:     if (ref($errorref)) {
 4290:         if ($$errorref) {
 4291:             return;
 4292:         }
 4293:     }
 4294: 
 4295:     my @fields=(['ID','Student/Employee ID'],
 4296: 		['username','Student Username'],
 4297: 		['domain','Student Domain']);
 4298:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4299:     foreach my $part (sort(@parts)) {
 4300: 	my @datum;
 4301: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4302: 	my $name=$part;
 4303: 	if  (!$display) { $display = $name; }
 4304: 	@datum=($name,$display);
 4305: 	if ($name=~/^stores_(.*)_awarded/) {
 4306: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4307: 	}
 4308: 	push(@fields,\@datum);
 4309:     }
 4310:     return (@fields);
 4311: }
 4312: 
 4313: sub csvuploadmap_footer {
 4314:     my ($request,$i,$keyfields) =@_;
 4315:     my $buttontext = &mt('Assign Grades');
 4316:     $request->print(<<ENDPICK);
 4317: </table>
 4318: <input type="hidden" name="nfields" value="$i" />
 4319: <input type="hidden" name="keyfields" value="$keyfields" />
 4320: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4321: </form>
 4322: ENDPICK
 4323: }
 4324: 
 4325: sub checkforfile_js {
 4326:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4327:     my $result =<<CSVFORMJS;
 4328: <script type="text/javascript" language="javascript">
 4329:     function checkUpload(formname) {
 4330: 	if (formname.upfile.value == "") {
 4331: 	    alert("$alertmsg");
 4332: 	    return false;
 4333: 	}
 4334: 	formname.submit();
 4335:     }
 4336:     </script>
 4337: CSVFORMJS
 4338:     return $result;
 4339: }
 4340: 
 4341: sub upcsvScores_form {
 4342:     my ($request) = shift;
 4343:     my ($symb)=&get_symb($request);
 4344:     if (!$symb) {return '';}
 4345:     my $result=&checkforfile_js();
 4346:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4347:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4348:     $result.=$table;
 4349:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4350:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4351:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4352: 	'</b></td></tr>'."\n";
 4353:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4354:     my $upload=&mt("Upload Scores");
 4355:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4356:     my $ignore=&mt('Ignore First Line');
 4357:     $symb = &Apache::lonenc::check_encrypt($symb);
 4358:     $result.=<<ENDUPFORM;
 4359: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4360: <input type="hidden" name="symb" value="$symb" />
 4361: <input type="hidden" name="command" value="csvuploadmap" />
 4362: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4363: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4364: $upfile_select
 4365: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4366: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4367: </form>
 4368: ENDUPFORM
 4369:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4370:                            &mt("How do I create a CSV file from a spreadsheet"))
 4371:     .'</td></tr></table>'."\n";
 4372:     $result.='</td></tr></table><br /><br />'."\n";
 4373:     $result.=&show_grading_menu_form($symb);
 4374:     return $result;
 4375: }
 4376: 
 4377: 
 4378: sub csvuploadmap {
 4379:     my ($request)= @_;
 4380:     my ($symb)=&get_symb($request);
 4381:     if (!$symb) {return '';}
 4382: 
 4383:     my $datatoken;
 4384:     if (!$env{'form.datatoken'}) {
 4385: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4386:     } else {
 4387: 	$datatoken=$env{'form.datatoken'};
 4388: 	&Apache::loncommon::load_tmp_file($request);
 4389:     }
 4390:     my @records=&Apache::loncommon::upfile_record_sep();
 4391:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4392:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4393:     my ($i,$keyfields);
 4394:     if (@records) {
 4395:         my $fieldserror;
 4396: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4397:         if ($fieldserror) {
 4398:             $request->print(&navmap_errormsg());
 4399:             return;
 4400:         }
 4401: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4402: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4403: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4404: 							  \@fields);
 4405: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4406: 	    chop($keyfields);
 4407: 	} else {
 4408: 	    unshift(@fields,['none','']);
 4409: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4410: 							    \@fields);
 4411:             foreach my $rec (@records) {
 4412:                 my %temp = &Apache::loncommon::record_sep($rec);
 4413:                 if (%temp) {
 4414:                     $keyfields=join(',',sort(keys(%temp)));
 4415:                     last;
 4416:                 }
 4417:             }
 4418: 	}
 4419:     }
 4420:     &csvuploadmap_footer($request,$i,$keyfields);
 4421:     $request->print(&show_grading_menu_form($symb));
 4422: 
 4423:     return '';
 4424: }
 4425: 
 4426: sub csvuploadoptions {
 4427:     my ($request)= @_;
 4428:     my ($symb)=&get_symb($request);
 4429:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4430:     my $ignore=&mt('Ignore First Line');
 4431:     $request->print(<<ENDPICK);
 4432: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4433: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4434: <input type="hidden" name="command"    value="csvuploadassign" />
 4435: <!--
 4436: <p>
 4437: <label>
 4438:    <input type="checkbox" name="show_full_results" />
 4439:    Show a table of all changes
 4440: </label>
 4441: </p>
 4442: -->
 4443: <p>
 4444: <label>
 4445:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4446:    Overwrite any existing score
 4447: </label>
 4448: </p>
 4449: ENDPICK
 4450:     my %fields=&get_fields();
 4451:     if (!defined($fields{'domain'})) {
 4452: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4453: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4454:     }
 4455:     foreach my $key (sort(keys(%env))) {
 4456: 	if ($key !~ /^form\.(.*)$/) { next; }
 4457: 	my $cleankey=$1;
 4458: 	if ($cleankey eq 'command') { next; }
 4459: 	$request->print('<input type="hidden" name="'.$cleankey.
 4460: 			'"  value="'.$env{$key}.'" />'."\n");
 4461:     }
 4462:     # FIXME do a check for any duplicated user ids...
 4463:     # FIXME do a check for any invalid user ids?...
 4464:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4465: <hr /></form>'."\n");
 4466:     $request->print(&show_grading_menu_form($symb));
 4467:     return '';
 4468: }
 4469: 
 4470: sub get_fields {
 4471:     my %fields;
 4472:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4473:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4474: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4475: 	    if ($env{'form.f'.$i} ne 'none') {
 4476: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4477: 	    }
 4478: 	} else {
 4479: 	    if ($env{'form.f'.$i} ne 'none') {
 4480: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4481: 	    }
 4482: 	}
 4483:     }
 4484:     return %fields;
 4485: }
 4486: 
 4487: sub csvuploadassign {
 4488:     my ($request)= @_;
 4489:     my ($symb)=&get_symb($request);
 4490:     if (!$symb) {return '';}
 4491:     my $error_msg = '';
 4492:     &Apache::loncommon::load_tmp_file($request);
 4493:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4494:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4495:     my %fields=&get_fields();
 4496:     $request->print('<h3>Assigning Grades</h3>');
 4497:     my $courseid=$env{'request.course.id'};
 4498:     my ($classlist) = &getclasslist('all',0);
 4499:     my @notallowed;
 4500:     my @skipped;
 4501:     my @warnings;
 4502:     my $countdone=0;
 4503:     foreach my $grade (@gradedata) {
 4504: 	my %entries=&Apache::loncommon::record_sep($grade);
 4505: 	my $domain;
 4506: 	if ($entries{$fields{'domain'}}) {
 4507: 	    $domain=$entries{$fields{'domain'}};
 4508: 	} else {
 4509: 	    $domain=$env{'form.default_domain'};
 4510: 	}
 4511: 	$domain=~s/\s//g;
 4512: 	my $username=$entries{$fields{'username'}};
 4513: 	$username=~s/\s//g;
 4514: 	if (!$username) {
 4515: 	    my $id=$entries{$fields{'ID'}};
 4516: 	    $id=~s/\s//g;
 4517: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4518: 	    $username=$ids{$id};
 4519: 	}
 4520: 	if (!exists($$classlist{"$username:$domain"})) {
 4521: 	    my $id=$entries{$fields{'ID'}};
 4522: 	    $id=~s/\s//g;
 4523: 	    if ($id) {
 4524: 		push(@skipped,"$id:$domain");
 4525: 	    } else {
 4526: 		push(@skipped,"$username:$domain");
 4527: 	    }
 4528: 	    next;
 4529: 	}
 4530: 	my $usec=$classlist->{"$username:$domain"}[5];
 4531: 	if (!&canmodify($usec)) {
 4532: 	    push(@notallowed,"$username:$domain");
 4533: 	    next;
 4534: 	}
 4535: 	my %points;
 4536: 	my %grades;
 4537: 	foreach my $dest (keys(%fields)) {
 4538: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4539: 		$dest eq 'domain') { next; }
 4540: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4541: 	    if ($dest=~/stores_(.*)_points/) {
 4542: 		my $part=$1;
 4543: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4544: 					      $symb,$domain,$username);
 4545:                 if ($wgt) {
 4546:                     $entries{$fields{$dest}}=~s/\s//g;
 4547:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4548:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4549:                                           : 'correct_by_override';
 4550:                     if ($pcr>1) {
 4551:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4552:                     }
 4553:                     $grades{"resource.$part.awarded"}=$pcr;
 4554:                     $grades{"resource.$part.solved"}=$award;
 4555:                     $points{$part}=1;
 4556:                 } else {
 4557:                     $error_msg = "<br />" .
 4558:                         &mt("Some point values were assigned"
 4559:                             ." for problems with a weight "
 4560:                             ."of zero. These values were "
 4561:                             ."ignored.");
 4562:                 }
 4563: 	    } else {
 4564: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4565: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4566: 		my $store_key=$dest;
 4567: 		$store_key=~s/^stores/resource/;
 4568: 		$store_key=~s/_/\./g;
 4569: 		$grades{$store_key}=$entries{$fields{$dest}};
 4570: 	    }
 4571: 	}
 4572: 	if (! %grades) { 
 4573:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4574:         } else {
 4575: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4576: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4577: 					   $env{'request.course.id'},
 4578: 					   $domain,$username);
 4579: 	   if ($result eq 'ok') {
 4580: 	      $request->print('.');
 4581: # Remove from grading queue
 4582:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4583:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4584:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4585:                                              $domain,$username);
 4586: 	   } else {
 4587: 	      $request->print("<p><span class=\"LC_error\">".
 4588:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4589:                                   "$username:$domain",$result)."</span></p>");
 4590: 	   }
 4591: 	   $request->rflush();
 4592: 	   $countdone++;
 4593:         }
 4594:     }
 4595:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4596:     if (@warnings) {
 4597:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4598:         $request->print(join(', ',@warnings));
 4599:     }
 4600:     if (@skipped) {
 4601: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4602:         $request->print(join(', ',@skipped));
 4603:     }
 4604:     if (@notallowed) {
 4605: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4606: 	$request->print(join(', ',@notallowed));
 4607:     }
 4608:     $request->print("<br />\n");
 4609:     $request->print(&show_grading_menu_form($symb));
 4610:     return $error_msg;
 4611: }
 4612: #------------- end of section for handling csv file upload ---------
 4613: #
 4614: #-------------------------------------------------------------------
 4615: #
 4616: #-------------- Next few routines handle grading by page/sequence
 4617: #
 4618: #--- Select a page/sequence and a student to grade
 4619: sub pickStudentPage {
 4620:     my ($request) = shift;
 4621: 
 4622:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4623:     $request->print(<<LISTJAVASCRIPT);
 4624: <script type="text/javascript" language="javascript">
 4625: 
 4626: function checkPickOne(formname) {
 4627:     if (radioSelection(formname.student) == null) {
 4628: 	alert("$alertmsg");
 4629: 	return;
 4630:     }
 4631:     ptr = pullDownSelection(formname.selectpage);
 4632:     formname.page.value = formname["page"+ptr].value;
 4633:     formname.title.value = formname["title"+ptr].value;
 4634:     formname.submit();
 4635: }
 4636: 
 4637: </script>
 4638: LISTJAVASCRIPT
 4639:     &commonJSfunctions($request);
 4640:     my ($symb) = &get_symb($request);
 4641:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4642:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4643:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4644: 
 4645:     my $result='<h3><span class="LC_info">&nbsp;'.
 4646: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4647: 
 4648:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4649:     my $map_error;
 4650:     my ($titles,$symbx) = &getSymbMap($map_error);
 4651:     if ($map_error) {
 4652:         $request->print(&navmap_errormsg());
 4653:         return; 
 4654:     }
 4655:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4656: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4657: #    my $type=($curpage =~ /\.(page|sequence)/);
 4658:     my $select = '<select name="selectpage">'."\n";
 4659:     my $ctr=0;
 4660:     foreach (@$titles) {
 4661: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4662: 	$select.='<option value="'.$ctr.'" '.
 4663: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4664: 	    '>'.$showtitle.'</option>'."\n";
 4665: 	$ctr++;
 4666:     }
 4667:     $select.= '</select>';
 4668:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4669: 
 4670:     $ctr=0;
 4671:     foreach (@$titles) {
 4672: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4673: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4674: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4675: 	$ctr++;
 4676:     }
 4677:     $result.='<input type="hidden" name="page" />'."\n".
 4678: 	'<input type="hidden" name="title" />'."\n";
 4679: 
 4680:     my $options =
 4681: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4682: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4683:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4684: 
 4685:     $options =
 4686: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4687: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4688: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4689:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4690:     
 4691:     $result.=&build_section_inputs();
 4692:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4693:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4694: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4695: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4696: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4697: 
 4698:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4699: 
 4700:     $result.='&nbsp;<input type="button" '.
 4701:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4702: 
 4703:     $request->print($result);
 4704: 
 4705:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4706: 	&Apache::loncommon::start_data_table().
 4707: 	&Apache::loncommon::start_data_table_header_row().
 4708: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4709: 	'<th>'.&nameUserString('header').'</th>'.
 4710: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4711: 	'<th>'.&nameUserString('header').'</th>'.
 4712: 	&Apache::loncommon::end_data_table_header_row();
 4713:  
 4714:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4715:     my $ptr = 1;
 4716:     foreach my $student (sort 
 4717: 			 {
 4718: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4719: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4720: 			     }
 4721: 			     return $a cmp $b;
 4722: 			 } (keys(%$fullname))) {
 4723: 	my ($uname,$udom) = split(/:/,$student);
 4724: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4725:                                   : '</td>');
 4726: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4727: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4728: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4729: 	$studentTable.=
 4730: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4731:                          : '');
 4732: 	$ptr++;
 4733:     }
 4734:     if ($ptr%2 == 0) {
 4735: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4736: 	    &Apache::loncommon::end_data_table_row();
 4737:     }
 4738:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4739:     $studentTable.='<input type="button" '.
 4740:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4741: 
 4742:     $studentTable.=&show_grading_menu_form($symb);
 4743:     $request->print($studentTable);
 4744: 
 4745:     return '';
 4746: }
 4747: 
 4748: sub getSymbMap {
 4749:     my ($map_error) = @_;
 4750:     my $navmap = Apache::lonnavmaps::navmap->new();
 4751:     unless (ref($navmap)) {
 4752:         if (ref($map_error)) {
 4753:             $$map_error = 'navmap';
 4754:         }
 4755:         return;
 4756:     }
 4757:     my %symbx = ();
 4758:     my @titles = ();
 4759:     my $minder = 0;
 4760: 
 4761:     # Gather every sequence that has problems.
 4762:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4763: 					       1,0,1);
 4764:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4765: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4766: 	    my $title = $minder.'.'.
 4767: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4768: 	    push(@titles, $title); # minder in case two titles are identical
 4769: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4770: 	    $minder++;
 4771: 	}
 4772:     }
 4773:     return \@titles,\%symbx;
 4774: }
 4775: 
 4776: #
 4777: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4778: sub displayPage {
 4779:     my ($request) = shift;
 4780: 
 4781:     my ($symb) = &get_symb($request);
 4782:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4783:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4784:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4785:     my $pageTitle = $env{'form.page'};
 4786:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4787:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4788:     my $usec=$classlist->{$env{'form.student'}}[5];
 4789: 
 4790:     #need to make sure we have the correct data for later EXT calls, 
 4791:     #thus invalidate the cache
 4792:     &Apache::lonnet::devalidatecourseresdata(
 4793:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4794:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4795:     &Apache::lonnet::clear_EXT_cache_status();
 4796: 
 4797:     if (!&canview($usec)) {
 4798: 	$request->print('<span class="LC_warning">'.
 4799:                         &mt('Unable to view requested student. ([_1])',
 4800:                             $env{'form.student'}).
 4801:                         '</span>');
 4802:         $request->print(&show_grading_menu_form($symb));
 4803:         return;
 4804:     }
 4805:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4806:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4807: 	'</h3>'."\n";
 4808:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4809:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4810: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4811:     } else {
 4812: 	delete($env{'form.CODE'});
 4813:     }
 4814:     &sub_page_js($request);
 4815:     $request->print($result);
 4816: 
 4817:     my $navmap = Apache::lonnavmaps::navmap->new();
 4818:     unless (ref($navmap)) {
 4819:         $request->print(&navmap_errormsg());
 4820:         $request->print(&show_grading_menu_form($symb));
 4821:         return;
 4822:     }
 4823:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4824:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4825:     if (!$map) {
 4826: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4827: 	$request->print(&show_grading_menu_form($symb));
 4828: 	return; 
 4829:     }
 4830:     my $iterator = $navmap->getIterator($map->map_start(),
 4831: 					$map->map_finish());
 4832: 
 4833:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4834: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4835: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4836: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4837: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4838: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4839: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4840: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4841: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4842: 
 4843:     if (defined($env{'form.CODE'})) {
 4844: 	$studentTable.=
 4845: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4846:     }
 4847:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4848: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4849: 
 4850:     $studentTable.='&nbsp;<span class="LC_info">'.
 4851:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4852:         '</span>'."\n".
 4853: 	&Apache::loncommon::start_data_table().
 4854: 	&Apache::loncommon::start_data_table_header_row().
 4855: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4856: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4857: 	&Apache::loncommon::end_data_table_header_row();
 4858: 
 4859:     &Apache::lonxml::clear_problem_counter();
 4860:     my ($depth,$question,$prob) = (1,1,1);
 4861:     $iterator->next(); # skip the first BEGIN_MAP
 4862:     my $curRes = $iterator->next(); # for "current resource"
 4863:     while ($depth > 0) {
 4864:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4865:         if($curRes == $iterator->END_MAP) { $depth--; }
 4866: 
 4867:         if (ref($curRes) && $curRes->is_problem()) {
 4868: 	    my $parts = $curRes->parts();
 4869:             my $title = $curRes->compTitle();
 4870: 	    my $symbx = $curRes->symb();
 4871: 	    $studentTable.=
 4872: 		&Apache::loncommon::start_data_table_row().
 4873: 		'<td align="center" valign="top" >'.$prob.
 4874: 		(scalar(@{$parts}) == 1 ? '' 
 4875: 		                        : '<br />('.&mt('[_1]parts',
 4876: 							scalar(@{$parts}).'&nbsp;').')'
 4877: 		 ).
 4878: 		 '</td>';
 4879: 	    $studentTable.='<td valign="top">';
 4880: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4881: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4882: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4883: 					     undef,'both',\%form);
 4884: 	    } else {
 4885: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4886: 		$companswer =~ s|<form(.*?)>||g;
 4887: 		$companswer =~ s|</form>||g;
 4888: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4889: #		    $companswer =~ s/$1/ /ms;
 4890: #		    $request->print('match='.$1."<br />\n");
 4891: #		}
 4892: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4893: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4894: 	    }
 4895: 
 4896: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4897: 
 4898: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4899: 		if ($record{'version'} eq '') {
 4900: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4901: 		} else {
 4902: 		    my %responseType = ();
 4903: 		    foreach my $partid (@{$parts}) {
 4904: 			my @responseIds =$curRes->responseIds($partid);
 4905: 			my @responseType =$curRes->responseType($partid);
 4906: 			my %responseIds;
 4907: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4908: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4909: 			}
 4910: 			$responseType{$partid} = \%responseIds;
 4911: 		    }
 4912: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4913: 
 4914: 		}
 4915: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4916: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4917: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4918: 									$env{'request.course.id'},
 4919: 									'','.submission');
 4920:  
 4921: 	    }
 4922: 	    if (&canmodify($usec)) {
 4923:             $studentTable.=&gradeBox_start();
 4924: 		foreach my $partid (@{$parts}) {
 4925: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4926: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4927: 		    $question++;
 4928: 		}
 4929:             $studentTable.=&gradeBox_end();
 4930: 		$prob++;
 4931: 	    }
 4932: 	    $studentTable.='</td></tr>';
 4933: 
 4934: 	}
 4935:         $curRes = $iterator->next();
 4936:     }
 4937: 
 4938:     $studentTable.=
 4939:         '</table>'."\n".
 4940:         '<input type="button" value="'.&mt('Save').'" '.
 4941:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4942:         '</form>'."\n";
 4943:     $studentTable.=&show_grading_menu_form($symb);
 4944:     $request->print($studentTable);
 4945: 
 4946:     return '';
 4947: }
 4948: 
 4949: sub displaySubByDates {
 4950:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4951:     my $isCODE=0;
 4952:     my $isTask = ($symb =~/\.task$/);
 4953:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4954:     my $studentTable=&Apache::loncommon::start_data_table().
 4955: 	&Apache::loncommon::start_data_table_header_row().
 4956: 	'<th>'.&mt('Date/Time').'</th>'.
 4957: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4958:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4959: 	'<th>'.&mt('Submission').'</th>'.
 4960: 	'<th>'.&mt('Status').'</th>'.
 4961: 	&Apache::loncommon::end_data_table_header_row();
 4962:     my ($version);
 4963:     my %mark;
 4964:     my %orders;
 4965:     $mark{'correct_by_student'} = $checkIcon;
 4966:     if (!exists($$record{'1:timestamp'})) {
 4967: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4968:     }
 4969: 
 4970:     my $interaction;
 4971:     my $no_increment = 1;
 4972:     my %lastrndseed;
 4973:     for ($version=1;$version<=$$record{'version'};$version++) {
 4974: 	my $timestamp = 
 4975: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4976: 	if (exists($$record{$version.':resource.0.version'})) {
 4977: 	    $interaction = $$record{$version.':resource.0.version'};
 4978: 	}
 4979:         if ($isTask && $env{'form.previousversion'}) {
 4980:             next unless ($interaction == $env{'form.previousversion'});
 4981:         }
 4982: 	my $where = ($isTask ? "$version:resource.$interaction"
 4983: 		             : "$version:resource");
 4984: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4985: 	    '<td>'.$timestamp.'</td>';
 4986: 	if ($isCODE) {
 4987: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4988: 	}
 4989:         if ($isTask) {
 4990:             $studentTable.='<td>'.$interaction.'</td>';
 4991:         }
 4992: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4993: 	my @displaySub = ();
 4994: 	foreach my $partid (@{$parts}) {
 4995:             my ($hidden,$type);
 4996:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4997:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4998:                 $hidden = 1;
 4999:             }
 5000: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 5001: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5002: 	    
 5003: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5004: 	    my $display_part=&get_display_part($partid,$symb);
 5005: 	    foreach my $matchKey (@matchKey) {
 5006: 		if (exists($$record{$version.':'.$matchKey}) &&
 5007: 		    $$record{$version.':'.$matchKey} ne '') {
 5008:                     
 5009: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5010: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5011:                     $displaySub[0].='<span class="LC_nobreak">';
 5012:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5013:                                    .' <span class="LC_internal_info">'
 5014:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5015:                                    .'</span>'
 5016:                                    .' <b>';
 5017:                     if ($hidden) {
 5018:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5019:                     } else {
 5020:                         my ($trial,$rndseed,$newvariation);
 5021:                         if ($type eq 'randomizetry') {
 5022:                             $trial = $$record{"$where.$partid.tries"};
 5023:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5024:                         }
 5025: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5026: 			    $displaySub[0].=&mt('Trial not counted');
 5027: 		        } else {
 5028: 			    $displaySub[0].=&mt('Trial: [_1]',
 5029: 					    $$record{"$where.$partid.tries"});
 5030:                             if ($rndseed || $lastrndseed{$partid}) {
 5031:                                 if ($rndseed ne $lastrndseed{$partid}) {
 5032:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5033:                                 }
 5034:                             }
 5035: 		        }
 5036: 		        my $responseType=($isTask ? 'Task'
 5037:                                               : $responseType->{$partid}->{$responseId});
 5038: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5039: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5040: 			    $orders{$partid}->{$responseId}=
 5041: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5042:                                            $no_increment,$type,$trial,$rndseed);
 5043: 		        }
 5044: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5045: 		        $displaySub[0].='&nbsp; '.
 5046: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5047:                     }
 5048: 		}
 5049: 	    }
 5050: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5051: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5052: 				    $$record{"$where.$partid.checkedin"},
 5053: 				    $$record{"$where.$partid.checkedin.slot"}).
 5054: 					'<br />';
 5055: 	    }
 5056: 	    if (exists $$record{"$where.$partid.award"}) {
 5057: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5058: 		    lc($$record{"$where.$partid.award"}).' '.
 5059: 		    $mark{$$record{"$where.$partid.solved"}}.
 5060: 		    '<br />';
 5061: 	    }
 5062: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5063: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5064: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5065: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5066: 		$displaySub[2].=
 5067: 		    $$record{"$version:resource.$partid.regrader"}.
 5068: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5069: 	    }
 5070: 	}
 5071: 	# needed because old essay regrader has not parts info
 5072: 	if (exists $$record{"$version:resource.regrader"}) {
 5073: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5074: 	}
 5075: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5076: 	if ($displaySub[2]) {
 5077: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5078: 	}
 5079: 	$studentTable.='&nbsp;</td>'.
 5080: 	    &Apache::loncommon::end_data_table_row();
 5081:     }
 5082:     $studentTable.=&Apache::loncommon::end_data_table();
 5083:     return $studentTable;
 5084: }
 5085: 
 5086: sub updateGradeByPage {
 5087:     my ($request) = shift;
 5088: 
 5089:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5090:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5091:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5092:     my $pageTitle = $env{'form.page'};
 5093:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5094:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5095:     my $usec=$classlist->{$env{'form.student'}}[5];
 5096:     if (!&canmodify($usec)) {
 5097: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5098: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5099: 	return;
 5100:     }
 5101:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5102:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5103: 	'</h3>'."\n";
 5104: 
 5105:     $request->print($result);
 5106: 
 5107: 
 5108:     my $navmap = Apache::lonnavmaps::navmap->new();
 5109:     unless (ref($navmap)) {
 5110:         $request->print(&navmap_errormsg());
 5111:         return;
 5112:     }
 5113:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5114:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5115:     if (!$map) {
 5116: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5117: 	my ($symb)=&get_symb($request);
 5118: 	$request->print(&show_grading_menu_form($symb));
 5119: 	return; 
 5120:     }
 5121:     my $iterator = $navmap->getIterator($map->map_start(),
 5122: 					$map->map_finish());
 5123: 
 5124:     my $studentTable=
 5125: 	&Apache::loncommon::start_data_table().
 5126: 	&Apache::loncommon::start_data_table_header_row().
 5127: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5128: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5129: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5130: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5131: 	&Apache::loncommon::end_data_table_header_row();
 5132: 
 5133:     $iterator->next(); # skip the first BEGIN_MAP
 5134:     my $curRes = $iterator->next(); # for "current resource"
 5135:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 5136:     while ($depth > 0) {
 5137:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5138:         if($curRes == $iterator->END_MAP) { $depth--; }
 5139: 
 5140:         if (ref($curRes) && $curRes->is_problem()) {
 5141: 	    my $parts = $curRes->parts();
 5142:             my $title = $curRes->compTitle();
 5143: 	    my $symbx = $curRes->symb();
 5144: 	    $studentTable.=
 5145: 		&Apache::loncommon::start_data_table_row().
 5146: 		'<td align="center" valign="top" >'.$prob.
 5147: 		(scalar(@{$parts}) == 1 ? '' 
 5148:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5149: 		.')').'</td>';
 5150: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5151: 
 5152: 	    my %newrecord=();
 5153: 	    my @displayPts=();
 5154:             my %aggregate = ();
 5155:             my $aggregateflag = 0;
 5156: 	    foreach my $partid (@{$parts}) {
 5157: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5158: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5159: 
 5160: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5161: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5162: 		my $partial = $newpts/$wgt;
 5163: 		my $score;
 5164: 		if ($partial > 0) {
 5165: 		    $score = 'correct_by_override';
 5166: 		} elsif ($newpts ne '') { #empty is taken as 0
 5167: 		    $score = 'incorrect_by_override';
 5168: 		}
 5169: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5170: 		if ($dropMenu eq 'excused') {
 5171: 		    $partial = '';
 5172: 		    $score = 'excused';
 5173: 		} elsif ($dropMenu eq 'reset status'
 5174: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5175: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5176: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5177: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5178: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5179: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5180: 		    $changeflag++;
 5181: 		    $newpts = '';
 5182:                     
 5183:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5184:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5185:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5186:                     if ($aggtries > 0) {
 5187:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5188:                         $aggregateflag = 1;
 5189:                     }
 5190: 		}
 5191: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5192: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5193: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5194: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5195: 		    '&nbsp;<br />';
 5196: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5197: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5198: 		    '&nbsp;<br />';
 5199: 		$question++;
 5200: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5201: 
 5202: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5203: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5204: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5205: 		    if (scalar(keys(%newrecord)) > 0);
 5206: 
 5207: 		$changeflag++;
 5208: 	    }
 5209: 	    if (scalar(keys(%newrecord)) > 0) {
 5210: 		my %record = 
 5211: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5212: 					     $udom,$uname);
 5213: 
 5214: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5215: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5216: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5217: 		    $newrecord{'resource.CODE'} = '';
 5218: 		}
 5219: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5220: 					$udom,$uname);
 5221: 		%record = &Apache::lonnet::restore($symbx,
 5222: 						   $env{'request.course.id'},
 5223: 						   $udom,$uname);
 5224: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5225: 					     $cdom,$cnum,$udom,$uname);
 5226: 	    }
 5227: 	    
 5228:             if ($aggregateflag) {
 5229:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5230:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5231:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5232:             }
 5233: 
 5234: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5235: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5236: 		&Apache::loncommon::end_data_table_row();
 5237: 
 5238: 	    $prob++;
 5239: 	}
 5240:         $curRes = $iterator->next();
 5241:     }
 5242: 
 5243:     $studentTable.=&Apache::loncommon::end_data_table();
 5244:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5245:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5246: 		  &mt('The scores were changed for [quant,_1,problem].',
 5247: 		  $changeflag));
 5248:     $request->print($grademsg.$studentTable);
 5249: 
 5250:     return '';
 5251: }
 5252: 
 5253: #-------- end of section for handling grading by page/sequence ---------
 5254: #
 5255: #-------------------------------------------------------------------
 5256: 
 5257: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5258: #
 5259: #------ start of section for handling grading by page/sequence ---------
 5260: 
 5261: =pod
 5262: 
 5263: =head1 Bubble sheet grading routines
 5264: 
 5265:   For this documentation:
 5266: 
 5267:    'scanline' refers to the full line of characters
 5268:    from the file that we are parsing that represents one entire sheet
 5269: 
 5270:    'bubble line' refers to the data
 5271:    representing the line of bubbles that are on the physical bubblesheet
 5272: 
 5273: 
 5274: The overall process is that a scanned in bubblesheet data is uploaded
 5275: into a course. When a user wants to grade, they select a
 5276: sequence/folder of resources, a file of bubblesheet info, and pick
 5277: one of the predefined configurations for what each scanline looks
 5278: like.
 5279: 
 5280: Next each scanline is checked for any errors of either 'missing
 5281: bubbles' (it's an error because it may have been mis-scanned
 5282: because too light bubbling), 'double bubble' (each bubble line should
 5283: have no more than one letter picked), invalid or duplicated CODE,
 5284: invalid student/employee ID
 5285: 
 5286: If the CODE option is used that determines the randomization of the
 5287: homework problems, either way the student/employee ID is looked up into a
 5288: username:domain.
 5289: 
 5290: During the validation phase the instructor can choose to skip scanlines. 
 5291: 
 5292: After the validation phase, there are now 3 bubblesheet files
 5293: 
 5294:   scantron_original_filename (unmodified original file)
 5295:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5296:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5297: 
 5298: Also there is a separate hash nohist_scantrondata that contains extra
 5299: correction information that isn't representable in the bubblesheet
 5300: file (see &scantron_getfile() for more information)
 5301: 
 5302: After all scanlines are either valid, marked as valid or skipped, then
 5303: foreach line foreach problem in the picked sequence, an ssi request is
 5304: made that simulates a user submitting their selected letter(s) against
 5305: the homework problem.
 5306: 
 5307: =over 4
 5308: 
 5309: 
 5310: 
 5311: =item defaultFormData
 5312: 
 5313:   Returns html hidden inputs used to hold context/default values.
 5314: 
 5315:  Arguments:
 5316:   $symb - $symb of the current resource 
 5317: 
 5318: =cut
 5319: 
 5320: sub defaultFormData {
 5321:     my ($symb)=@_;
 5322:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5323:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5324:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5325: }
 5326: 
 5327: 
 5328: =pod 
 5329: 
 5330: =item getSequenceDropDown
 5331: 
 5332:    Return html dropdown of possible sequences to grade
 5333:  
 5334:  Arguments:
 5335:    $symb - $symb of the current resource
 5336:    $map_error - ref to scalar which will container error if
 5337:                 $navmap object is unavailable in &getSymbMap().
 5338: 
 5339: =cut
 5340: 
 5341: sub getSequenceDropDown {
 5342:     my ($symb,$map_error)=@_;
 5343:     my $result='<select name="selectpage">'."\n";
 5344:     my ($titles,$symbx) = &getSymbMap($map_error);
 5345:     if (ref($map_error)) {
 5346:         return if ($$map_error);
 5347:     }
 5348:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5349:     my $ctr=0;
 5350:     foreach (@$titles) {
 5351: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5352: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5353: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5354: 	    '>'.$showtitle.'</option>'."\n";
 5355: 	$ctr++;
 5356:     }
 5357:     $result.= '</select>';
 5358:     return $result;
 5359: }
 5360: 
 5361: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5362:                                    # key is zero-based index - 0, 1, 2 ...
 5363: 
 5364: my %first_bubble_line;             # First bubble line no. for each bubble.
 5365: 
 5366: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5367:                                    # matchresponse or rankresponse, where 
 5368:                                    # an individual response can have multiple 
 5369:                                    # lines
 5370: 
 5371: my %responsetype_per_response;     # responsetype for each response
 5372: 
 5373: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5374:                                    # numbered response. Needed when randomorder
 5375:                                    # or randompick are in use. Key is ID, value 
 5376:                                    # is response number.
 5377: 
 5378: # Save and restore the bubble lines array to the form env.
 5379: 
 5380: 
 5381: sub save_bubble_lines {
 5382:     foreach my $line (keys(%bubble_lines_per_response)) {
 5383: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5384: 	$env{"form.scantron.first_bubble_line.$line"} =
 5385: 	    $first_bubble_line{$line};
 5386:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5387:             $subdivided_bubble_lines{$line};
 5388:         $env{"form.scantron.responsetype.$line"} =
 5389:             $responsetype_per_response{$line};
 5390:     }
 5391:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5392:         my $line = $masterseq_id_responsenum{$resid};
 5393:         $env{"form.scantron.residpart.$line"} = $resid;
 5394:     }
 5395: }
 5396: 
 5397: 
 5398: sub restore_bubble_lines {
 5399:     my $line = 0;
 5400:     %bubble_lines_per_response = ();
 5401:     %masterseq_id_responsenum = ();
 5402:     while ($env{"form.scantron.bubblelines.$line"}) {
 5403: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5404: 	$bubble_lines_per_response{$line} = $value;
 5405: 	$first_bubble_line{$line}  =
 5406: 	    $env{"form.scantron.first_bubble_line.$line"};
 5407:         $subdivided_bubble_lines{$line} =
 5408:             $env{"form.scantron.sub_bubblelines.$line"};
 5409:         $responsetype_per_response{$line} =
 5410:             $env{"form.scantron.responsetype.$line"};
 5411:         my $id = $env{"form.scantron.residpart.$line"};
 5412:         $masterseq_id_responsenum{$id} = $line;
 5413: 	$line++;
 5414:     }
 5415: }
 5416: 
 5417: =pod 
 5418: 
 5419: =item scantron_filenames
 5420: 
 5421:    Returns a list of the scantron files in the current course 
 5422: 
 5423: =cut
 5424: 
 5425: sub scantron_filenames {
 5426:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5427:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5428:     my $getpropath = 1;
 5429:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5430:                                                         $cname,$getpropath);
 5431:     my @possiblenames;
 5432:     if (ref($dirlist) eq 'ARRAY') {
 5433:         foreach my $filename (sort(@{$dirlist})) {
 5434: 	    ($filename)=split(/&/,$filename);
 5435: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5436: 	    $filename=~s/^scantron_orig_//;
 5437: 	    push(@possiblenames,$filename);
 5438:         }
 5439:     }
 5440:     return @possiblenames;
 5441: }
 5442: 
 5443: =pod 
 5444: 
 5445: =item scantron_uploads
 5446: 
 5447:    Returns  html drop-down list of scantron files in current course.
 5448: 
 5449:  Arguments:
 5450:    $file2grade - filename to set as selected in the dropdown
 5451: 
 5452: =cut
 5453: 
 5454: sub scantron_uploads {
 5455:     my ($file2grade) = @_;
 5456:     my $result=	'<select name="scantron_selectfile">';
 5457:     $result.="<option></option>";
 5458:     foreach my $filename (sort(&scantron_filenames())) {
 5459: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5460:     }
 5461:     $result.="</select>";
 5462:     return $result;
 5463: }
 5464: 
 5465: =pod 
 5466: 
 5467: =item scantron_scantab
 5468: 
 5469:   Returns html drop down of the scantron formats in the scantronformat.tab
 5470:   file.
 5471: 
 5472: =cut
 5473: 
 5474: sub scantron_scantab {
 5475:     my $result='<select name="scantron_format">'."\n";
 5476:     $result.='<option></option>'."\n";
 5477:     my @lines = &get_scantronformat_file();
 5478:     if (@lines > 0) {
 5479:         foreach my $line (@lines) {
 5480:             next if (($line =~ /^\#/) || ($line eq ''));
 5481: 	    my ($name,$descrip)=split(/:/,$line);
 5482: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5483:         }
 5484:     }
 5485:     $result.='</select>'."\n";
 5486:     return $result;
 5487: }
 5488: 
 5489: =pod
 5490: 
 5491: =item get_scantronformat_file
 5492: 
 5493:   Returns an array containing lines from the scantron format file for
 5494:   the domain of the course.
 5495: 
 5496:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5497:   lines are from this file.
 5498: 
 5499:   Otherwise, if a default.tab has been published in RES space by the 
 5500:   domainconfig user, lines are from this file.
 5501: 
 5502:   Otherwise, fall back to getting lines from the legacy file on the
 5503:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5504: 
 5505: =cut
 5506: 
 5507: sub get_scantronformat_file {
 5508:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5509:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5510:     my $gottab = 0;
 5511:     my @lines;
 5512:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5513:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5514:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5515:             if ($formatfile ne '-1') {
 5516:                 @lines = split("\n",$formatfile,-1);
 5517:                 $gottab = 1;
 5518:             }
 5519:         }
 5520:     }
 5521:     if (!$gottab) {
 5522:         my $confname = $cdom.'-domainconfig';
 5523:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5524:         my $formatfile =  &Apache::lonnet::getfile($default);
 5525:         if ($formatfile ne '-1') {
 5526:             @lines = split("\n",$formatfile,-1);
 5527:             $gottab = 1;
 5528:         }
 5529:     }
 5530:     if (!$gottab) {
 5531:         my @domains = &Apache::lonnet::current_machine_domains();
 5532:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5533:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5534:             @lines = <$fh>;
 5535:             close($fh);
 5536:         } else {
 5537:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5538:             @lines = <$fh>;
 5539:             close($fh);
 5540:         }
 5541:     }
 5542:     return @lines;
 5543: }
 5544: 
 5545: =pod 
 5546: 
 5547: =item scantron_CODElist
 5548: 
 5549:   Returns html drop down of the saved CODE lists from current course,
 5550:   generated from earlier printings.
 5551: 
 5552: =cut
 5553: 
 5554: sub scantron_CODElist {
 5555:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5556:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5557:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5558:     my $namechoice='<option></option>';
 5559:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5560: 	if ($name =~ /^error: 2 /) { next; }
 5561: 	if ($name =~ /^type\0/) { next; }
 5562: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5563:     }
 5564:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5565:     return $namechoice;
 5566: }
 5567: 
 5568: =pod 
 5569: 
 5570: =item scantron_CODEunique
 5571: 
 5572:   Returns the html for "Each CODE to be used once" radio.
 5573: 
 5574: =cut
 5575: 
 5576: sub scantron_CODEunique {
 5577:     my $result='<span class="LC_nobreak">
 5578:                  <label><input type="radio" name="scantron_CODEunique"
 5579:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5580:                 </span>
 5581:                 <span class="LC_nobreak">
 5582:                  <label><input type="radio" name="scantron_CODEunique"
 5583:                         value="no" />'.&mt('No').' </label>
 5584:                 </span>';
 5585:     return $result;
 5586: }
 5587: 
 5588: =pod 
 5589: 
 5590: =item scantron_selectphase
 5591: 
 5592:   Generates the initial screen to start the bubblesheet process.
 5593:   Allows for - starting a grading run.
 5594:              - downloading existing scan data (original, corrected
 5595:                                                 or skipped info)
 5596: 
 5597:              - uploading new scan data
 5598: 
 5599:  Arguments:
 5600:   $r          - The Apache request object
 5601:   $file2grade - name of the file that contain the scanned data to score
 5602: 
 5603: =cut
 5604: 
 5605: sub scantron_selectphase {
 5606:     my ($r,$file2grade) = @_;
 5607:     my ($symb)=&get_symb($r);
 5608:     if (!$symb) {return '';}
 5609:     my $map_error;
 5610:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5611:     if ($map_error) {
 5612:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5613:         return;
 5614:     }
 5615:     my $default_form_data=&defaultFormData($symb);
 5616:     my $grading_menu_button=&show_grading_menu_form($symb);
 5617:     my $file_selector=&scantron_uploads($file2grade);
 5618:     my $format_selector=&scantron_scantab();
 5619:     my $CODE_selector=&scantron_CODElist();
 5620:     my $CODE_unique=&scantron_CODEunique();
 5621:     my $result;
 5622: 
 5623:     $ssi_error = 0;
 5624: 
 5625:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5626:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5627: 
 5628:         # Chunk of form to prompt for a scantron file upload.
 5629: 
 5630:         $r->print('
 5631:     <br />
 5632:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5633:        '.&Apache::loncommon::start_data_table_header_row().'
 5634:             <th>
 5635:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5636:             </th>
 5637:        '.&Apache::loncommon::end_data_table_header_row().'
 5638:        '.&Apache::loncommon::start_data_table_row().'
 5639:             <td>
 5640: ');
 5641:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5642:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5643:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5644:     $r->print('
 5645:               <script type="text/javascript" language="javascript">
 5646:     function checkUpload(formname) {
 5647:         if (formname.upfile.value == "") {
 5648:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5649:             return false;
 5650:         }
 5651:         formname.submit();
 5652:     }
 5653:               </script>
 5654: 
 5655:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5656:                 '.$default_form_data.'
 5657:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5658:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5659:                 <input name="command" value="scantronupload_save" type="hidden" />
 5660:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5661:                 <br />
 5662:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5663:               </form>
 5664: ');
 5665: 
 5666:         $r->print('
 5667:             </td>
 5668:        '.&Apache::loncommon::end_data_table_row().'
 5669:        '.&Apache::loncommon::end_data_table().'
 5670: ');
 5671:     }
 5672: 
 5673:     # Chunk of form to prompt for a file to grade and how:
 5674: 
 5675:     $result.= '
 5676:     <br />
 5677:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5678:     <input type="hidden" name="command" value="scantron_warning" />
 5679:     '.$default_form_data.'
 5680:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5681:        '.&Apache::loncommon::start_data_table_header_row().'
 5682:             <th colspan="2">
 5683:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5684:             </th>
 5685:        '.&Apache::loncommon::end_data_table_header_row().'
 5686:        '.&Apache::loncommon::start_data_table_row().'
 5687:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5688:        '.&Apache::loncommon::end_data_table_row().'
 5689:        '.&Apache::loncommon::start_data_table_row().'
 5690:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5691:        '.&Apache::loncommon::end_data_table_row().'
 5692:        '.&Apache::loncommon::start_data_table_row().'
 5693:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5694:        '.&Apache::loncommon::end_data_table_row().'
 5695:        '.&Apache::loncommon::start_data_table_row().'
 5696:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5697:        '.&Apache::loncommon::end_data_table_row().'
 5698:        '.&Apache::loncommon::start_data_table_row().'
 5699:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5700:        '.&Apache::loncommon::end_data_table_row().'
 5701:        '.&Apache::loncommon::start_data_table_row().'
 5702: 	    <td> '.&mt('Options:').' </td>
 5703:             <td>
 5704: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5705:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5706:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5707: 	    </td>
 5708:        '.&Apache::loncommon::end_data_table_row().'
 5709:        '.&Apache::loncommon::start_data_table_row().'
 5710:             <td colspan="2">
 5711:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5712:             </td>
 5713:        '.&Apache::loncommon::end_data_table_row().'
 5714:     '.&Apache::loncommon::end_data_table().'
 5715:     </form>
 5716: ';
 5717:    
 5718:     $r->print($result);
 5719: 
 5720:     # Chunk of the form that prompts to view a scoring office file,
 5721:     # corrected file, skipped records in a file.
 5722: 
 5723:     $r->print('
 5724:    <br />
 5725:    <form action="/adm/grades" name="scantron_download">
 5726:      '.$default_form_data.'
 5727:      <input type="hidden" name="command" value="scantron_download" />
 5728:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5729:        '.&Apache::loncommon::start_data_table_header_row().'
 5730:               <th>
 5731:                 &nbsp;'.&mt('Download a scoring office file').'
 5732:               </th>
 5733:        '.&Apache::loncommon::end_data_table_header_row().'
 5734:        '.&Apache::loncommon::start_data_table_row().'
 5735:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5736:                 <br />
 5737:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5738:        '.&Apache::loncommon::end_data_table_row().'
 5739:      '.&Apache::loncommon::end_data_table().'
 5740:    </form>
 5741:    <br />
 5742: ');
 5743: 
 5744:     &Apache::lonpickcode::code_list($r,2);
 5745: 
 5746:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5747:              $default_form_data."\n".
 5748:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5749:              &Apache::loncommon::start_data_table_header_row()."\n".
 5750:              '<th colspan="2">
 5751:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5752:              '</th>'."\n".
 5753:               &Apache::loncommon::end_data_table_header_row()."\n".
 5754:               &Apache::loncommon::start_data_table_row()."\n".
 5755:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5756:               '<td> '.$sequence_selector.' </td>'.
 5757:               &Apache::loncommon::end_data_table_row()."\n".
 5758:               &Apache::loncommon::start_data_table_row()."\n".
 5759:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5760:               '<td> '.$file_selector.' </td>'."\n".
 5761:               &Apache::loncommon::end_data_table_row()."\n".
 5762:               &Apache::loncommon::start_data_table_row()."\n".
 5763:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5764:               '<td> '.$format_selector.' </td>'."\n".
 5765:               &Apache::loncommon::end_data_table_row()."\n".
 5766:               &Apache::loncommon::start_data_table_row()."\n".
 5767:               '<td> '.&mt('Options').' </td>'."\n".
 5768:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5769:               &Apache::loncommon::end_data_table_row()."\n".
 5770:               &Apache::loncommon::start_data_table_row()."\n".
 5771:               '<td colspan="2">'."\n".
 5772:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5773:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5774:               '</td>'."\n".
 5775:               &Apache::loncommon::end_data_table_row()."\n".
 5776:               &Apache::loncommon::end_data_table()."\n".
 5777:               '</form><br />');
 5778:     $r->print($grading_menu_button);
 5779:     return;
 5780: }
 5781: 
 5782: =pod
 5783: 
 5784: =item get_scantron_config
 5785: 
 5786:    Parse and return the scantron configuration line selected as a
 5787:    hash of configuration file fields.
 5788: 
 5789:  Arguments:
 5790:     which - the name of the configuration to parse from the file.
 5791: 
 5792: 
 5793:  Returns:
 5794:             If the named configuration is not in the file, an empty
 5795:             hash is returned.
 5796:     a hash with the fields
 5797:       name         - internal name for the this configuration setup
 5798:       description  - text to display to operator that describes this config
 5799:       CODElocation - if 0 or the string 'none'
 5800:                           - no CODE exists for this config
 5801:                      if -1 || the string 'letter'
 5802:                           - a CODE exists for this config and is
 5803:                             a string of letters
 5804:                      Unsupported value (but planned for future support)
 5805:                           if a positive integer
 5806:                                - The CODE exists as the first n items from
 5807:                                  the question section of the form
 5808:                           if the string 'number'
 5809:                                - The CODE exists for this config and is
 5810:                                  a string of numbers
 5811:       CODEstart   - (only matter if a CODE exists) column in the line where
 5812:                      the CODE starts
 5813:       CODElength  - length of the CODE
 5814:       IDstart     - column where the student/employee ID starts
 5815:       IDlength    - length of the student/employee ID info
 5816:       Qstart      - column where the information from the bubbled
 5817:                     'questions' start
 5818:       Qlength     - number of columns comprising a single bubble line from
 5819:                     the sheet. (usually either 1 or 10)
 5820:       Qon         - either a single character representing the character used
 5821:                     to signal a bubble was chosen in the positional setup, or
 5822:                     the string 'letter' if the letter of the chosen bubble is
 5823:                     in the final, or 'number' if a number representing the
 5824:                     chosen bubble is in the file (1->A 0->J)
 5825:       Qoff        - the character used to represent that a bubble was
 5826:                     left blank
 5827:       PaperID     - if the scanning process generates a unique number for each
 5828:                     sheet scanned the column that this ID number starts in
 5829:       PaperIDlength - number of columns that comprise the unique ID number
 5830:                       for the sheet of paper
 5831:       FirstName   - column that the first name starts in
 5832:       FirstNameLength - number of columns that the first name spans
 5833:  
 5834:       LastName    - column that the last name starts in
 5835:       LastNameLength - number of columns that the last name spans
 5836:       BubblesPerRow - number of bubbles available in each row used to
 5837:                       bubble an answer. (If not specified, 10 assumed).
 5838: 
 5839: =cut
 5840: 
 5841: sub get_scantron_config {
 5842:     my ($which) = @_;
 5843:     my @lines = &get_scantronformat_file();
 5844:     my %config;
 5845:     #FIXME probably should move to XML it has already gotten a bit much now
 5846:     foreach my $line (@lines) {
 5847: 	my ($name,$descrip)=split(/:/,$line);
 5848: 	if ($name ne $which ) { next; }
 5849: 	chomp($line);
 5850: 	my @config=split(/:/,$line);
 5851: 	$config{'name'}=$config[0];
 5852: 	$config{'description'}=$config[1];
 5853: 	$config{'CODElocation'}=$config[2];
 5854: 	$config{'CODEstart'}=$config[3];
 5855: 	$config{'CODElength'}=$config[4];
 5856: 	$config{'IDstart'}=$config[5];
 5857: 	$config{'IDlength'}=$config[6];
 5858: 	$config{'Qstart'}=$config[7];
 5859:  	$config{'Qlength'}=$config[8];
 5860: 	$config{'Qoff'}=$config[9];
 5861: 	$config{'Qon'}=$config[10];
 5862: 	$config{'PaperID'}=$config[11];
 5863: 	$config{'PaperIDlength'}=$config[12];
 5864: 	$config{'FirstName'}=$config[13];
 5865: 	$config{'FirstNamelength'}=$config[14];
 5866: 	$config{'LastName'}=$config[15];
 5867: 	$config{'LastNamelength'}=$config[16];
 5868:         $config{'BubblesPerRow'}=$config[17];
 5869: 	last;
 5870:     }
 5871:     return %config;
 5872: }
 5873: 
 5874: =pod 
 5875: 
 5876: =item username_to_idmap
 5877: 
 5878:     creates a hash keyed by student/employee ID with values of the corresponding
 5879:     student username:domain.
 5880: 
 5881:   Arguments:
 5882: 
 5883:     $classlist - reference to the class list hash. This is a hash
 5884:                  keyed by student name:domain  whose elements are references
 5885:                  to arrays containing various chunks of information
 5886:                  about the student. (See loncoursedata for more info).
 5887: 
 5888:   Returns
 5889:     %idmap - the constructed hash
 5890: 
 5891: =cut
 5892: 
 5893: sub username_to_idmap {
 5894:     my ($classlist)= @_;
 5895:     my %idmap;
 5896:     foreach my $student (keys(%$classlist)) {
 5897: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5898: 	    $student;
 5899:     }
 5900:     return %idmap;
 5901: }
 5902: 
 5903: =pod
 5904: 
 5905: =item scantron_fixup_scanline
 5906: 
 5907:    Process a requested correction to a scanline.
 5908: 
 5909:   Arguments:
 5910:     $scantron_config   - hash from &get_scantron_config()
 5911:     $scan_data         - hash of correction information 
 5912:                           (see &scantron_getfile())
 5913:     $line              - existing scanline
 5914:     $whichline         - line number of the passed in scanline
 5915:     $field             - type of change to process 
 5916:                          (either 
 5917:                           'ID'     -> correct the student/employee ID
 5918:                           'CODE'   -> correct the CODE
 5919:                           'answer' -> fixup the submitted answers)
 5920:     
 5921:    $args               - hash of additional info,
 5922:                           - 'ID' 
 5923:                                'newid' -> studentID to use in replacement
 5924:                                           of existing one
 5925:                           - 'CODE' 
 5926:                                'CODE_ignore_dup' - set to true if duplicates
 5927:                                                    should be ignored.
 5928: 	                       'CODE' - is new code or 'use_unfound'
 5929:                                         if the existing unfound code should
 5930:                                         be used as is
 5931:                           - 'answer'
 5932:                                'response' - new answer or 'none' if blank
 5933:                                'question' - the bubble line to change
 5934:                                'questionnum' - the question identifier,
 5935:                                                may include subquestion. 
 5936: 
 5937:   Returns:
 5938:     $line - the modified scanline
 5939: 
 5940:   Side effects: 
 5941:     $scan_data - may be updated
 5942: 
 5943: =cut
 5944: 
 5945: 
 5946: sub scantron_fixup_scanline {
 5947:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5948:     if ($field eq 'ID') {
 5949: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5950: 	    return ($line,1,'New value too large');
 5951: 	}
 5952: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5953: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5954: 				     $args->{'newid'});
 5955: 	}
 5956: 	substr($line,$$scantron_config{'IDstart'}-1,
 5957: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5958: 	if ($args->{'newid'}=~/^\s*$/) {
 5959: 	    &scan_data($scan_data,"$whichline.user",
 5960: 		       $args->{'username'}.':'.$args->{'domain'});
 5961: 	}
 5962:     } elsif ($field eq 'CODE') {
 5963: 	if ($args->{'CODE_ignore_dup'}) {
 5964: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5965: 	}
 5966: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5967: 	if ($args->{'CODE'} ne 'use_unfound') {
 5968: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5969: 		return ($line,1,'New CODE value too large');
 5970: 	    }
 5971: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5972: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5973: 	    }
 5974: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5975: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5976: 	}
 5977:     } elsif ($field eq 'answer') {
 5978: 	my $length=$scantron_config->{'Qlength'};
 5979: 	my $off=$scantron_config->{'Qoff'};
 5980: 	my $on=$scantron_config->{'Qon'};
 5981: 	my $answer=${off}x$length;
 5982: 	if ($args->{'response'} eq 'none') {
 5983: 	    &scan_data($scan_data,
 5984: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5985: 	} else {
 5986: 	    if ($on eq 'letter') {
 5987: 		my @alphabet=('A'..'Z');
 5988: 		$answer=$alphabet[$args->{'response'}];
 5989: 	    } elsif ($on eq 'number') {
 5990: 		$answer=$args->{'response'}+1;
 5991: 		if ($answer == 10) { $answer = '0'; }
 5992: 	    } else {
 5993: 		substr($answer,$args->{'response'},1)=$on;
 5994: 	    }
 5995: 	    &scan_data($scan_data,
 5996: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5997: 	}
 5998: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5999: 	substr($line,$where-1,$length)=$answer;
 6000:     }
 6001:     return $line;
 6002: }
 6003: 
 6004: =pod
 6005: 
 6006: =item scan_data
 6007: 
 6008:     Edit or look up  an item in the scan_data hash.
 6009: 
 6010:   Arguments:
 6011:     $scan_data  - The hash (see scantron_getfile)
 6012:     $key        - shorthand of the key to edit (actual key is
 6013:                   scantronfilename_key).
 6014:     $data        - New value of the hash entry.
 6015:     $delete      - If true, the entry is removed from the hash.
 6016: 
 6017:   Returns:
 6018:     The new value of the hash table field (undefined if deleted).
 6019: 
 6020: =cut
 6021: 
 6022: 
 6023: sub scan_data {
 6024:     my ($scan_data,$key,$value,$delete)=@_;
 6025:     my $filename=$env{'form.scantron_selectfile'};
 6026:     if (defined($value)) {
 6027: 	$scan_data->{$filename.'_'.$key} = $value;
 6028:     }
 6029:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6030:     return $scan_data->{$filename.'_'.$key};
 6031: }
 6032: 
 6033: # ----- These first few routines are general use routines.----
 6034: 
 6035: # Return the number of occurences of a pattern in a string.
 6036: 
 6037: sub occurence_count {
 6038:     my ($string, $pattern) = @_;
 6039: 
 6040:     my @matches = ($string =~ /$pattern/g);
 6041: 
 6042:     return scalar(@matches);
 6043: }
 6044: 
 6045: 
 6046: # Take a string known to have digits and convert all the
 6047: # digits into letters in the range J,A..I.
 6048: 
 6049: sub digits_to_letters {
 6050:     my ($input) = @_;
 6051: 
 6052:     my @alphabet = ('J', 'A'..'I');
 6053: 
 6054:     my @input    = split(//, $input);
 6055:     my $output ='';
 6056:     for (my $i = 0; $i < scalar(@input); $i++) {
 6057: 	if ($input[$i] =~ /\d/) {
 6058: 	    $output .= $alphabet[$input[$i]];
 6059: 	} else {
 6060: 	    $output .= $input[$i];
 6061: 	}
 6062:     }
 6063:     return $output;
 6064: }
 6065: 
 6066: =pod 
 6067: 
 6068: =item scantron_parse_scanline
 6069: 
 6070:   Decodes a scanline from the selected scantron file
 6071: 
 6072:  Arguments:
 6073:     line             - The text of the scantron file line to process
 6074:     whichline        - Line number
 6075:     scantron_config  - Hash describing the format of the scantron lines.
 6076:     scan_data        - Hash of extra information about the scanline
 6077:                        (see scantron_getfile for more information)
 6078:     just_header      - True if should not process question answers but only
 6079:                        the stuff to the left of the answers.
 6080:     randomorder      - True if randomorder in use
 6081:     randompick       - True if randompick in use
 6082:     sequence         - Exam folder URL
 6083:     master_seq       - Ref to array containing symbs in exam folder
 6084:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6085:                        (corresponding values are resource objects)
 6086:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6087:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6088:                        are refs to an array of resource objects, ordered
 6089:                        according to order used for CODE, when randomorder
 6090:                        and or randompick are in use.
 6091:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6092:                        for current line to question number used for same question
 6093:                         in "Master Sequence" (as seen by Course Coordinator).
 6094:     startline        - Ref to hash where key is question number (0 is first)
 6095:                        and value is number of first bubble line for current 
 6096:                        student or code-based randompick and/or randomorder.
 6097:     totalref         - Ref of scalar used to score total number of bubble
 6098:                        lines needed for responses in a scan line (used when
 6099:                        randompick in use. 
 6100: 
 6101:  Returns:
 6102:    Hash containing the result of parsing the scanline
 6103: 
 6104:    Keys are all proceeded by the string 'scantron.'
 6105: 
 6106:        CODE    - the CODE in use for this scanline
 6107:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6108:                  by the operator
 6109:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6110:                             CODEs were selected, but the usage has been
 6111:                             forced by the operator
 6112:        ID  - student/employee ID
 6113:        PaperID - if used, the ID number printed on the sheet when the 
 6114:                  paper was scanned
 6115:        FirstName - first name from the sheet
 6116:        LastName  - last name from the sheet
 6117: 
 6118:      if just_header was not true these key may also exist
 6119: 
 6120:        missingerror - a list of bubble ranges that are considered to be answers
 6121:                       to a single question that don't have any bubbles filled in.
 6122:                       Of the form questionnumber:firstbubblenumber:count.
 6123:        doubleerror  - a list of bubble ranges that are considered to be answers
 6124:                       to a single question that have more than one bubble filled in.
 6125:                       Of the form questionnumber::firstbubblenumber:count
 6126:    
 6127:                 In the above, count is the number of bubble responses in the
 6128:                 input line needed to represent the possible answers to the question.
 6129:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6130:                 per line would have count = 2.
 6131: 
 6132:        maxquest     - the number of the last bubble line that was parsed
 6133: 
 6134:        (<number> starts at 1)
 6135:        <number>.answer - zero or more letters representing the selected
 6136:                          letters from the scanline for the bubble line 
 6137:                          <number>.
 6138:                          if blank there was either no bubble or there where
 6139:                          multiple bubbles, (consult the keys missingerror and
 6140:                          doubleerror if this is an error condition)
 6141: 
 6142: =cut
 6143: 
 6144: sub scantron_parse_scanline {
 6145:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6146:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6147:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6148: 
 6149:     my %record;
 6150:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6151:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6152: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6153: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6154: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6155: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6156: 	    $record{'scantron.CODE'}=substr($data,
 6157: 					    $$scantron_config{'CODEstart'}-1,
 6158: 					    $$scantron_config{'CODElength'});
 6159: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6160: 		$record{'scantron.useCODE'}=1;
 6161: 	    }
 6162: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6163: 		$record{'scantron.CODE_ignore_dup'}=1;
 6164: 	    }
 6165: 	} else {
 6166: 	    #FIXME interpret first N questions
 6167: 	}
 6168:     }
 6169:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6170: 				  $$scantron_config{'IDlength'});
 6171:     $record{'scantron.PaperID'}=
 6172: 	substr($data,$$scantron_config{'PaperID'}-1,
 6173: 	       $$scantron_config{'PaperIDlength'});
 6174:     $record{'scantron.FirstName'}=
 6175: 	substr($data,$$scantron_config{'FirstName'}-1,
 6176: 	       $$scantron_config{'FirstNamelength'});
 6177:     $record{'scantron.LastName'}=
 6178: 	substr($data,$$scantron_config{'LastName'}-1,
 6179: 	       $$scantron_config{'LastNamelength'});
 6180:     if ($just_header) { return \%record; }
 6181: 
 6182:     my @alphabet=('A'..'Z');
 6183:     my $questnum=0;
 6184:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6185: 
 6186:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6187:     if ($randompick || $randomorder) {
 6188:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6189:                                          $master_seq,$symb_to_resource,
 6190:                                          $partids_by_symb,$orderedforcode,
 6191:                                          $respnumlookup,$startline);
 6192:         if ($total) {
 6193:             $lastpos = $total*$$scantron_config{'Qlength'};
 6194:         }
 6195:         if (ref($totalref)) {
 6196:             $$totalref = $total;
 6197:         }
 6198:     }
 6199:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6200:     chomp($questions);		# Get rid of any trailing \n.
 6201:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6202:     while (length($questions)) {
 6203:         my $answers_needed;
 6204:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6205:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6206:         } else {
 6207:             $answers_needed = $bubble_lines_per_response{$questnum};
 6208:         }
 6209:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6210:                              || 1;
 6211:         $questnum++;
 6212:         my $quest_id = $questnum;
 6213:         my $currentquest = substr($questions,0,$answer_length);
 6214:         $questions       = substr($questions,$answer_length);
 6215:         if (length($currentquest) < $answer_length) { next; }
 6216: 
 6217:         my $subdivided;
 6218:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6219:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6220:         } else {
 6221:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6222:         }
 6223:         if ($subdivided =~ /,/) {
 6224:             my $subquestnum = 1;
 6225:             my $subquestions = $currentquest;
 6226:             my @subanswers_needed = split(/,/,$subdivided);
 6227:             foreach my $subans (@subanswers_needed) {
 6228:                 my $subans_length =
 6229:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6230:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6231:                 $subquestions   = substr($subquestions,$subans_length);
 6232:                 $quest_id = "$questnum.$subquestnum";
 6233:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6234:                     ($$scantron_config{'Qon'} eq 'number')) {
 6235:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6236:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6237:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6238:                         $randomorder,$randompick,$respnumlookup);
 6239:                 } else {
 6240:                     $ansnum = &scantron_validator_positional($ansnum,
 6241:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6242:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6243:                         $randomorder,$randompick,$respnumlookup);
 6244:                 }
 6245:                 $subquestnum ++;
 6246:             }
 6247:         } else {
 6248:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6249:                 ($$scantron_config{'Qon'} eq 'number')) {
 6250:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6251:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6252:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6253:                     $randomorder,$randompick,$respnumlookup);
 6254:             } else {
 6255:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6256:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6257:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6258:                     $randomorder,$randompick,$respnumlookup);
 6259:             }
 6260:         }
 6261:     }
 6262:     $record{'scantron.maxquest'}=$questnum;
 6263:     return \%record;
 6264: }
 6265: 
 6266: sub get_master_seq {
 6267:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6268:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6269:                    (ref($symb_to_resource) eq 'HASH'));
 6270:     my $resource_error;
 6271:     foreach my $resource (@{$resources}) {
 6272:         my $ressymb;
 6273:         if (ref($resource)) {
 6274:             $ressymb = $resource->symb();
 6275:             push(@{$master_seq},$ressymb);
 6276:             $symb_to_resource->{$ressymb} = $resource;
 6277:         } else {
 6278:             $resource_error = 1;
 6279:             last;
 6280:         }
 6281:     }
 6282:     return $resource_error;
 6283: }
 6284: 
 6285: sub get_respnum_lookups {
 6286:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6287:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6288:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6289:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6290:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6291:                    (ref($startline) eq 'HASH'));
 6292:     my ($user,$scancode);
 6293:     if ((exists($record->{'scantron.CODE'})) &&
 6294:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6295:         $scancode = $record->{'scantron.CODE'};
 6296:     } else {
 6297:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6298:     }
 6299:     my @mapresources =
 6300:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6301:                      $orderedforcode);
 6302:     my $total = 0;
 6303:     my $count = 0;
 6304:     foreach my $resource (@mapresources) {
 6305:         my $id = $resource->id();
 6306:         my $symb = $resource->symb();
 6307:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6308:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6309:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6310:                 if ($respnum ne '') {
 6311:                     $respnumlookup->{$count} = $respnum;
 6312:                     $startline->{$count} = $total;
 6313:                     $total += $bubble_lines_per_response{$respnum};
 6314:                     $count ++;
 6315:                 }
 6316:             }
 6317:         }
 6318:     }
 6319:     return $total;
 6320: }
 6321: 
 6322: sub scantron_validator_lettnum {
 6323:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6324:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6325:         $randompick,$respnumlookup) = @_;
 6326: 
 6327:     # Qon 'letter' implies for each slot in currquest we have:
 6328:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6329:     #    about anything else (esp. a value of Qoff) for missing
 6330:     #    bubbles.
 6331:     #
 6332:     # Qon 'number' implies each slot gives a digit that indexes the
 6333:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6334:     #    and * or ? for double bubbles on a single line.
 6335:     #
 6336: 
 6337:     my $matchon;
 6338:     if ($$scantron_config{'Qon'} eq 'letter') {
 6339:         $matchon = '[A-Z]';
 6340:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6341:         $matchon = '\d';
 6342:     }
 6343:     my $occurrences = 0;
 6344:     my $responsenum = $questnum-1;
 6345:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6346:        $responsenum = $respnumlookup->{$questnum-1}
 6347:     }
 6348:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6349:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6350:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6351:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6352:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6353:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6354:         my @singlelines = split('',$currquest);
 6355:         foreach my $entry (@singlelines) {
 6356:             $occurrences = &occurence_count($entry,$matchon);
 6357:             if ($occurrences > 1) {
 6358:                 last;
 6359:             }
 6360:         }
 6361:     } else {
 6362:         $occurrences = &occurence_count($currquest,$matchon); 
 6363:     }
 6364:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6365:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6366:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6367:             my $bubble = substr($currquest,$ans,1);
 6368:             if ($bubble =~ /$matchon/ ) {
 6369:                 if ($$scantron_config{'Qon'} eq 'number') {
 6370:                     if ($bubble == 0) {
 6371:                         $bubble = 10; 
 6372:                     }
 6373:                     $record->{"scantron.$ansnum.answer"} = 
 6374:                         $alphabet->[$bubble-1];
 6375:                 } else {
 6376:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6377:                 }
 6378:             } else {
 6379:                 $record->{"scantron.$ansnum.answer"}='';
 6380:             }
 6381:             $ansnum++;
 6382:         }
 6383:     } elsif (!defined($currquest)
 6384:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6385:             || (&occurence_count($currquest,$matchon) == 0)) {
 6386:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6387:             $record->{"scantron.$ansnum.answer"}='';
 6388:             $ansnum++;
 6389:         }
 6390:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6391:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6392:         }
 6393:     } else {
 6394:         if ($$scantron_config{'Qon'} eq 'number') {
 6395:             $currquest = &digits_to_letters($currquest);            
 6396:         }
 6397:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6398:             my $bubble = substr($currquest,$ans,1);
 6399:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6400:             $ansnum++;
 6401:         }
 6402:     }
 6403:     return $ansnum;
 6404: }
 6405: 
 6406: sub scantron_validator_positional {
 6407:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6408:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6409:         $randomorder,$randompick,$respnumlookup) = @_;
 6410: 
 6411:     # Otherwise there's a positional notation;
 6412:     # each bubble line requires Qlength items, and there are filled in
 6413:     # bubbles for each case where there 'Qon' characters.
 6414:     #
 6415: 
 6416:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6417: 
 6418:     # If the split only gives us one element.. the full length of the
 6419:     # answer string, no bubbles are filled in:
 6420: 
 6421:     if ($answers_needed eq '') {
 6422:         return;
 6423:     }
 6424: 
 6425:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6426:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6427:             $record->{"scantron.$ansnum.answer"}='';
 6428:             $ansnum++;
 6429:         }
 6430:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6431:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6432:         }
 6433:     } elsif (scalar(@array) == 2) {
 6434:         my $location = length($array[0]);
 6435:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6436:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6437:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6438:             if ($ans eq $line_num) {
 6439:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6440:             } else {
 6441:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6442:             }
 6443:             $ansnum++;
 6444:          }
 6445:     } else {
 6446:         #  If there's more than one instance of a bubble character
 6447:         #  That's a double bubble; with positional notation we can
 6448:         #  record all the bubbles filled in as well as the
 6449:         #  fact this response consists of multiple bubbles.
 6450:         #
 6451:         my $responsenum = $questnum-1;
 6452:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6453:             $responsenum = $respnumlookup->{$questnum-1}
 6454:         }
 6455:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6456:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6457:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6458:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6459:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6460:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6461:             my $doubleerror = 0;
 6462:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6463:                    (!$doubleerror)) {
 6464:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6465:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6466:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6467:                if (length(@currarray) > 2) {
 6468:                    $doubleerror = 1;
 6469:                } 
 6470:             }
 6471:             if ($doubleerror) {
 6472:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6473:             }
 6474:         } else {
 6475:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6476:         }
 6477:         my $item = $ansnum;
 6478:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6479:             $record->{"scantron.$item.answer"} = '';
 6480:             $item ++;
 6481:         }
 6482: 
 6483:         my @ans=@array;
 6484:         my $i=0;
 6485:         my $increment = 0;
 6486:         while ($#ans) {
 6487:             $i+=length($ans[0]) + $increment;
 6488:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6489:             my $bubble = $i%$$scantron_config{'Qlength'};
 6490:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6491:             shift(@ans);
 6492:             $increment = 1;
 6493:         }
 6494:         $ansnum += $answers_needed;
 6495:     }
 6496:     return $ansnum;
 6497: }
 6498: 
 6499: =pod
 6500: 
 6501: =item scantron_add_delay
 6502: 
 6503:    Adds an error message that occurred during the grading phase to a
 6504:    queue of messages to be shown after grading pass is complete
 6505: 
 6506:  Arguments:
 6507:    $delayqueue  - arrary ref of hash ref of error messages
 6508:    $scanline    - the scanline that caused the error
 6509:    $errormesage - the error message
 6510:    $errorcode   - a numeric code for the error
 6511: 
 6512:  Side Effects:
 6513:    updates the $delayqueue to have a new hash ref of the error
 6514: 
 6515: =cut
 6516: 
 6517: sub scantron_add_delay {
 6518:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6519:     push(@$delayqueue,
 6520: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6521: 	  'ecode' => $errorcode }
 6522: 	 );
 6523: }
 6524: 
 6525: =pod
 6526: 
 6527: =item scantron_find_student
 6528: 
 6529:    Finds the username for the current scanline
 6530: 
 6531:   Arguments:
 6532:    $scantron_record - hash result from scantron_parse_scanline
 6533:    $scan_data       - hash of correction information 
 6534:                       (see &scantron_getfile() form more information)
 6535:    $idmap           - hash from &username_to_idmap()
 6536:    $line            - number of current scanline
 6537:  
 6538:   Returns:
 6539:    Either 'username:domain' or undef if unknown
 6540: 
 6541: =cut
 6542: 
 6543: sub scantron_find_student {
 6544:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6545:     my $scanID=$$scantron_record{'scantron.ID'};
 6546:     if ($scanID =~ /^\s*$/) {
 6547:  	return &scan_data($scan_data,"$line.user");
 6548:     }
 6549:     foreach my $id (keys(%$idmap)) {
 6550:  	if (lc($id) eq lc($scanID)) {
 6551:  	    return $$idmap{$id};
 6552:  	}
 6553:     }
 6554:     return undef;
 6555: }
 6556: 
 6557: =pod
 6558: 
 6559: =item scantron_filter
 6560: 
 6561:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6562:    hidden resources was selected
 6563: 
 6564: =cut
 6565: 
 6566: sub scantron_filter {
 6567:     my ($curres)=@_;
 6568: 
 6569:     if (ref($curres) && $curres->is_problem()) {
 6570: 	# if the user has asked to not have either hidden
 6571: 	# or 'randomout' controlled resources to be graded
 6572: 	# don't include them
 6573: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6574: 	    && $curres->randomout) {
 6575: 	    return 0;
 6576: 	}
 6577: 	return 1;
 6578:     }
 6579:     return 0;
 6580: }
 6581: 
 6582: =pod
 6583: 
 6584: =item scantron_process_corrections
 6585: 
 6586:    Gets correction information out of submitted form data and corrects
 6587:    the scanline
 6588: 
 6589: =cut
 6590: 
 6591: sub scantron_process_corrections {
 6592:     my ($r) = @_;
 6593:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6594:     my ($scanlines,$scan_data)=&scantron_getfile();
 6595:     my $classlist=&Apache::loncoursedata::get_classlist();
 6596:     my $which=$env{'form.scantron_line'};
 6597:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6598:     my ($skip,$err,$errmsg);
 6599:     if ($env{'form.scantron_skip_record'}) {
 6600: 	$skip=1;
 6601:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6602: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6603: 	    $env{'form.scantron_domain'};
 6604: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6605: 	($line,$err,$errmsg)=
 6606: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6607: 				     'ID',{'newid'=>$newid,
 6608: 				    'username'=>$env{'form.scantron_username'},
 6609: 				    'domain'=>$env{'form.scantron_domain'}});
 6610:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6611: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6612: 	my $newCODE;
 6613: 	my %args;
 6614: 	if      ($resolution eq 'use_unfound') {
 6615: 	    $newCODE='use_unfound';
 6616: 	} elsif ($resolution eq 'use_found') {
 6617: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6618: 	} elsif ($resolution eq 'use_typed') {
 6619: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6620: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6621: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6622: 	}
 6623: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6624: 	    $args{'CODE_ignore_dup'}=1;
 6625: 	}
 6626: 	$args{'CODE'}=$newCODE;
 6627: 	($line,$err,$errmsg)=
 6628: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6629: 				     'CODE',\%args);
 6630:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6631: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6632: 	    ($line,$err,$errmsg)=
 6633: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6634: 					 $which,'answer',
 6635: 					 { 'question'=>$question,
 6636: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6637:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6638: 	    if ($err) { last; }
 6639: 	}
 6640:     }
 6641:     if ($err) {
 6642: 	$r->print(
 6643:             '<p class="LC_error">'
 6644:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6645:                 $errmsg)
 6646:            .'</p>');
 6647:     } else {
 6648: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6649: 	&scantron_putfile($scanlines,$scan_data);
 6650:     }
 6651: }
 6652: 
 6653: =pod
 6654: 
 6655: =item reset_skipping_status
 6656: 
 6657:    Forgets the current set of remember skipped scanlines (and thus
 6658:    reverts back to considering all lines in the
 6659:    scantron_skipped_<filename> file)
 6660: 
 6661: =cut
 6662: 
 6663: sub reset_skipping_status {
 6664:     my ($scanlines,$scan_data)=&scantron_getfile();
 6665:     &scan_data($scan_data,'remember_skipping',undef,1);
 6666:     &scantron_putfile(undef,$scan_data);
 6667: }
 6668: 
 6669: =pod
 6670: 
 6671: =item start_skipping
 6672: 
 6673:    Marks a scanline to be skipped. 
 6674: 
 6675: =cut
 6676: 
 6677: sub start_skipping {
 6678:     my ($scan_data,$i)=@_;
 6679:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6680:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6681: 	$remembered{$i}=2;
 6682:     } else {
 6683: 	$remembered{$i}=1;
 6684:     }
 6685:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6686: }
 6687: 
 6688: =pod
 6689: 
 6690: =item should_be_skipped
 6691: 
 6692:    Checks whether a scanline should be skipped.
 6693: 
 6694: =cut
 6695: 
 6696: sub should_be_skipped {
 6697:     my ($scanlines,$scan_data,$i)=@_;
 6698:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6699: 	# not redoing old skips
 6700: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6701: 	return 0;
 6702:     }
 6703:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6704: 
 6705:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6706: 	return 0;
 6707:     }
 6708:     return 1;
 6709: }
 6710: 
 6711: =pod
 6712: 
 6713: =item remember_current_skipped
 6714: 
 6715:    Discovers what scanlines are in the scantron_skipped_<filename>
 6716:    file and remembers them into scan_data for later use.
 6717: 
 6718: =cut
 6719: 
 6720: sub remember_current_skipped {
 6721:     my ($scanlines,$scan_data)=&scantron_getfile();
 6722:     my %to_remember;
 6723:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6724: 	if ($scanlines->{'skipped'}[$i]) {
 6725: 	    $to_remember{$i}=1;
 6726: 	}
 6727:     }
 6728: 
 6729:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6730:     &scantron_putfile(undef,$scan_data);
 6731: }
 6732: 
 6733: =pod
 6734: 
 6735: =item check_for_error
 6736: 
 6737:     Checks if there was an error when attempting to remove a specific
 6738:     scantron_.. bubblesheet data file. Prints out an error if
 6739:     something went wrong.
 6740: 
 6741: =cut
 6742: 
 6743: sub check_for_error {
 6744:     my ($r,$result)=@_;
 6745:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6746: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6747:     }
 6748: }
 6749: 
 6750: =pod
 6751: 
 6752: =item scantron_warning_screen
 6753: 
 6754:    Interstitial screen to make sure the operator has selected the
 6755:    correct options before we start the validation phase.
 6756: 
 6757: =cut
 6758: 
 6759: sub scantron_warning_screen {
 6760:     my ($button_text)=@_;
 6761:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6762:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6763:     my $CODElist;
 6764:     if ($scantron_config{'CODElocation'} &&
 6765: 	$scantron_config{'CODEstart'} &&
 6766: 	$scantron_config{'CODElength'}) {
 6767: 	$CODElist=$env{'form.scantron_CODElist'};
 6768: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6769: 	$CODElist=
 6770: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6771: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6772:     }
 6773:     my $lastbubblepoints;
 6774:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6775:         $lastbubblepoints =
 6776:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6777:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6778:     }
 6779:     return ('
 6780: <p>
 6781: <span class="LC_warning">
 6782: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6783: </p>
 6784: <table>
 6785: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6786: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6787: '.$CODElist.$lastbubblepoints.'
 6788: </table>
 6789: <br />
 6790: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 6791: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 6792: 
 6793: <br />
 6794: ');
 6795: }
 6796: 
 6797: =pod
 6798: 
 6799: =item scantron_do_warning
 6800: 
 6801:    Check if the operator has picked something for all required
 6802:    fields. Error out if something is missing.
 6803: 
 6804: =cut
 6805: 
 6806: sub scantron_do_warning {
 6807:     my ($r)=@_;
 6808:     my ($symb)=&get_symb($r);
 6809:     if (!$symb) {return '';}
 6810:     my $default_form_data=&defaultFormData($symb);
 6811:     $r->print(&scantron_form_start().$default_form_data);
 6812:     if ( $env{'form.selectpage'} eq '' ||
 6813: 	 $env{'form.scantron_selectfile'} eq '' ||
 6814: 	 $env{'form.scantron_format'} eq '' ) {
 6815: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6816: 	if ( $env{'form.selectpage'} eq '') {
 6817: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6818: 	} 
 6819: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6820: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6821: 	} 
 6822: 	if ( $env{'form.scantron_format'} eq '') {
 6823: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6824: 	} 
 6825:     } else {
 6826: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6827:         my $bubbledbyhand=&hand_bubble_option();
 6828: 	$r->print('
 6829: '.$warning.$bubbledbyhand.'
 6830: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6831: <input type="hidden" name="command" value="scantron_validate" />
 6832: ');
 6833:     }
 6834:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6835:     return '';
 6836: }
 6837: 
 6838: =pod
 6839: 
 6840: =item scantron_form_start
 6841: 
 6842:     html hidden input for remembering all selected grading options
 6843: 
 6844: =cut
 6845: 
 6846: sub scantron_form_start {
 6847:     my ($max_bubble)=@_;
 6848:     my $result= <<SCANTRONFORM;
 6849: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6850:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6851:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6852:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6853:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6854:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6855:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6856:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6857:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6858:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6859: SCANTRONFORM
 6860: 
 6861:   my $line = 0;
 6862:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6863:        my $chunk =
 6864: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6865:        $chunk .=
 6866: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6867:        $chunk .= 
 6868:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6869:        $chunk .=
 6870:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6871:        $chunk .=
 6872:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6873:        $result .= $chunk;
 6874:        $line++;
 6875:     }
 6876:     return $result;
 6877: }
 6878: 
 6879: =pod
 6880: 
 6881: =item scantron_validate_file
 6882: 
 6883:     Dispatch routine for doing validation of a bubblesheet data file.
 6884: 
 6885:     Also processes any necessary information resets that need to
 6886:     occur before validation begins (ignore previous corrections,
 6887:     restarting the skipped records processing)
 6888: 
 6889: =cut
 6890: 
 6891: sub scantron_validate_file {
 6892:     my ($r) = @_;
 6893:     my ($symb)=&get_symb($r);
 6894:     if (!$symb) {return '';}
 6895:     my $default_form_data=&defaultFormData($symb);
 6896:     
 6897:     # do the detection of only doing skipped records first before we delete
 6898:     # them when doing the corrections reset
 6899:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6900: 	&reset_skipping_status();
 6901:     }
 6902:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6903: 	&remember_current_skipped();
 6904: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6905:     }
 6906: 
 6907:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6908: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6909: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6910: 	&check_for_error($r,&scantron_remove_scan_data());
 6911: 	$env{'form.scantron_options_ignore'}='done';
 6912:     }
 6913: 
 6914:     if ($env{'form.scantron_corrections'}) {
 6915: 	&scantron_process_corrections($r);
 6916:     }
 6917:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6918:     #get the student pick code ready
 6919:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6920:     my $nav_error;
 6921:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6922:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6923:     if ($nav_error) {
 6924:         $r->print(&navmap_errormsg());
 6925:         return '';
 6926:     }
 6927:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6928:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6929:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6930:     }
 6931:     $r->print($result);
 6932:     
 6933:     my @validate_phases=( 'sequence',
 6934: 			  'ID',
 6935: 			  'CODE',
 6936: 			  'doublebubble',
 6937: 			  'missingbubbles');
 6938:     if (!$env{'form.validatepass'}) {
 6939: 	$env{'form.validatepass'} = 0;
 6940:     }
 6941:     my $currentphase=$env{'form.validatepass'};
 6942: 
 6943: 
 6944:     my $stop=0;
 6945:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6946: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6947: 	$r->rflush();
 6948: 
 6949: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6950: 	{
 6951: 	    no strict 'refs';
 6952: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6953: 	}
 6954:     }
 6955:     if (!$stop) {
 6956: 	my $warning=&scantron_warning_screen('Start Grading');
 6957: 	$r->print(&mt('Validation process complete.').'<br />'.
 6958:                   $warning.
 6959:                   &mt('Perform verification for each student after storage of submissions?').
 6960:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6961:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6962:                   ('&nbsp;'x3).'<label>'.
 6963:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6964:                   '</label></span><br />'.
 6965:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6966:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6967:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6968:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6969:     } else {
 6970: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6971: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6972:     }
 6973:     if ($stop) {
 6974: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6975: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6976: 	    $r->print(' '.&mt('this error').' <br />');
 6977: 
 6978: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6979: 	} else {
 6980:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6981: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6982:             } else {
 6983:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6984:             }
 6985: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6986: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6987: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6988: 	}
 6989:     }
 6990:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6991:     return '';
 6992: }
 6993: 
 6994: 
 6995: =pod
 6996: 
 6997: =item scantron_remove_file
 6998: 
 6999:    Removes the requested bubblesheet data file, makes sure that
 7000:    scantron_original_<filename> is never removed
 7001: 
 7002: 
 7003: =cut
 7004: 
 7005: sub scantron_remove_file {
 7006:     my ($which)=@_;
 7007:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7008:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7009:     my $file='scantron_';
 7010:     if ($which eq 'corrected' || $which eq 'skipped') {
 7011: 	$file.=$which.'_';
 7012:     } else {
 7013: 	return 'refused';
 7014:     }
 7015:     $file.=$env{'form.scantron_selectfile'};
 7016:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7017: }
 7018: 
 7019: 
 7020: =pod
 7021: 
 7022: =item scantron_remove_scan_data
 7023: 
 7024:    Removes all scan_data correction for the requested bubblesheet
 7025:    data file.  (In the case that both the are doing skipped records we need
 7026:    to remember the old skipped lines for the time being so that element
 7027:    persists for a while.)
 7028: 
 7029: =cut
 7030: 
 7031: sub scantron_remove_scan_data {
 7032:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7033:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7034:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7035:     my @todelete;
 7036:     my $filename=$env{'form.scantron_selectfile'};
 7037:     foreach my $key (@keys) {
 7038: 	if ($key=~/^\Q$filename\E_/) {
 7039: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7040: 		$key=~/remember_skipping/) {
 7041: 		next;
 7042: 	    }
 7043: 	    push(@todelete,$key);
 7044: 	}
 7045:     }
 7046:     my $result;
 7047:     if (@todelete) {
 7048: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7049: 				       \@todelete,$cdom,$cname);
 7050:     } else {
 7051: 	$result = 'ok';
 7052:     }
 7053:     return $result;
 7054: }
 7055: 
 7056: 
 7057: =pod
 7058: 
 7059: =item scantron_getfile
 7060: 
 7061:     Fetches the requested bubblesheet data file (all 3 versions), and
 7062:     the scan_data hash
 7063:   
 7064:   Arguments:
 7065:     None
 7066: 
 7067:   Returns:
 7068:     2 hash references
 7069: 
 7070:      - first one has 
 7071:          orig      -
 7072:          corrected -
 7073:          skipped   -  each of which points to an array ref of the specified
 7074:                       file broken up into individual lines
 7075:          count     - number of scanlines
 7076:  
 7077:      - second is the scan_data hash possible keys are
 7078:        ($number refers to scanline numbered $number and thus the key affects
 7079:         only that scanline
 7080:         $bubline refers to the specific bubble line element and the aspects
 7081:         refers to that specific bubble line element)
 7082: 
 7083:        $number.user - username:domain to use
 7084:        $number.CODE_ignore_dup 
 7085:                     - ignore the duplicate CODE error 
 7086:        $number.useCODE
 7087:                     - use the CODE in the scanline as is
 7088:        $number.no_bubble.$bubline
 7089:                     - it is valid that there is no bubbled in bubble
 7090:                       at $number $bubline
 7091:        remember_skipping
 7092:                     - a frozen hash containing keys of $number and values
 7093:                       of either 
 7094:                         1 - we are on a 'do skipped records pass' and plan
 7095:                             on processing this line
 7096:                         2 - we are on a 'do skipped records pass' and this
 7097:                             scanline has been marked to skip yet again
 7098: 
 7099: =cut
 7100: 
 7101: sub scantron_getfile {
 7102:     #FIXME really would prefer a scantron directory
 7103:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7104:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7105:     my $lines;
 7106:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7107: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7108:     my %scanlines;
 7109:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7110:     my $temp=$scanlines{'orig'};
 7111:     $scanlines{'count'}=$#$temp;
 7112: 
 7113:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7114: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7115:     if ($lines eq '-1') {
 7116: 	$scanlines{'corrected'}=[];
 7117:     } else {
 7118: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7119:     }
 7120:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7121: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7122:     if ($lines eq '-1') {
 7123: 	$scanlines{'skipped'}=[];
 7124:     } else {
 7125: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7126:     }
 7127:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7128:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7129:     my %scan_data = @tmp;
 7130:     return (\%scanlines,\%scan_data);
 7131: }
 7132: 
 7133: =pod
 7134: 
 7135: =item lonnet_putfile
 7136: 
 7137:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7138: 
 7139:  Arguments:
 7140:    $contents - data to store
 7141:    $filename - filename to store $contents into
 7142: 
 7143:  Returns:
 7144:    result value from &Apache::lonnet::finishuserfileupload
 7145: 
 7146: =cut
 7147: 
 7148: sub lonnet_putfile {
 7149:     my ($contents,$filename)=@_;
 7150:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7151:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7152:     $env{'form.sillywaytopassafilearound'}=$contents;
 7153:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7154: 
 7155: }
 7156: 
 7157: =pod
 7158: 
 7159: =item scantron_putfile
 7160: 
 7161:     Stores the current version of the bubblesheet data files, and the
 7162:     scan_data hash. (Does not modify the original version only the
 7163:     corrected and skipped versions.
 7164: 
 7165:  Arguments:
 7166:     $scanlines - hash ref that looks like the first return value from
 7167:                  &scantron_getfile()
 7168:     $scan_data - hash ref that looks like the second return value from
 7169:                  &scantron_getfile()
 7170: 
 7171: =cut
 7172: 
 7173: sub scantron_putfile {
 7174:     my ($scanlines,$scan_data) = @_;
 7175:     #FIXME really would prefer a scantron directory
 7176:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7177:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7178:     if ($scanlines) {
 7179: 	my $prefix='scantron_';
 7180: # no need to update orig, shouldn't change
 7181: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7182: #		    $env{'form.scantron_selectfile'});
 7183: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7184: 			$prefix.'corrected_'.
 7185: 			$env{'form.scantron_selectfile'});
 7186: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7187: 			$prefix.'skipped_'.
 7188: 			$env{'form.scantron_selectfile'});
 7189:     }
 7190:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7191: }
 7192: 
 7193: =pod
 7194: 
 7195: =item scantron_get_line
 7196: 
 7197:    Returns the correct version of the scanline
 7198: 
 7199:  Arguments:
 7200:     $scanlines - hash ref that looks like the first return value from
 7201:                  &scantron_getfile()
 7202:     $scan_data - hash ref that looks like the second return value from
 7203:                  &scantron_getfile()
 7204:     $i         - number of the requested line (starts at 0)
 7205: 
 7206:  Returns:
 7207:    A scanline, (either the original or the corrected one if it
 7208:    exists), or undef if the requested scanline should be
 7209:    skipped. (Either because it's an skipped scanline, or it's an
 7210:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7211:    pass.
 7212: 
 7213: =cut
 7214: 
 7215: sub scantron_get_line {
 7216:     my ($scanlines,$scan_data,$i)=@_;
 7217:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7218:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7219:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7220:     return $scanlines->{'orig'}[$i]; 
 7221: }
 7222: 
 7223: =pod
 7224: 
 7225: =item scantron_todo_count
 7226: 
 7227:     Counts the number of scanlines that need processing.
 7228: 
 7229:  Arguments:
 7230:     $scanlines - hash ref that looks like the first return value from
 7231:                  &scantron_getfile()
 7232:     $scan_data - hash ref that looks like the second return value from
 7233:                  &scantron_getfile()
 7234: 
 7235:  Returns:
 7236:     $count - number of scanlines to process
 7237: 
 7238: =cut
 7239: 
 7240: sub get_todo_count {
 7241:     my ($scanlines,$scan_data)=@_;
 7242:     my $count=0;
 7243:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7244: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7245: 	if ($line=~/^[\s\cz]*$/) { next; }
 7246: 	$count++;
 7247:     }
 7248:     return $count;
 7249: }
 7250: 
 7251: =pod
 7252: 
 7253: =item scantron_put_line
 7254: 
 7255:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7256:     data file.
 7257: 
 7258:  Arguments:
 7259:     $scanlines - hash ref that looks like the first return value from
 7260:                  &scantron_getfile()
 7261:     $scan_data - hash ref that looks like the second return value from
 7262:                  &scantron_getfile()
 7263:     $i         - line number to update
 7264:     $newline   - contents of the updated scanline
 7265:     $skip      - if true make the line for skipping and update the
 7266:                  'skipped' file
 7267: 
 7268: =cut
 7269: 
 7270: sub scantron_put_line {
 7271:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7272:     if ($skip) {
 7273: 	$scanlines->{'skipped'}[$i]=$newline;
 7274: 	&start_skipping($scan_data,$i);
 7275: 	return;
 7276:     }
 7277:     $scanlines->{'corrected'}[$i]=$newline;
 7278: }
 7279: 
 7280: =pod
 7281: 
 7282: =item scantron_clear_skip
 7283: 
 7284:    Remove a line from the 'skipped' file
 7285: 
 7286:  Arguments:
 7287:     $scanlines - hash ref that looks like the first return value from
 7288:                  &scantron_getfile()
 7289:     $scan_data - hash ref that looks like the second return value from
 7290:                  &scantron_getfile()
 7291:     $i         - line number to update
 7292: 
 7293: =cut
 7294: 
 7295: sub scantron_clear_skip {
 7296:     my ($scanlines,$scan_data,$i)=@_;
 7297:     if (exists($scanlines->{'skipped'}[$i])) {
 7298: 	undef($scanlines->{'skipped'}[$i]);
 7299: 	return 1;
 7300:     }
 7301:     return 0;
 7302: }
 7303: 
 7304: =pod
 7305: 
 7306: =item scantron_filter_not_exam
 7307: 
 7308:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7309:    filter out resources that are not marked as 'exam' mode
 7310: 
 7311: =cut
 7312: 
 7313: sub scantron_filter_not_exam {
 7314:     my ($curres)=@_;
 7315:     
 7316:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7317: 	# if the user has asked to not have either hidden
 7318: 	# or 'randomout' controlled resources to be graded
 7319: 	# don't include them
 7320: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7321: 	    && $curres->randomout) {
 7322: 	    return 0;
 7323: 	}
 7324: 	return 1;
 7325:     }
 7326:     return 0;
 7327: }
 7328: 
 7329: =pod
 7330: 
 7331: =item scantron_validate_sequence
 7332: 
 7333:     Validates the selected sequence, checking for resource that are
 7334:     not set to exam mode.
 7335: 
 7336: =cut
 7337: 
 7338: sub scantron_validate_sequence {
 7339:     my ($r,$currentphase) = @_;
 7340: 
 7341:     my $navmap=Apache::lonnavmaps::navmap->new();
 7342:     unless (ref($navmap)) {
 7343:         $r->print(&navmap_errormsg());
 7344:         return (1,$currentphase);
 7345:     }
 7346:     my (undef,undef,$sequence)=
 7347: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7348: 
 7349:     my $map=$navmap->getResourceByUrl($sequence);
 7350: 
 7351:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7352:                                     value="ignore" />');
 7353:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7354: 	my @resources=
 7355: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7356: 	if (@resources) {
 7357: 	    $r->print('<p class="LC_warning">'
 7358:                .&mt('Some resources in the sequence currently are not set to'
 7359:                    .' exam mode. Grading these resources currently may not'
 7360:                    .' work correctly.')
 7361:                .'</p>'
 7362:             );
 7363: 	    return (1,$currentphase);
 7364: 	}
 7365:     }
 7366: 
 7367:     return (0,$currentphase+1);
 7368: }
 7369: 
 7370: 
 7371: 
 7372: sub scantron_validate_ID {
 7373:     my ($r,$currentphase) = @_;
 7374:     
 7375:     #get student info
 7376:     my $classlist=&Apache::loncoursedata::get_classlist();
 7377:     my %idmap=&username_to_idmap($classlist);
 7378: 
 7379:     #get scantron line setup
 7380:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7381:     my ($scanlines,$scan_data)=&scantron_getfile();
 7382: 
 7383:     my $nav_error;
 7384:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7385:     if ($nav_error) {
 7386:         $r->print(&navmap_errormsg());
 7387:         return(1,$currentphase);
 7388:     }
 7389: 
 7390:     my %found=('ids'=>{},'usernames'=>{});
 7391:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7392: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7393: 	if ($line=~/^[\s\cz]*$/) { next; }
 7394: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7395: 						 $scan_data);
 7396: 	my $id=$$scan_record{'scantron.ID'};
 7397: 	my $found;
 7398: 	foreach my $checkid (keys(%idmap)) {
 7399: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7400: 	}
 7401: 	if ($found) {
 7402: 	    my $username=$idmap{$found};
 7403: 	    if ($found{'ids'}{$found}) {
 7404: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7405: 					 $line,'duplicateID',$found);
 7406: 		return(1,$currentphase);
 7407: 	    } elsif ($found{'usernames'}{$username}) {
 7408: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7409: 					 $line,'duplicateID',$username);
 7410: 		return(1,$currentphase);
 7411: 	    }
 7412: 	    #FIXME store away line we previously saw the ID on to use above
 7413: 	    $found{'ids'}{$found}++;
 7414: 	    $found{'usernames'}{$username}++;
 7415: 	} else {
 7416: 	    if ($id =~ /^\s*$/) {
 7417: 		my $username=&scan_data($scan_data,"$i.user");
 7418: 		if (defined($username) && $found{'usernames'}{$username}) {
 7419: 		    &scantron_get_correction($r,$i,$scan_record,
 7420: 					     \%scantron_config,
 7421: 					     $line,'duplicateID',$username);
 7422: 		    return(1,$currentphase);
 7423: 		} elsif (!defined($username)) {
 7424: 		    &scantron_get_correction($r,$i,$scan_record,
 7425: 					     \%scantron_config,
 7426: 					     $line,'incorrectID');
 7427: 		    return(1,$currentphase);
 7428: 		}
 7429: 		$found{'usernames'}{$username}++;
 7430: 	    } else {
 7431: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7432: 					 $line,'incorrectID');
 7433: 		return(1,$currentphase);
 7434: 	    }
 7435: 	}
 7436:     }
 7437: 
 7438:     return (0,$currentphase+1);
 7439: }
 7440: 
 7441: 
 7442: sub scantron_get_correction {
 7443:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7444:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7445: #FIXME in the case of a duplicated ID the previous line, probably need
 7446: #to show both the current line and the previous one and allow skipping
 7447: #the previous one or the current one
 7448: 
 7449:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7450:         $r->print(
 7451:             '<p class="LC_warning">'
 7452:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7453:                 "<b>$error</b>",
 7454:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7455:            ."</p> \n");
 7456:     } else {
 7457:         $r->print(
 7458:             '<p class="LC_warning">'
 7459:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7460:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7461:            ."</p> \n");
 7462:     }
 7463:     my $message =
 7464:         '<p>'
 7465:        .&mt('The ID on the form is [_1]',
 7466:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7467:        .'<br />'
 7468:        .&mt('The name on the paper is [_1], [_2]',
 7469:             $$scan_record{'scantron.LastName'},
 7470:             $$scan_record{'scantron.FirstName'})
 7471:        .'</p>';
 7472: 
 7473:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7474:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7475:                            # Array populated for doublebubble or
 7476:     my @lines_to_correct;  # missingbubble errors to build javascript
 7477:                            # to validate radio button checking   
 7478: 
 7479:     if ($error =~ /ID$/) {
 7480: 	if ($error eq 'incorrectID') {
 7481: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7482: 		      "</p>\n");
 7483: 	} elsif ($error eq 'duplicateID') {
 7484: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7485: 	}
 7486: 	$r->print($message);
 7487: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7488: 	$r->print("\n<ul><li> ");
 7489: 	#FIXME it would be nice if this sent back the user ID and
 7490: 	#could do partial userID matches
 7491: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7492: 				       'scantron_username','scantron_domain'));
 7493: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7494: 	$r->print("\n:\n".
 7495: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7496: 
 7497: 	$r->print('</li>');
 7498:     } elsif ($error =~ /CODE$/) {
 7499: 	if ($error eq 'incorrectCODE') {
 7500: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7501: 	} elsif ($error eq 'duplicateCODE') {
 7502: 	    $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");
 7503: 	}
 7504:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7505:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7506:                  ."</p>\n");
 7507: 	$r->print($message);
 7508: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7509: 	$r->print("\n<br /> ");
 7510: 	my $i=0;
 7511: 	if ($error eq 'incorrectCODE' 
 7512: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7513: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7514: 	    if ($closest > 0) {
 7515: 		foreach my $testcode (@{$closest}) {
 7516: 		    my $checked='';
 7517: 		    if (!$i) { $checked=' checked="checked"'; }
 7518: 		    $r->print("
 7519:    <label>
 7520:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7521:        ".&mt("Use the similar CODE [_1] instead.",
 7522: 	    "<b><tt>".$testcode."</tt></b>")."
 7523:     </label>
 7524:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7525: 		    $r->print("\n<br />");
 7526: 		    $i++;
 7527: 		}
 7528: 	    }
 7529: 	}
 7530: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7531: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7532: 	    $r->print("
 7533:     <label>
 7534:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7535:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7536: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7537:     </label>");
 7538: 	    $r->print("\n<br />");
 7539: 	}
 7540: 
 7541: 	$r->print(<<ENDSCRIPT);
 7542: <script type="text/javascript">
 7543: function change_radio(field) {
 7544:     var slct=document.scantronupload.scantron_CODE_resolution;
 7545:     var i;
 7546:     for (i=0;i<slct.length;i++) {
 7547:         if (slct[i].value==field) { slct[i].checked=true; }
 7548:     }
 7549: }
 7550: </script>
 7551: ENDSCRIPT
 7552: 	my $href="/adm/pickcode?".
 7553: 	   "form=".&escape("scantronupload").
 7554: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7555: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7556: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7557: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7558: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7559: 	    $r->print("
 7560:     <label>
 7561:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7562:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7563: 	     "<a target='_blank' href='$href'>","</a>")."
 7564:     </label> 
 7565:     ".&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\')" />'));
 7566: 	    $r->print("\n<br />");
 7567: 	}
 7568: 	$r->print("
 7569:     <label>
 7570:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7571:        ".&mt("Use [_1] as the CODE.",
 7572: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7573: 	$r->print("\n<br /><br />");
 7574:     } elsif ($error eq 'doublebubble') {
 7575: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7576: 
 7577: 	# The form field scantron_questions is acutally a list of line numbers.
 7578: 	# represented by this form so:
 7579: 
 7580: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7581:                                                 $respnumlookup,$startline);
 7582: 
 7583: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7584: 		  $line_list.'" />');
 7585: 	$r->print($message);
 7586: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7587: 	foreach my $question (@{$arg}) {
 7588: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7589:                                                    $scan_record, $error,
 7590:                                                    $randomorder,$randompick,
 7591:                                                    $respnumlookup,$startline);
 7592:             push(@lines_to_correct,@linenums);
 7593: 	}
 7594:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7595:     } elsif ($error eq 'missingbubble') {
 7596: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7597: 	$r->print($message);
 7598: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7599: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7600: 
 7601: 	# The form field scantron_questions is actually a list of line numbers not
 7602: 	# a list of question numbers. Therefore:
 7603: 	#
 7604: 	
 7605: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7606:                                                 $respnumlookup,$startline);
 7607: 
 7608: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7609: 		  $line_list.'" />');
 7610: 	foreach my $question (@{$arg}) {
 7611: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7612:                                                    $scan_record, $error,
 7613:                                                    $randomorder,$randompick,
 7614:                                                    $respnumlookup,$startline);
 7615:             push(@lines_to_correct,@linenums);
 7616: 	}
 7617:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7618:     } else {
 7619: 	$r->print("\n<ul>");
 7620:     }
 7621:     $r->print("\n</li></ul>");
 7622: }
 7623: 
 7624: sub verify_bubbles_checked {
 7625:     my (@ansnums) = @_;
 7626:     my $ansnumstr = join('","',@ansnums);
 7627:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7628:     my $output = (<<ENDSCRIPT);
 7629: <script type="text/javascript">
 7630: function verify_bubble_radio(form) {
 7631:     var ansnumArray = new Array ("$ansnumstr");
 7632:     var need_bubble_count = 0;
 7633:     for (var i=0; i<ansnumArray.length; i++) {
 7634:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7635:             var bubble_picked = 0; 
 7636:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7637:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7638:                     bubble_picked = 1;
 7639:                 }
 7640:             }
 7641:             if (bubble_picked == 0) {
 7642:                 need_bubble_count ++;
 7643:             }
 7644:         }
 7645:     }
 7646:     if (need_bubble_count) {
 7647:         alert("$warning");
 7648:         return;
 7649:     }
 7650:     form.submit(); 
 7651: }
 7652: </script>
 7653: ENDSCRIPT
 7654:     return $output;
 7655: }
 7656: 
 7657: =pod
 7658: 
 7659: =item  questions_to_line_list
 7660: 
 7661: Converts a list of questions into a string of comma separated
 7662: line numbers in the answer sheet used by the questions.  This is
 7663: used to fill in the scantron_questions form field.
 7664: 
 7665:   Arguments:
 7666:      questions    - Reference to an array of questions.
 7667:      randomorder  - True if randomorder in use.
 7668:      randompick   - True if randompick in use.
 7669:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7670:                      for current line to question number used for same question
 7671:                      in "Master Seqence" (as seen by Course Coordinator).
 7672:      startline    - Reference to hash where key is question number (0 is first)
 7673:                     and key is number of first bubble line for current student
 7674:                     or code-based randompick and/or randomorder.
 7675: 
 7676: =cut
 7677: 
 7678: 
 7679: sub questions_to_line_list {
 7680:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7681:     my @lines;
 7682: 
 7683:     foreach my $item (@{$questions}) {
 7684:         my $question = $item;
 7685:         my ($first,$count,$last);
 7686:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7687:             $question = $1;
 7688:             my $subquestion = $2;
 7689:             my $responsenum = $question-1;
 7690:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7691:                 $responsenum = $respnumlookup->{$question-1};
 7692:                 if (ref($startline) eq 'HASH') {
 7693:                     $first = $startline->{$question-1} + 1;
 7694:                 }
 7695:             } else {
 7696:                 $first = $first_bubble_line{$responsenum} + 1;
 7697:             }
 7698:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7699:             my $subcount = 1;
 7700:             while ($subcount<$subquestion) {
 7701:                 $first += $subans[$subcount-1];
 7702:                 $subcount ++;
 7703:             }
 7704:             $count = $subans[$subquestion-1];
 7705:         } else {
 7706:             my $responsenum = $question-1;
 7707:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7708:                 $responsenum = $respnumlookup->{$question-1};
 7709:                 if (ref($startline) eq 'HASH') {
 7710:                     $first = $startline->{$question-1} + 1;
 7711:                 }
 7712:             } else {
 7713:                 $first = $first_bubble_line{$responsenum} + 1;
 7714:             }
 7715:             $count   = $bubble_lines_per_response{$responsenum};
 7716:         }
 7717:         $last = $first+$count-1;
 7718:         push(@lines, ($first..$last));
 7719:     }
 7720:     return join(',', @lines);
 7721: }
 7722: 
 7723: =pod 
 7724: 
 7725: =item prompt_for_corrections
 7726: 
 7727: Prompts for a potentially multiline correction to the
 7728: user's bubbling (factors out common code from scantron_get_correction
 7729: for multi and missing bubble cases).
 7730: 
 7731:  Arguments:
 7732:    $r           - Apache request object.
 7733:    $question    - The question number to prompt for.
 7734:    $scan_config - The scantron file configuration hash.
 7735:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7736:    $error       - Type of error
 7737:    $randomorder - True if randomorder in use.
 7738:    $randompick  - True if randompick in use.
 7739:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7740:                     for current line to question number used for same question
 7741:                     in "Master Seqence" (as seen by Course Coordinator).
 7742:    $startline   - Reference to hash where key is question number (0 is first)
 7743:                   and value is number of first bubble line for current student
 7744:                   or code-based randompick and/or randomorder.
 7745: 
 7746:  Implicit inputs:
 7747:    %bubble_lines_per_response   - Starting line numbers for each question.
 7748:                                   Numbered from 0 (but question numbers are from
 7749:                                   1.
 7750:    %first_bubble_line           - Starting bubble line for each question.
 7751:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7752:                                   type problems render as separate sub-questions, 
 7753:                                   in exam mode. This hash contains a 
 7754:                                   comma-separated list of the lines per 
 7755:                                   sub-question.
 7756:    %responsetype_per_response   - essayresponse, formularesponse,
 7757:                                   stringresponse, imageresponse, reactionresponse,
 7758:                                   and organicresponse type problem parts can have
 7759:                                   multiple lines per response if the weight
 7760:                                   assigned exceeds 10.  In this case, only
 7761:                                   one bubble per line is permitted, but more 
 7762:                                   than one line might contain bubbles, e.g.
 7763:                                   bubbling of: line 1 - J, line 2 - J, 
 7764:                                   line 3 - B would assign 22 points.  
 7765: 
 7766: =cut
 7767: 
 7768: sub prompt_for_corrections {
 7769:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7770:         $randompick, $respnumlookup, $startline) = @_;
 7771:     my ($current_line,$lines);
 7772:     my @linenums;
 7773:     my $questionnum = $question;
 7774:     my ($first,$responsenum);
 7775:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7776:         $question = $1;
 7777:         my $subquestion = $2;
 7778:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7779:             $responsenum = $respnumlookup->{$question-1};
 7780:             if (ref($startline) eq 'HASH') {
 7781:                 $first = $startline->{$question-1};
 7782:             }
 7783:         } else {
 7784:             $responsenum = $question-1;
 7785:             $first = $first_bubble_line{$responsenum};
 7786:         }
 7787:         $current_line = $first + 1 ;
 7788:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7789:         my $subcount = 1;
 7790:         while ($subcount<$subquestion) {
 7791:             $current_line += $subans[$subcount-1];
 7792:             $subcount ++;
 7793:         }
 7794:         $lines = $subans[$subquestion-1];
 7795:     } else {
 7796:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7797:             $responsenum = $respnumlookup->{$question-1};
 7798:             if (ref($startline) eq 'HASH') {
 7799:                 $first = $startline->{$question-1};
 7800:             }
 7801:         } else {
 7802:             $responsenum = $question-1;
 7803:             $first = $first_bubble_line{$responsenum};
 7804:         }
 7805:         $current_line = $first + 1;
 7806:         $lines        = $bubble_lines_per_response{$responsenum};
 7807:     }
 7808:     if ($lines > 1) {
 7809:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7810:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7811:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7812:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7813:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7814:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7815:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7816:             $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 />');
 7817:         } else {
 7818:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7819:         }
 7820:     }
 7821:     for (my $i =0; $i < $lines; $i++) {
 7822:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7823: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7824: 	        		  $questionnum,$error,split('', $selected));
 7825:         push(@linenums,$current_line);
 7826: 	$current_line++;
 7827:     }
 7828:     if ($lines > 1) {
 7829: 	$r->print("<hr /><br />");
 7830:     }
 7831:     return @linenums;
 7832: }
 7833: 
 7834: =pod
 7835: 
 7836: =item scantron_bubble_selector
 7837:   
 7838:    Generates the html radiobuttons to correct a single bubble line
 7839:    possibly showing the existing the selected bubbles if known
 7840: 
 7841:  Arguments:
 7842:     $r           - Apache request object
 7843:     $scan_config - hash from &get_scantron_config()
 7844:     $line        - Number of the line being displayed.
 7845:     $questionnum - Question number (may include subquestion)
 7846:     $error       - Type of error.
 7847:     @selected    - Array of bubbles picked on this line.
 7848: 
 7849: =cut
 7850: 
 7851: sub scantron_bubble_selector {
 7852:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7853:     my $max=$$scan_config{'Qlength'};
 7854: 
 7855:     my $scmode=$$scan_config{'Qon'};
 7856:     if ($scmode eq 'number' || $scmode eq 'letter') {
 7857:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7858:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7859:             $max=$$scan_config{'BubblesPerRow'};
 7860:             if (($scmode eq 'number') && ($max > 10)) {
 7861:                 $max = 10;
 7862:             } elsif (($scmode eq 'letter') && $max > 26) {
 7863:                 $max = 26;
 7864:             }
 7865:         } else {
 7866:             $max = 10;
 7867:         }
 7868:     }
 7869: 
 7870:     my @alphabet=('A'..'Z');
 7871:     $r->print(&Apache::loncommon::start_data_table().
 7872:               &Apache::loncommon::start_data_table_row());
 7873:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7874:     for (my $i=0;$i<$max+1;$i++) {
 7875: 	$r->print("\n".'<td align="center">');
 7876: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7877: 	else { $r->print('&nbsp;'); }
 7878: 	$r->print('</td>');
 7879:     }
 7880:     $r->print(&Apache::loncommon::end_data_table_row().
 7881:               &Apache::loncommon::start_data_table_row());
 7882:     for (my $i=0;$i<$max;$i++) {
 7883: 	$r->print("\n".
 7884: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7885: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7886:     }
 7887:     my $nobub_checked = ' ';
 7888:     if ($error eq 'missingbubble') {
 7889:         $nobub_checked = ' checked = "checked" ';
 7890:     }
 7891:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7892: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7893:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7894:               $line.'" value="'.$questionnum.'" /></td>');
 7895:     $r->print(&Apache::loncommon::end_data_table_row().
 7896:               &Apache::loncommon::end_data_table());
 7897: }
 7898: 
 7899: =pod
 7900: 
 7901: =item num_matches
 7902: 
 7903:    Counts the number of characters that are the same between the two arguments.
 7904: 
 7905:  Arguments:
 7906:    $orig - CODE from the scanline
 7907:    $code - CODE to match against
 7908: 
 7909:  Returns:
 7910:    $count - integer count of the number of same characters between the
 7911:             two arguments
 7912: 
 7913: =cut
 7914: 
 7915: sub num_matches {
 7916:     my ($orig,$code) = @_;
 7917:     my @code=split(//,$code);
 7918:     my @orig=split(//,$orig);
 7919:     my $same=0;
 7920:     for (my $i=0;$i<scalar(@code);$i++) {
 7921: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7922:     }
 7923:     return $same;
 7924: }
 7925: 
 7926: =pod
 7927: 
 7928: =item scantron_get_closely_matching_CODEs
 7929: 
 7930:    Cycles through all CODEs and finds the set that has the greatest
 7931:    number of same characters as the provided CODE
 7932: 
 7933:  Arguments:
 7934:    $allcodes - hash ref returned by &get_codes()
 7935:    $CODE     - CODE from the current scanline
 7936: 
 7937:  Returns:
 7938:    2 element list
 7939:     - first elements is number of how closely matching the best fit is 
 7940:       (5 means best set has 5 matching characters)
 7941:     - second element is an arrary ref containing the set of valid CODEs
 7942:       that best fit the passed in CODE
 7943: 
 7944: =cut
 7945: 
 7946: sub scantron_get_closely_matching_CODEs {
 7947:     my ($allcodes,$CODE)=@_;
 7948:     my @CODEs;
 7949:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7950: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7951:     }
 7952: 
 7953:     return ($#CODEs,$CODEs[-1]);
 7954: }
 7955: 
 7956: =pod
 7957: 
 7958: =item get_codes
 7959: 
 7960:    Builds a hash which has keys of all of the valid CODEs from the selected
 7961:    set of remembered CODEs.
 7962: 
 7963:  Arguments:
 7964:   $old_name - name of the set of remembered CODEs
 7965:   $cdom     - domain of the course
 7966:   $cnum     - internal course name
 7967: 
 7968:  Returns:
 7969:   %allcodes - keys are the valid CODEs, values are all 1
 7970: 
 7971: =cut
 7972: 
 7973: sub get_codes {
 7974:     my ($old_name, $cdom, $cnum) = @_;
 7975:     if (!$old_name) {
 7976: 	$old_name=$env{'form.scantron_CODElist'};
 7977:     }
 7978:     if (!$cdom) {
 7979: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7980:     }
 7981:     if (!$cnum) {
 7982: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7983:     }
 7984:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7985: 				    $cdom,$cnum);
 7986:     my %allcodes;
 7987:     if ($result{"type\0$old_name"} eq 'number') {
 7988: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7989:     } else {
 7990: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7991:     }
 7992:     return %allcodes;
 7993: }
 7994: 
 7995: =pod
 7996: 
 7997: =item scantron_validate_CODE
 7998: 
 7999:    Validates all scanlines in the selected file to not have any
 8000:    invalid or underspecified CODEs and that none of the codes are
 8001:    duplicated if this was requested.
 8002: 
 8003: =cut
 8004: 
 8005: sub scantron_validate_CODE {
 8006:     my ($r,$currentphase) = @_;
 8007:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8008:     if ($scantron_config{'CODElocation'} &&
 8009: 	$scantron_config{'CODEstart'} &&
 8010: 	$scantron_config{'CODElength'}) {
 8011: 	if (!defined($env{'form.scantron_CODElist'})) {
 8012: 	    &FIXME_blow_up()
 8013: 	}
 8014:     } else {
 8015: 	return (0,$currentphase+1);
 8016:     }
 8017:     
 8018:     my %usedCODEs;
 8019: 
 8020:     my %allcodes=&get_codes();
 8021: 
 8022:     my $nav_error;
 8023:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8024:     if ($nav_error) {
 8025:         $r->print(&navmap_errormsg());
 8026:         return(1,$currentphase);
 8027:     }
 8028: 
 8029:     my ($scanlines,$scan_data)=&scantron_getfile();
 8030:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8031: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8032: 	if ($line=~/^[\s\cz]*$/) { next; }
 8033: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8034: 						 $scan_data);
 8035: 	my $CODE=$$scan_record{'scantron.CODE'};
 8036: 	my $error=0;
 8037: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8038: 	    &scantron_get_correction($r,$i,$scan_record,
 8039: 				     \%scantron_config,
 8040: 				     $line,'incorrectCODE',\%allcodes);
 8041: 	    return(1,$currentphase);
 8042: 	}
 8043: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8044: 	    && !$$scan_record{'scantron.useCODE'}) {
 8045: 	    &scantron_get_correction($r,$i,$scan_record,
 8046: 				     \%scantron_config,
 8047: 				     $line,'incorrectCODE',\%allcodes);
 8048: 	    return(1,$currentphase);
 8049: 	}
 8050: 	if (exists($usedCODEs{$CODE}) 
 8051: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8052: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8053: 	    &scantron_get_correction($r,$i,$scan_record,
 8054: 				     \%scantron_config,
 8055: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8056: 	    return(1,$currentphase);
 8057: 	}
 8058: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8059:     }
 8060:     return (0,$currentphase+1);
 8061: }
 8062: 
 8063: =pod
 8064: 
 8065: =item scantron_validate_doublebubble
 8066: 
 8067:    Validates all scanlines in the selected file to not have any
 8068:    bubble lines with multiple bubbles marked.
 8069: 
 8070: =cut
 8071: 
 8072: sub scantron_validate_doublebubble {
 8073:     my ($r,$currentphase) = @_;
 8074:     #get student info
 8075:     my $classlist=&Apache::loncoursedata::get_classlist();
 8076:     my %idmap=&username_to_idmap($classlist);
 8077:     my (undef,undef,$sequence)=
 8078:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8079: 
 8080:     #get scantron line setup
 8081:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8082:     my ($scanlines,$scan_data)=&scantron_getfile();
 8083: 
 8084:     my $navmap = Apache::lonnavmaps::navmap->new();
 8085:     unless (ref($navmap)) {
 8086:         $r->print(&navmap_errormsg());
 8087:         return(1,$currentphase);
 8088:     }
 8089:     my $map=$navmap->getResourceByUrl($sequence);
 8090:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8091:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8092:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8093:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8094: 
 8095:     my $nav_error;
 8096:     if (ref($map)) {
 8097:         $randomorder = $map->randomorder();
 8098:         $randompick = $map->randompick();
 8099:         if ($randomorder || $randompick) {
 8100:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8101:             if ($nav_error) {
 8102:                 $r->print(&navmap_errormsg());
 8103:                 return(1,$currentphase);
 8104:             }
 8105:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8106:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8107:         }
 8108:     } else {
 8109:         $r->print(&navmap_errormsg());
 8110:         return(1,$currentphase);
 8111:     }
 8112: 
 8113:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8114:     if ($nav_error) {
 8115:         $r->print(&navmap_errormsg());
 8116:         return(1,$currentphase);
 8117:     }
 8118: 
 8119:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8120: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8121: 	if ($line=~/^[\s\cz]*$/) { next; }
 8122: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8123: 						 $scan_data,undef,\%idmap,$randomorder,
 8124:                                                  $randompick,$sequence,\@master_seq,
 8125:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8126:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8127: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8128: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8129: 				 'doublebubble',
 8130: 				 $$scan_record{'scantron.doubleerror'},
 8131:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8132:     	return (1,$currentphase);
 8133:     }
 8134:     return (0,$currentphase+1);
 8135: }
 8136: 
 8137: 
 8138: sub scantron_get_maxbubble {
 8139:     my ($nav_error,$scantron_config) = @_;
 8140:     if (defined($env{'form.scantron_maxbubble'}) &&
 8141: 	$env{'form.scantron_maxbubble'}) {
 8142: 	&restore_bubble_lines();
 8143: 	return $env{'form.scantron_maxbubble'};
 8144:     }
 8145: 
 8146:     my (undef, undef, $sequence) =
 8147: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8148: 
 8149:     my $navmap=Apache::lonnavmaps::navmap->new();
 8150:     unless (ref($navmap)) {
 8151:         if (ref($nav_error)) {
 8152:             $$nav_error = 1;
 8153:         }
 8154:         return;
 8155:     }
 8156:     my $map=$navmap->getResourceByUrl($sequence);
 8157:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8158:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8159: 
 8160:     &Apache::lonxml::clear_problem_counter();
 8161: 
 8162:     my $uname       = $env{'user.name'};
 8163:     my $udom        = $env{'user.domain'};
 8164:     my $cid         = $env{'request.course.id'};
 8165:     my $total_lines = 0;
 8166:     %bubble_lines_per_response = ();
 8167:     %first_bubble_line         = ();
 8168:     %subdivided_bubble_lines   = ();
 8169:     %responsetype_per_response = ();
 8170:     %masterseq_id_responsenum  = ();
 8171: 
 8172:     my $response_number = 0;
 8173:     my $bubble_line     = 0;
 8174:     foreach my $resource (@resources) {
 8175:         my $resid = $resource->id();
 8176:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8177:                                                           $udom,undef,$bubbles_per_row);
 8178:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8179: 	    foreach my $part_id (@{$parts}) {
 8180:                 my $lines;
 8181: 
 8182: 	        # TODO - make this a persistent hash not an array.
 8183: 
 8184:                 # optionresponse, matchresponse and rankresponse type items 
 8185:                 # render as separate sub-questions in exam mode.
 8186:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8187:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8188:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8189:                     my ($numbub,$numshown);
 8190:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8191:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8192:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8193:                         }
 8194:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8195:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8196:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8197:                         }
 8198:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8199:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8200:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8201:                         }
 8202:                     }
 8203:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8204:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8205:                     }
 8206:                     my $bubbles_per_row =
 8207:                         &bubblesheet_bubbles_per_row($scantron_config);
 8208:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8209:                     if (($numbub % $bubbles_per_row) != 0) {
 8210:                         $inner_bubble_lines++;
 8211:                     }
 8212:                     for (my $i=0; $i<$numshown; $i++) {
 8213:                         $subdivided_bubble_lines{$response_number} .= 
 8214:                             $inner_bubble_lines.',';
 8215:                     }
 8216:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8217:                     $lines = $numshown * $inner_bubble_lines;
 8218:                 } else {
 8219:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8220:                 }
 8221: 
 8222:                 $first_bubble_line{$response_number} = $bubble_line;
 8223: 	        $bubble_lines_per_response{$response_number} = $lines;
 8224:                 $responsetype_per_response{$response_number} = 
 8225:                     $analysis->{$part_id.'.type'};
 8226:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8227: 	        $response_number++;
 8228: 
 8229: 	        $bubble_line +=  $lines;
 8230: 	        $total_lines +=  $lines;
 8231: 	    }
 8232:         }
 8233:     }
 8234:     &Apache::lonnet::delenv('scantron.');
 8235: 
 8236:     &save_bubble_lines();
 8237:     $env{'form.scantron_maxbubble'} =
 8238: 	$total_lines;
 8239:     return $env{'form.scantron_maxbubble'};
 8240: }
 8241: 
 8242: sub bubblesheet_bubbles_per_row {
 8243:     my ($scantron_config) = @_;
 8244:     my $bubbles_per_row;
 8245:     if (ref($scantron_config) eq 'HASH') {
 8246:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8247:     }
 8248:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8249:         $bubbles_per_row = 10;
 8250:     }
 8251:     return $bubbles_per_row;
 8252: }
 8253: 
 8254: sub scantron_validate_missingbubbles {
 8255:     my ($r,$currentphase) = @_;
 8256:     #get student info
 8257:     my $classlist=&Apache::loncoursedata::get_classlist();
 8258:     my %idmap=&username_to_idmap($classlist);
 8259:     my (undef,undef,$sequence)=
 8260:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8261: 
 8262:     #get scantron line setup
 8263:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8264:     my ($scanlines,$scan_data)=&scantron_getfile();
 8265: 
 8266:     my $navmap = Apache::lonnavmaps::navmap->new();
 8267:     unless (ref($navmap)) {
 8268:         $r->print(&navmap_errormsg());
 8269:         return(1,$currentphase);
 8270:     }
 8271: 
 8272:     my $map=$navmap->getResourceByUrl($sequence);
 8273:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8274:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8275:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8276:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8277: 
 8278:     my $nav_error;
 8279:     if (ref($map)) {
 8280:         $randomorder = $map->randomorder();
 8281:         $randompick = $map->randompick();
 8282:         if ($randomorder || $randompick) {
 8283:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8284:             if ($nav_error) {
 8285:                 $r->print(&navmap_errormsg());
 8286:                 return(1,$currentphase);
 8287:             }
 8288:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8289:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8290:         }
 8291:     } else {
 8292:         $r->print(&navmap_errormsg());
 8293:         return(1,$currentphase);
 8294:     }
 8295: 
 8296: 
 8297:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8298:     if ($nav_error) {
 8299:         $r->print(&navmap_errormsg());
 8300:         return(1,$currentphase);
 8301:     }
 8302: 
 8303:     if (!$max_bubble) { $max_bubble=2**31; }
 8304:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8305: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8306: 	if ($line=~/^[\s\cz]*$/) { next; }
 8307:         my $scan_record =
 8308:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8309:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8310:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8311:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8312: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8313: 	my @to_correct;
 8314: 	
 8315: 	# Probably here's where the error is...
 8316: 
 8317: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8318:             my $lastbubble;
 8319:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8320:                 my $question = $1;
 8321:                 my $subquestion = $2;
 8322:                 my ($first,$responsenum);
 8323:                 if ($randomorder || $randompick) {
 8324:                     $responsenum = $respnumlookup{$question-1};
 8325:                     $first = $startline{$question-1};
 8326:                 } else {
 8327:                     $responsenum = $question-1;
 8328:                     $first = $first_bubble_line{$responsenum};
 8329:                 }
 8330:                 if (!defined($first)) { next; }
 8331:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8332:                 my $subcount = 1;
 8333:                 while ($subcount<$subquestion) {
 8334:                     $first += $subans[$subcount-1];
 8335:                     $subcount ++;
 8336:                 }
 8337:                 my $count = $subans[$subquestion-1];
 8338:                 $lastbubble = $first + $count;
 8339:             } else {
 8340:                 my ($first,$responsenum);
 8341:                 if ($randomorder || $randompick) {
 8342:                     $responsenum = $respnumlookup{$missing-1};
 8343:                     $first = $startline{$missing-1};
 8344:                 } else {
 8345:                     $responsenum = $missing-1;
 8346:                     $first = $first_bubble_line{$responsenum};
 8347:                 }
 8348:                 if (!defined($first)) { next; }
 8349:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8350:             }
 8351:             if ($lastbubble > $max_bubble) { next; }
 8352: 	    push(@to_correct,$missing);
 8353: 	}
 8354: 	if (@to_correct) {
 8355: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8356: 				     $line,'missingbubble',\@to_correct,
 8357:                                      $randomorder,$randompick,\%respnumlookup,
 8358:                                      \%startline);
 8359: 	    return (1,$currentphase);
 8360: 	}
 8361: 
 8362:     }
 8363:     return (0,$currentphase+1);
 8364: }
 8365: 
 8366: sub hand_bubble_option {
 8367:     my (undef, undef, $sequence) =
 8368:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8369:     return if ($sequence eq '');
 8370:     my $navmap = Apache::lonnavmaps::navmap->new();
 8371:     unless (ref($navmap)) {
 8372:         return;
 8373:     }
 8374:     my $needs_hand_bubbles;
 8375:     my $map=$navmap->getResourceByUrl($sequence);
 8376:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8377:     foreach my $res (@resources) {
 8378:         if (ref($res)) {
 8379:             if ($res->is_problem()) {
 8380:                 my $partlist = $res->parts();
 8381:                 foreach my $part (@{ $partlist }) {
 8382:                     my @types = $res->responseType($part);
 8383:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8384:                         $needs_hand_bubbles = 1;
 8385:                         last;
 8386:                     }
 8387:                 }
 8388:             }
 8389:         }
 8390:     }
 8391:     if ($needs_hand_bubbles) {
 8392:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8393:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8394:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8395:                &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 />').
 8396:                '<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;'.
 8397:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8398:     }
 8399:     return;
 8400: }
 8401: 
 8402: sub scantron_process_students {
 8403:     my ($r) = @_;
 8404: 
 8405:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8406:     my ($symb)=&get_symb($r);
 8407:     if (!$symb) {
 8408: 	return '';
 8409:     }
 8410:     my $default_form_data=&defaultFormData($symb);
 8411: 
 8412:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8413:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8414:     my ($scanlines,$scan_data)=&scantron_getfile();
 8415:     my $classlist=&Apache::loncoursedata::get_classlist();
 8416:     my %idmap=&username_to_idmap($classlist);
 8417:     my $navmap=Apache::lonnavmaps::navmap->new();
 8418:     unless (ref($navmap)) {
 8419:         $r->print(&navmap_errormsg());
 8420:         return '';
 8421:     }
 8422:     my $map=$navmap->getResourceByUrl($sequence);
 8423:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8424:         %grader_randomlists_by_symb);
 8425:     if (ref($map)) {
 8426:         $randomorder = $map->randomorder();
 8427:         $randompick = $map->randompick();
 8428:     } else {
 8429:         $r->print(&navmap_errormsg());
 8430:         return '';
 8431:     }
 8432:     my $nav_error;
 8433:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8434:     if ($randomorder || $randompick) {
 8435:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8436:         if ($nav_error) {
 8437:             $r->print(&navmap_errormsg());
 8438:             return '';
 8439:         }
 8440:     }
 8441:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8442:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8443: 
 8444:     my ($uname,$udom);
 8445:     my $result= <<SCANTRONFORM;
 8446: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8447:   <input type="hidden" name="command" value="scantron_configphase" />
 8448:   $default_form_data
 8449: SCANTRONFORM
 8450:     $r->print($result);
 8451: 
 8452:     my @delayqueue;
 8453:     my (%completedstudents,%scandata);
 8454:     
 8455:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8456:     my $count=&get_todo_count($scanlines,$scan_data);
 8457:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8458:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8459: 					  'Processing first student');
 8460:     $r->print('<br />');
 8461:     my $start=&Time::HiRes::time();
 8462:     my $i=-1;
 8463:     my $started;
 8464: 
 8465:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8466:     if ($nav_error) {
 8467:         $r->print(&navmap_errormsg());
 8468:         return '';
 8469:     }
 8470: 
 8471:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8472:     # the user and return.
 8473: 
 8474:     if ($ssi_error) {
 8475: 	$r->print("</form>");
 8476: 	&ssi_print_error($r);
 8477: 	$r->print(&show_grading_menu_form($symb));
 8478:         &Apache::lonnet::remove_lock($lock);
 8479: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8480:     }
 8481: 
 8482:     my %lettdig = &letter_to_digits();
 8483:     my $numletts = scalar(keys(%lettdig));
 8484:     my %orderedforcode;
 8485: 
 8486:     while ($i<$scanlines->{'count'}) {
 8487:  	($uname,$udom)=('','');
 8488:  	$i++;
 8489:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8490:  	if ($line=~/^[\s\cz]*$/) { next; }
 8491: 	if ($started) {
 8492: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8493: 						     'last student');
 8494: 	}
 8495: 	$started=1;
 8496:         my %respnumlookup = ();
 8497:         my %startline = ();
 8498:         my $total;
 8499:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8500:  						 $scan_data,undef,\%idmap,$randomorder,
 8501:                                                  $randompick,$sequence,\@master_seq,
 8502:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8503:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8504:                                                  \$total);
 8505:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8506:  					      \%idmap,$i)) {
 8507:   	    &scantron_add_delay(\@delayqueue,$line,
 8508:  				'Unable to find a student that matches',1);
 8509:  	    next;
 8510:   	}
 8511:  	if (exists $completedstudents{$uname}) {
 8512:  	    &scantron_add_delay(\@delayqueue,$line,
 8513:  				'Student '.$uname.' has multiple sheets',2);
 8514:  	    next;
 8515:  	}
 8516:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8517:         my $user = $uname.':'.$usec;
 8518:   	($uname,$udom)=split(/:/,$uname);
 8519: 
 8520:         my $scancode;
 8521:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8522:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8523:             $scancode = $scan_record->{'scantron.CODE'};
 8524:         } else {
 8525:             $scancode = '';
 8526:         }
 8527: 
 8528:         my @mapresources = @resources;
 8529:         if ($randomorder || $randompick) {
 8530:             @mapresources =
 8531:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8532:                              \%orderedforcode);
 8533:         }
 8534:         my (%partids_by_symb,$res_error);
 8535:         foreach my $resource (@mapresources) {
 8536:             my $ressymb;
 8537:             if (ref($resource)) {
 8538:                 $ressymb = $resource->symb();
 8539:             } else {
 8540:                 $res_error = 1;
 8541:                 last;
 8542:             }
 8543:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8544:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8545:                 my ($analysis,$parts) =
 8546:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8547:                                               $uname,$udom,undef,$bubbles_per_row);
 8548:                 $partids_by_symb{$ressymb} = $parts;
 8549:             } else {
 8550:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8551:             }
 8552:         }
 8553: 
 8554:         if ($res_error) {
 8555:             &scantron_add_delay(\@delayqueue,$line,
 8556:                                 'An error occurred while grading student '.$uname,2);
 8557:             next;
 8558:         }
 8559: 
 8560: 	&Apache::lonxml::clear_problem_counter();
 8561:   	&Apache::lonnet::appenv($scan_record);
 8562: 
 8563: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8564: 	    &scantron_putfile($scanlines,$scan_data);
 8565: 	}
 8566: 	
 8567:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8568:                                    \@mapresources,\%partids_by_symb,
 8569:                                    $bubbles_per_row,$randomorder,$randompick,
 8570:                                    \%respnumlookup,\%startline) 
 8571:             eq 'ssi_error') {
 8572:             $ssi_error = 0; # So end of handler error message does not trigger.
 8573:             $r->print("</form>");
 8574:             &ssi_print_error($r);
 8575:             $r->print(&show_grading_menu_form($symb));
 8576:             &Apache::lonnet::remove_lock($lock);
 8577:             return '';      # Why return ''?  Beats me.
 8578:         }
 8579: 
 8580:         if (($scancode) && ($randomorder || $randompick)) {
 8581:             my $parmresult =
 8582:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8583:                                                        '0_examcode',2,$scancode,
 8584:                                                        'string_examcode',$uname,
 8585:                                                        $udom);
 8586:         }
 8587: 	$completedstudents{$uname}={'line'=>$line};
 8588:         if ($env{'form.verifyrecord'}) {
 8589:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8590:             if ($randompick) {
 8591:                 if ($total) {
 8592:                     $lastpos = $total*$scantron_config{'Qlength'};
 8593:                 }
 8594:             }
 8595: 
 8596:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8597:             chomp($studentdata);
 8598:             $studentdata =~ s/\r$//;
 8599:             my $studentrecord = '';
 8600:             my $counter = -1;
 8601:             foreach my $resource (@mapresources) {
 8602:                 my $ressymb = $resource->symb();
 8603:                 ($counter,my $recording) =
 8604:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8605:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8606:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8607:                                              $randompick,\%respnumlookup,\%startline);
 8608:                 $studentrecord .= $recording;
 8609:             }
 8610:             if ($studentrecord ne $studentdata) {
 8611:                 &Apache::lonxml::clear_problem_counter();
 8612:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8613:                                            \@mapresources,\%partids_by_symb,
 8614:                                            $bubbles_per_row,$randomorder,$randompick,
 8615:                                            \%respnumlookup,\%startline)
 8616:                     eq 'ssi_error') {
 8617:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8618:                     $r->print("</form>");
 8619:                     &ssi_print_error($r);
 8620:                     $r->print(&show_grading_menu_form($symb));
 8621:                     &Apache::lonnet::remove_lock($lock);
 8622:                     delete($completedstudents{$uname});
 8623:                     return '';
 8624:                 }
 8625:                 $counter = -1;
 8626:                 $studentrecord = '';
 8627:                 foreach my $resource (@mapresources) {
 8628:                     my $ressymb = $resource->symb();
 8629:                     ($counter,my $recording) =
 8630:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8631:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8632:                                                  \%scantron_config,\%lettdig,$numletts,
 8633:                                                  $randomorder,$randompick,\%respnumlookup,
 8634:                                                  \%startline);
 8635:                     $studentrecord .= $recording;
 8636:                 }
 8637:                 if ($studentrecord ne $studentdata) {
 8638:                     $r->print('<p><span class="LC_warning">');
 8639:                     if ($scancode eq '') {
 8640:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8641:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8642:                     } else {
 8643:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8644:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8645:                     }
 8646:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8647:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8648:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8649:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8650:                               &Apache::loncommon::start_data_table_row().
 8651:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8652:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8653:                               &Apache::loncommon::end_data_table_row().
 8654:                               &Apache::loncommon::start_data_table_row().
 8655:                               '<td>'.&mt('Stored submissions').'</td>'.
 8656:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8657:                               &Apache::loncommon::end_data_table_row().
 8658:                               &Apache::loncommon::end_data_table().'</p>');
 8659:                 } else {
 8660:                     $r->print('<br /><span class="LC_warning">'.
 8661:                              &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 />'.
 8662:                              &mt("As a consequence, this user's submission history records two tries.").
 8663:                                  '</span><br />');
 8664:                 }
 8665:             }
 8666:         }
 8667:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8668:     } continue {
 8669: 	&Apache::lonxml::clear_problem_counter();
 8670: 	&Apache::lonnet::delenv('scantron.');
 8671:     }
 8672:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8673:     &Apache::lonnet::remove_lock($lock);
 8674: #    my $lasttime = &Time::HiRes::time()-$start;
 8675: #    $r->print("<p>took $lasttime</p>");
 8676: 
 8677:     $r->print("</form>");
 8678:     $r->print(&show_grading_menu_form($symb));
 8679:     return '';
 8680: }
 8681: 
 8682: sub graders_resources_pass {
 8683:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8684:         $bubbles_per_row) = @_;
 8685:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8686:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8687:         foreach my $resource (@{$resources}) {
 8688:             my $ressymb = $resource->symb();
 8689:             my ($analysis,$parts) =
 8690:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8691:                                           $env{'user.name'},$env{'user.domain'},
 8692:                                           1,$bubbles_per_row);
 8693:             $grader_partids_by_symb->{$ressymb} = $parts;
 8694:             if (ref($analysis) eq 'HASH') {
 8695:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8696:                     $grader_randomlists_by_symb->{$ressymb} =
 8697:                         $analysis->{'parts_withrandomlist'};
 8698:                 }
 8699:             }
 8700:         }
 8701:     }
 8702:     return;
 8703: }
 8704: 
 8705: =pod
 8706: 
 8707: =item users_order
 8708: 
 8709:   Returns array of resources in current map, ordered based on either CODE,
 8710:   if this is a CODEd exam, or based on student's identity if this is a
 8711:   "NAMEd" exam.
 8712: 
 8713:   Should be used when randomorder and/or randompick applied when the 
 8714:   corresponding exam was printed, prior to students completing bubblesheets 
 8715:   for the version of the exam the student received.
 8716: 
 8717: =cut
 8718: 
 8719: sub users_order  {
 8720:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8721:     my @mapresources;
 8722:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8723:         return @mapresources;
 8724:     }
 8725:     if ($scancode) {
 8726:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8727:             @mapresources = @{$orderedforcode->{$scancode}};
 8728:         } else {
 8729:             $env{'form.CODE'} = $scancode;
 8730:             my $actual_seq =
 8731:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8732:                                                                $master_seq,
 8733:                                                                $user,$scancode,1);
 8734:             if (ref($actual_seq) eq 'ARRAY') {
 8735:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8736:                 if (ref($orderedforcode) eq 'HASH') {
 8737:                     if (@mapresources > 0) {
 8738:                         $orderedforcode->{$scancode} = \@mapresources;
 8739:                     }
 8740:                 }
 8741:             }
 8742:             delete($env{'form.CODE'});
 8743:         }
 8744:     } else {
 8745:         my $actual_seq =
 8746:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8747:                                                            $master_seq,
 8748:                                                            $user,undef,1);
 8749:         if (ref($actual_seq) eq 'ARRAY') {
 8750:             @mapresources =
 8751:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8752:         }
 8753:     }
 8754:     return @mapresources;
 8755: }
 8756: 
 8757: sub grade_student_bubbles {
 8758:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8759:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8760:     my $uselookup = 0;
 8761:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8762:         (ref($startline) eq 'HASH')) {
 8763:         $uselookup = 1;
 8764:     }
 8765: 
 8766:     if (ref($resources) eq 'ARRAY') {
 8767:         my $count = 0;
 8768:         foreach my $resource (@{$resources}) {
 8769:             my $ressymb = $resource->symb();
 8770:             my %form = ('submitted'      => 'scantron',
 8771:                         'grade_target'   => 'grade',
 8772:                         'grade_username' => $uname,
 8773:                         'grade_domain'   => $udom,
 8774:                         'grade_courseid' => $env{'request.course.id'},
 8775:                         'grade_symb'     => $ressymb,
 8776:                         'CODE'           => $scancode
 8777:                        );
 8778:             if ($bubbles_per_row ne '') {
 8779:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8780:             }
 8781:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8782:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8783:             }
 8784:             if (ref($parts) eq 'HASH') {
 8785:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8786:                     foreach my $part (@{$parts->{$ressymb}}) {
 8787:                         if ($uselookup) {
 8788:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8789:                         } else {
 8790:                             $form{'scantron_questnum_start.'.$part} =
 8791:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8792:                         }
 8793:                         $count++;
 8794:                     }
 8795:                 }
 8796:             }
 8797:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8798:             return 'ssi_error' if ($ssi_error);
 8799:             last if (&Apache::loncommon::connection_aborted($r));
 8800:         }
 8801:     }
 8802:     return;
 8803: }
 8804: 
 8805: sub scantron_upload_scantron_data {
 8806:     my ($r)=@_;
 8807:     my $dom = $env{'request.role.domain'};
 8808:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8809:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8810:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8811: 							  'domainid',
 8812: 							  'coursename',$dom);
 8813:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8814:                        ('&nbsp'x2).&mt('(shows course personnel)');
 8815:     my ($symb) = &get_symb($r,1);
 8816:     my $default_form_data=&defaultFormData($symb);
 8817:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8818:     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.");
 8819:     $r->print('
 8820: <script type="text/javascript" language="javascript">
 8821:     function checkUpload(formname) {
 8822: 	if (formname.upfile.value == "") {
 8823: 	    alert("'.$nofile_alert.'");
 8824: 	    return false;
 8825: 	}
 8826:         if (formname.courseid.value == "") {
 8827:             alert("'.$nocourseid_alert.'");
 8828:             return false;
 8829:         }
 8830: 	formname.submit();
 8831:     }
 8832: 
 8833:     function ToSyllabus() {
 8834:         var cdom = '."'$dom'".';
 8835:         var cnum = document.rules.courseid.value;
 8836:         if (cdom == "" || cdom == null) {
 8837:             return;
 8838:         }
 8839:         if (cnum == "" || cnum == null) {
 8840:            return;
 8841:         }
 8842:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8843:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8844:         return;
 8845:     }
 8846: 
 8847: </script>
 8848: 
 8849: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8850: 
 8851: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8852: '.$default_form_data.
 8853:   &Apache::lonhtmlcommon::start_pick_box().
 8854:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8855:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8856:   &Apache::lonhtmlcommon::row_closure().
 8857:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8858:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8859:   &Apache::lonhtmlcommon::row_closure().
 8860:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8861:   '<input name="domainid" type="hidden" />'.$domdesc.
 8862:   &Apache::lonhtmlcommon::row_closure().
 8863:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8864:   '<input type="file" name="upfile" size="50" />'.
 8865:   &Apache::lonhtmlcommon::row_closure(1).
 8866:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8867: 
 8868: <input name="command" value="scantronupload_save" type="hidden" />
 8869: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8870: </form>
 8871: ');
 8872:     return '';
 8873: }
 8874: 
 8875: 
 8876: sub scantron_upload_scantron_data_save {
 8877:     my($r)=@_;
 8878:     my ($symb)=&get_symb($r,1);
 8879:     my $doanotherupload=
 8880: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8881: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8882: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8883: 	'</form>'."\n";
 8884:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8885: 	!&Apache::lonnet::allowed('usc',
 8886: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8887: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8888: 	if ($symb) {
 8889: 	    $r->print(&show_grading_menu_form($symb));
 8890: 	} else {
 8891: 	    $r->print($doanotherupload);
 8892: 	}
 8893: 	return '';
 8894:     }
 8895:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8896:     my $uploadedfile;
 8897:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 8898:     if (length($env{'form.upfile'}) < 2) {
 8899:         $r->print(
 8900:             &Apache::lonhtmlcommon::confirm_success(
 8901:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8902:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8903:     } else {
 8904:         my $result = 
 8905:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8906:                                             $env{'form.courseid'},$env{'form.domainid'});
 8907: 	if ($result =~ m{^/uploaded/}) {
 8908:             $r->print(
 8909:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8910:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8911:                         (length($env{'form.upfile'})-1),
 8912:                         '<span class="LC_filename">'.$result.'</span>'));
 8913:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8914:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8915:                                                        $env{'form.courseid'},$uploadedfile));
 8916: 	} else {
 8917:             $r->print(
 8918:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8919:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8920:                           $result,
 8921: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8922: 	}
 8923:     }
 8924:     if ($symb) {
 8925: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8926:     } else {
 8927: 	$r->print($doanotherupload);
 8928:     }
 8929:     return '';
 8930: }
 8931: 
 8932: sub validate_uploaded_scantron_file {
 8933:     my ($cdom,$cname,$fname) = @_;
 8934:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8935:     my @lines;
 8936:     if ($scanlines ne '-1') {
 8937:         @lines=split("\n",$scanlines,-1);
 8938:     }
 8939:     my $output;
 8940:     if (@lines) {
 8941:         my (%counts,$max_match_format);
 8942:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8943:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8944:         my %idmap = &username_to_idmap($classlist);
 8945:         foreach my $key (keys(%idmap)) {
 8946:             my $lckey = lc($key);
 8947:             $idmap{$lckey} = $idmap{$key};
 8948:         }
 8949:         my %unique_formats;
 8950:         my @formatlines = &get_scantronformat_file();
 8951:         foreach my $line (@formatlines) {
 8952:             chomp($line);
 8953:             my @config = split(/:/,$line);
 8954:             my $idstart = $config[5];
 8955:             my $idlength = $config[6];
 8956:             if (($idstart ne '') && ($idlength > 0)) {
 8957:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8958:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8959:                 } else {
 8960:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8961:                 }
 8962:             }
 8963:         }
 8964:         foreach my $key (keys(%unique_formats)) {
 8965:             my ($idstart,$idlength) = split(':',$key);
 8966:             %{$counts{$key}} = (
 8967:                                'found'   => 0,
 8968:                                'total'   => 0,
 8969:                               );
 8970:             foreach my $line (@lines) {
 8971:                 next if ($line =~ /^#/);
 8972:                 next if ($line =~ /^[\s\cz]*$/);
 8973:                 my $id = substr($line,$idstart-1,$idlength);
 8974:                 $id = lc($id);
 8975:                 if (exists($idmap{$id})) {
 8976:                     $counts{$key}{'found'} ++;
 8977:                 }
 8978:                 $counts{$key}{'total'} ++;
 8979:             }
 8980:             if ($counts{$key}{'total'}) {
 8981:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8982:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8983:                     $max_match_pct = $percent_match;
 8984:                     $max_match_format = $key;
 8985:                     $found_match_count = $counts{$key}{'found'};
 8986:                     $max_match_count = $counts{$key}{'total'};
 8987:                 }
 8988:             }
 8989:         }
 8990:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8991:             my $format_descs;
 8992:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8993:             for (my $i=0; $i<$numwithformat; $i++) {
 8994:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8995:                 if ($i<$numwithformat-2) {
 8996:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8997:                 } elsif ($i==$numwithformat-2) {
 8998:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8999:                 } elsif ($i==$numwithformat-1) {
 9000:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9001:                 }
 9002:             }
 9003:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9004:             $output .= '<br />';
 9005:             if ($found_match_count == $max_match_count) {
 9006:                 # 100% matching entries
 9007:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9008:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9009:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9010:                 &mt('Comparison of student IDs in the uploaded file with'.
 9011:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9012:                     ' in the file (for the format defined for [_3]).',
 9013:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9014:             } else {
 9015:                 # Not all entries matching? -> Show warning and additional info
 9016:                 $output .=
 9017:                     &Apache::lonhtmlcommon::confirm_success(
 9018:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9019:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9020:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9021:                     &mt('Comparison of student IDs in the uploaded file with'.
 9022:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9023:                         ' in the file (for the format defined for [_3]).',
 9024:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9025:                     '<p class="LC_info">'.
 9026:                     &mt('A low percentage of matches results from one of the following:').
 9027:                     '</p><ul>'.
 9028:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9029:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9030:                                '<i>'.$cdom.'</i>').'</li>'.
 9031:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9032:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9033:                     '</ul>';
 9034:             }
 9035:         }
 9036:     } else {
 9037:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9038:     }
 9039:     return $output;
 9040: }
 9041: 
 9042: sub valid_file {
 9043:     my ($requested_file)=@_;
 9044:     foreach my $filename (sort(&scantron_filenames())) {
 9045: 	if ($requested_file eq $filename) { return 1; }
 9046:     }
 9047:     return 0;
 9048: }
 9049: 
 9050: sub scantron_download_scantron_data {
 9051:     my ($r)=@_;
 9052:     my ($symb) = &get_symb($r,1);
 9053:     my $default_form_data=&defaultFormData($symb);
 9054:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9055:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9056:     my $file=$env{'form.scantron_selectfile'};
 9057:     if (! &valid_file($file)) {
 9058: 	$r->print('
 9059: 	<p>
 9060: 	    '.&mt('The requested filename was invalid.').'
 9061:         </p>
 9062: ');
 9063: 	$r->print(&show_grading_menu_form($symb));
 9064: 	return;
 9065:     }
 9066:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9067:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9068:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9069:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9070:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9071:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9072:     $r->print('
 9073:     <p>
 9074: 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
 9075: 	      '<a href="'.$orig.'">','</a>').'
 9076:     </p>
 9077:     <p>
 9078: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9079: 	      '<a href="'.$corrected.'">','</a>').'
 9080:     </p>
 9081:     <p>
 9082: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9083: 	      '<a href="'.$skipped.'">','</a>').'
 9084:     </p>
 9085: ');
 9086:     $r->print(&show_grading_menu_form($symb));
 9087:     return '';
 9088: }
 9089: 
 9090: sub checkscantron_results {
 9091:     my ($r) = @_;
 9092:     my ($symb)=&get_symb($r);
 9093:     if (!$symb) {return '';}
 9094:     my $grading_menu_button=&show_grading_menu_form($symb);
 9095:     my $cid = $env{'request.course.id'};
 9096:     my %lettdig = &letter_to_digits();
 9097:     my $numletts = scalar(keys(%lettdig));
 9098:     my $cnum = $env{'course.'.$cid.'.num'};
 9099:     my $cdom = $env{'course.'.$cid.'.domain'};
 9100:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9101:     my %record;
 9102:     my %scantron_config =
 9103:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9104:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9105:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9106:     my $classlist=&Apache::loncoursedata::get_classlist();
 9107:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9108:     my $navmap=Apache::lonnavmaps::navmap->new();
 9109:     unless (ref($navmap)) {
 9110:         $r->print(&navmap_errormsg());
 9111:         return '';
 9112:     }
 9113:     my $map=$navmap->getResourceByUrl($sequence);
 9114:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9115:         %grader_randomlists_by_symb,%orderedforcode);
 9116:     if (ref($map)) {
 9117:         $randomorder=$map->randomorder();
 9118:         $randompick=$map->randompick();
 9119:     }
 9120:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9121:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9122:     if ($nav_error) {
 9123:         $r->print(&navmap_errormsg());
 9124:         return '';
 9125:     }
 9126:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9127:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9128:     my ($uname,$udom);
 9129:     my (%scandata,%lastname,%bylast);
 9130:     $r->print('
 9131: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9132: 
 9133:     my @delayqueue;
 9134:     my %completedstudents;
 9135: 
 9136:     my $count=&get_todo_count($scanlines,$scan_data);
 9137:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9138:     my ($username,$domain,$started);
 9139:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9140:     if ($nav_error) {
 9141:         $r->print(&navmap_errormsg());
 9142:         return '';
 9143:     }
 9144: 
 9145:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9146:                                           'Processing first student');
 9147:     my $start=&Time::HiRes::time();
 9148:     my $i=-1;
 9149: 
 9150:     while ($i<$scanlines->{'count'}) {
 9151:         ($username,$domain,$uname)=('','','');
 9152:         $i++;
 9153:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9154:         if ($line=~/^[\s\cz]*$/) { next; }
 9155:         if ($started) {
 9156:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9157:                                                      'last student');
 9158:         }
 9159:         $started=1;
 9160:         my $scan_record=
 9161:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9162:                                                      $scan_data);
 9163:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9164:                                               \%idmap,$i)) {
 9165:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9166:                                 'Unable to find a student that matches',1);
 9167:             next;
 9168:         }
 9169:         if (exists $completedstudents{$uname}) {
 9170:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9171:                                 'Student '.$uname.' has multiple sheets',2);
 9172:             next;
 9173:         }
 9174:         my $pid = $scan_record->{'scantron.ID'};
 9175:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9176:         push(@{$bylast{$lastname{$pid}}},$pid);
 9177:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9178:         my $user = $uname.':'.$usec;
 9179:         ($username,$domain)=split(/:/,$uname);
 9180: 
 9181:         my $scancode;
 9182:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9183:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9184:             $scancode = $scan_record->{'scantron.CODE'};
 9185:         } else {
 9186:             $scancode = '';
 9187:         }
 9188: 
 9189:         my @mapresources = @resources;
 9190:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9191:         my %respnumlookup=();
 9192:         my %startline=();
 9193:         if ($randomorder || $randompick) {
 9194:             @mapresources =
 9195:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9196:                              \%orderedforcode);
 9197:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9198:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9199:                                              \%grader_partids_by_symb,\%orderedforcode,
 9200:                                              \%respnumlookup,\%startline);
 9201:             if ($randompick && $total) {
 9202:                 $lastpos = $total*$scantron_config{'Qlength'};
 9203:             }
 9204:         }
 9205:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9206:         chomp($scandata{$pid});
 9207:         $scandata{$pid} =~ s/\r$//;
 9208: 
 9209:         my $counter = -1;
 9210:         foreach my $resource (@mapresources) {
 9211:             my $parts;
 9212:             my $ressymb = $resource->symb();
 9213:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9214:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9215:                 (my $analysis,$parts) =
 9216:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9217:                                               $username,$domain,undef,
 9218:                                               $bubbles_per_row);
 9219:             } else {
 9220:                 $parts = $grader_partids_by_symb{$ressymb};
 9221:             }
 9222:             ($counter,my $recording) =
 9223:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9224:                                          $scandata{$pid},$parts,
 9225:                                          \%scantron_config,\%lettdig,$numletts,
 9226:                                          $randomorder,$randompick,
 9227:                                          \%respnumlookup,\%startline);
 9228:             $record{$pid} .= $recording;
 9229:         }
 9230:     }
 9231:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9232:     $r->print('<br />');
 9233:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9234:     $passed = 0;
 9235:     $failed = 0;
 9236:     $numstudents = 0;
 9237:     foreach my $last (sort(keys(%bylast))) {
 9238:         if (ref($bylast{$last}) eq 'ARRAY') {
 9239:             foreach my $pid (sort(@{$bylast{$last}})) {
 9240:                 my $showscandata = $scandata{$pid};
 9241:                 my $showrecord = $record{$pid};
 9242:                 $showscandata =~ s/\s/&nbsp;/g;
 9243:                 $showrecord =~ s/\s/&nbsp;/g;
 9244:                 if ($scandata{$pid} eq $record{$pid}) {
 9245:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9246:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9247: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9248: '</tr>'."\n".
 9249: '<tr class="'.$css_class.'">'."\n".
 9250: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9251:                     $passed ++;
 9252:                 } else {
 9253:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9254:                     $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".
 9255: '</tr>'."\n".
 9256: '<tr class="'.$css_class.'">'."\n".
 9257: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9258: '</tr>'."\n";
 9259:                     $failed ++;
 9260:                 }
 9261:                 $numstudents ++;
 9262:             }
 9263:         }
 9264:     }
 9265:     $r->print('<p>'.
 9266:               &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).',
 9267:                   '<b>',
 9268:                   $numstudents,
 9269:                   '</b>',
 9270:                   $env{'form.scantron_maxbubble'}).
 9271:               '</p>'
 9272:     );
 9273:     $r->print('<p>'
 9274:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9275:              .'<br />'
 9276:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9277:              .'</p>');
 9278:     if ($passed) {
 9279:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9280:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9281:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9282:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9283:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9284:                  $okstudents."\n".
 9285:                  &Apache::loncommon::end_data_table().'<br />');
 9286:     }
 9287:     if ($failed) {
 9288:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9289:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9290:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9291:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9292:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9293:                  $badstudents."\n".
 9294:                  &Apache::loncommon::end_data_table()).'<br />'.
 9295:                  &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.');  
 9296:     }
 9297:     $r->print('</form><br />'.$grading_menu_button);
 9298:     return;
 9299: }
 9300: 
 9301: sub verify_scantron_grading {
 9302:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9303:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9304:         $respnumlookup,$startline) = @_;
 9305:     my ($record,%expected,%startpos);
 9306:     return ($counter,$record) if (!ref($resource));
 9307:     return ($counter,$record) if (!$resource->is_problem());
 9308:     my $symb = $resource->symb();
 9309:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9310:     foreach my $part_id (@{$partids}) {
 9311:         $counter ++;
 9312:         $expected{$part_id} = 0;
 9313:         my $respnum = $counter;
 9314:         if ($randomorder || $randompick) {
 9315:             $respnum = $respnumlookup->{$counter};
 9316:             $startpos{$part_id} = $startline->{$counter} + 1;
 9317:         } else {
 9318:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9319:         }
 9320:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9321:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9322:             foreach my $item (@sub_lines) {
 9323:                 $expected{$part_id} += $item;
 9324:             }
 9325:         } else {
 9326:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9327:         }
 9328:     }
 9329:     if ($symb) {
 9330:         my %recorded;
 9331:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9332:         if ($returnhash{'version'}) {
 9333:             my %lasthash=();
 9334:             my $version;
 9335:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9336:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9337:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9338:                 }
 9339:             }
 9340:             foreach my $key (keys(%lasthash)) {
 9341:                 if ($key =~ /\.scantron$/) {
 9342:                     my $value = &unescape($lasthash{$key});
 9343:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9344:                     if ($value eq '') {
 9345:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9346:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9347:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9348:                             }
 9349:                         }
 9350:                     } else {
 9351:                         my @tocheck;
 9352:                         my @items = split(//,$value);
 9353:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9354:                             ($scantron_config->{'Qon'} eq 'number')) {
 9355:                             if (@items < $expected{$part_id}) {
 9356:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9357:                                 my @singles = split(//,$fragment);
 9358:                                 foreach my $pos (@singles) {
 9359:                                     if ($pos eq ' ') {
 9360:                                         push(@tocheck,$pos);
 9361:                                     } else {
 9362:                                         my $next = shift(@items);
 9363:                                         push(@tocheck,$next);
 9364:                                     }
 9365:                                 }
 9366:                             } else {
 9367:                                 @tocheck = @items;
 9368:                             }
 9369:                             foreach my $letter (@tocheck) {
 9370:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9371:                                     if ($letter !~ /^[A-J]$/) {
 9372:                                         $letter = $scantron_config->{'Qoff'};
 9373:                                     }
 9374:                                     $recorded{$part_id} .= $letter;
 9375:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9376:                                     my $digit;
 9377:                                     if ($letter !~ /^[A-J]$/) {
 9378:                                         $digit = $scantron_config->{'Qoff'};
 9379:                                     } else {
 9380:                                         $digit = $lettdig->{$letter};
 9381:                                     }
 9382:                                     $recorded{$part_id} .= $digit;
 9383:                                 }
 9384:                             }
 9385:                         } else {
 9386:                             @tocheck = @items;
 9387:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9388:                                 my $curr_sub = shift(@tocheck);
 9389:                                 my $digit;
 9390:                                 if ($curr_sub =~ /^[A-J]$/) {
 9391:                                     $digit = $lettdig->{$curr_sub}-1;
 9392:                                 }
 9393:                                 if ($curr_sub eq 'J') {
 9394:                                     $digit += scalar($numletts);
 9395:                                 }
 9396:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9397:                                     if ($j == $digit) {
 9398:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9399:                                     } else {
 9400:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9401:                                     }
 9402:                                 }
 9403:                             }
 9404:                         }
 9405:                     }
 9406:                 }
 9407:             }
 9408:         }
 9409:         foreach my $part_id (@{$partids}) {
 9410:             if ($recorded{$part_id} eq '') {
 9411:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9412:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9413:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9414:                     }
 9415:                 }
 9416:             }
 9417:             $record .= $recorded{$part_id};
 9418:         }
 9419:     }
 9420:     return ($counter,$record);
 9421: }
 9422: 
 9423: sub letter_to_digits {
 9424:     my %lettdig = (
 9425:                     A => 1,
 9426:                     B => 2,
 9427:                     C => 3,
 9428:                     D => 4,
 9429:                     E => 5,
 9430:                     F => 6,
 9431:                     G => 7,
 9432:                     H => 8,
 9433:                     I => 9,
 9434:                     J => 0,
 9435:                   );
 9436:     return %lettdig;
 9437: }
 9438: 
 9439: 
 9440: #-------- end of section for handling grading scantron forms -------
 9441: #
 9442: #-------------------------------------------------------------------
 9443: 
 9444: #-------------------------- Menu interface -------------------------
 9445: #
 9446: #--- Show a Grading Menu button - Calls the next routine ---
 9447: sub show_grading_menu_form {
 9448:     my ($symb)=@_;
 9449:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9450: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9451: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9452: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9453: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9454: 	'</form>'."\n";
 9455:     return $result;
 9456: }
 9457: 
 9458: # -- Retrieve choices for grading form
 9459: sub savedState {
 9460:     my %savedState = ();
 9461:     if ($env{'form.saveState'}) {
 9462: 	foreach (split(/:/,$env{'form.saveState'})) {
 9463: 	    my ($key,$value) = split(/=/,$_,2);
 9464: 	    $savedState{$key} = $value;
 9465: 	}
 9466:     }
 9467:     return \%savedState;
 9468: }
 9469: 
 9470: #--- Href with symb and command ---
 9471: 
 9472: sub href_symb_cmd {
 9473:     my ($symb,$cmd)=@_;
 9474:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9475: }
 9476: 
 9477: sub grading_menu {
 9478:     my ($request) = @_;
 9479:     my ($symb)=&get_symb($request);
 9480:     if (!$symb) {return '';}
 9481:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9482:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9483: 
 9484:     $request->print($table);
 9485:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9486:                   'handgrade'=>$hdgrade,
 9487:                   'probTitle'=>$probTitle,
 9488:                   'command'=>'submit_options',
 9489:                   'saveState'=>"",
 9490:                   'gradingMenu'=>1,
 9491:                   'showgrading'=>"yes");
 9492:     
 9493:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9494:     
 9495:     $fields{'command'} = 'csvform';
 9496:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9497:     
 9498:     $fields{'command'} = 'processclicker';
 9499:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9500:     
 9501:     $fields{'command'} = 'scantron_selectphase';
 9502:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9503:     
 9504:     my @menu = ({	categorytitle=>'Course Grading',
 9505:             items =>[
 9506:                         {	linktext => 'Manual Grading/View Submissions',
 9507:                     		url => $url1,
 9508:                     		permission => 'F',
 9509:                     		icon => 'edit-find-replace.png',
 9510:                     		linktitle => 'Start the process of hand grading submissions.'
 9511:                         },
 9512:                 	    {	linktext => 'Upload Scores',
 9513:                     		url => $url2,
 9514:                     		permission => 'F',
 9515:                     		icon => 'uploadscores.png',
 9516:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9517:                 	    },
 9518:                 	    {	linktext => 'Process Clicker',
 9519:                     		url => $url3,
 9520:                     		permission => 'F',
 9521:                     		icon => 'addClickerInfoFile.png',
 9522:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9523:                 	    },
 9524:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9525:                     		url => $url4,
 9526:                     		permission => 'F',
 9527:                     		icon => 'stat.png',
 9528:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9529:                 	    }
 9530:                     ]
 9531:             });
 9532: 
 9533:     #$fields{'command'} = 'verify';
 9534:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9535:     #
 9536:     # Create the menu
 9537:     my $Str;
 9538:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9539:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9540:     $Str .= '<input type="hidden" name="command" value="" />'.
 9541:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9542: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9543: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9544: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9545: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9546: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9547: 
 9548:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9549:     #$menudata->{'jscript'}
 9550:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9551:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9552:         ' /> '.
 9553:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9554:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9555: 
 9556:     $Str .="</form>\n";
 9557:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9558:     $request->print(<<GRADINGMENUJS);
 9559: <script type="text/javascript" language="javascript">
 9560:     function checkChoice(formname,val,cmdx) {
 9561: 	if (val <= 2) {
 9562: 	    var cmd = radioSelection(formname.radioChoice);
 9563: 	    var cmdsave = cmd;
 9564: 	} else {
 9565: 	    cmd = cmdx;
 9566: 	    cmdsave = 'submission';
 9567: 	}
 9568: 	formname.command.value = cmd;
 9569: 	if (val < 5) formname.submit();
 9570: 	if (val == 5) {
 9571: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9572: 	        return false;
 9573: 	    } else {
 9574: 	        formname.submit();
 9575: 	    }
 9576: 	}
 9577:     }
 9578: 
 9579:     function checkReceiptNo(formname,nospace) {
 9580: 	var receiptNo = formname.receipt.value;
 9581: 	var checkOpt = false;
 9582: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9583: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9584: 	if (checkOpt) {
 9585: 	    alert("$receiptalert");
 9586: 	    formname.receipt.value = "";
 9587: 	    formname.receipt.focus();
 9588: 	    return false;
 9589: 	}
 9590: 	return true;
 9591:     }
 9592: </script>
 9593: GRADINGMENUJS
 9594:     &commonJSfunctions($request);
 9595:     return $Str;    
 9596: }
 9597: 
 9598: 
 9599: #--- Displays the submissions first page -------
 9600: sub submit_options {
 9601:     my ($request) = @_;
 9602:     my ($symb)=&get_symb($request);
 9603:     if (!$symb) {return '';}
 9604:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9605: 
 9606:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9607:     $request->print(<<GRADINGMENUJS);
 9608: <script type="text/javascript" language="javascript">
 9609:     function checkChoice(formname,val,cmdx) {
 9610: 	if (val <= 2) {
 9611: 	    var cmd = radioSelection(formname.radioChoice);
 9612: 	    var cmdsave = cmd;
 9613: 	} else {
 9614: 	    cmd = cmdx;
 9615: 	    cmdsave = 'submission';
 9616: 	}
 9617: 	formname.command.value = cmd;
 9618: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9619: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9620: 	if (val < 5) formname.submit();
 9621: 	if (val == 5) {
 9622: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9623: 	    formname.submit();
 9624: 	}
 9625: 	if (val < 7) formname.submit();
 9626:     }
 9627: 
 9628:     function checkReceiptNo(formname,nospace) {
 9629: 	var receiptNo = formname.receipt.value;
 9630: 	var checkOpt = false;
 9631: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9632: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9633: 	if (checkOpt) {
 9634: 	    alert("$receiptalert");
 9635: 	    formname.receipt.value = "";
 9636: 	    formname.receipt.focus();
 9637: 	    return false;
 9638: 	}
 9639: 	return true;
 9640:     }
 9641: </script>
 9642: GRADINGMENUJS
 9643:     &commonJSfunctions($request);
 9644:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9645:     my $result;
 9646:     my (undef,$sections) = &getclasslist('all','0');
 9647:     my $savedState = &savedState();
 9648:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9649:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9650:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9651:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9652: 
 9653:     # Preselect sections
 9654:     my $selsec="";
 9655:     if (ref($sections)) {
 9656:         foreach my $section (sort(@$sections)) {
 9657:             $selsec.='<option value="'.$section.'" '.
 9658:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9659:         }
 9660:     }
 9661: 
 9662:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9663: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9664: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9665: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9666: 	'<input type="hidden" name="command"     value="" />'."\n".
 9667: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9668: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9669: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9670: 
 9671:     $result.='
 9672: <h2>
 9673:   '.&mt('Grade Current Resource').'
 9674: </h2>
 9675: <div>
 9676:   '.$table.'
 9677: </div>
 9678: 
 9679: <div class="LC_columnSection">
 9680:   
 9681:     <fieldset>
 9682:       <legend>
 9683:        '.&mt('Sections').'
 9684:       </legend>
 9685:       <select name="section" multiple="multiple" size="5">'."\n";
 9686:     $result.= $selsec;
 9687:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9688:     $result.='
 9689:     </fieldset>
 9690:   
 9691:     <fieldset>
 9692:       <legend>
 9693:         '.&mt('Groups').'
 9694:       </legend>
 9695:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9696:     </fieldset>
 9697:   
 9698:     <fieldset>
 9699:       <legend>
 9700:         '.&mt('Access Status').'
 9701:       </legend>
 9702:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9703:     </fieldset>
 9704:   
 9705:     <fieldset>
 9706:       <legend>
 9707:         '.&mt('Submission Status').'
 9708:       </legend>
 9709:       <select name="submitonly" size="5">
 9710: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9711: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9712: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9713: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9714:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9715:       </select>
 9716:     </fieldset>
 9717:   
 9718: </div>
 9719: 
 9720: <br />
 9721:           <div>
 9722:             <div>
 9723:               <label>
 9724:                 <input type="radio" name="radioChoice" value="submission" '.
 9725:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9726:              &mt('Select individual students to grade and view submissions.').'
 9727: 	      </label> 
 9728:             </div>
 9729:             <div>
 9730: 	      <label>
 9731:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9732:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 9733:                     &mt('Grade all selected students in a grading table.').'
 9734:               </label>
 9735:             </div>
 9736:             <div>
 9737: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9738:             </div>
 9739:           </div>
 9740: 
 9741: 
 9742:         <h2>
 9743:          '.&mt('Grade Complete Folder for One Student').'
 9744:         </h2>
 9745:         <div>
 9746:             <div>
 9747:               <label>
 9748:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 9749: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 9750:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 9751:               </label>
 9752:             </div>
 9753:             <div>
 9754: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9755:             </div>
 9756:         </div>
 9757:   </form>';
 9758:     $result .= &show_grading_menu_form($symb);
 9759:     return $result;
 9760: }
 9761: 
 9762: sub reset_perm {
 9763:     undef(%perm);
 9764: }
 9765: 
 9766: sub init_perm {
 9767:     &reset_perm();
 9768:     foreach my $test_perm ('vgr','mgr','opa') {
 9769: 
 9770: 	my $scope = $env{'request.course.id'};
 9771: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9772: 
 9773: 	    $scope .= '/'.$env{'request.course.sec'};
 9774: 	    if ( $perm{$test_perm}=
 9775: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9776: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9777: 	    } else {
 9778: 		delete($perm{$test_perm});
 9779: 	    }
 9780: 	}
 9781:     }
 9782: }
 9783: 
 9784: sub init_old_essays {
 9785:     my ($symb,$apath,$adom,$aname) = @_;
 9786:     if ($symb ne '') {
 9787:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9788:         if (keys(%essays) > 0) {
 9789:             $old_essays{$symb} = \%essays;
 9790:         }
 9791:     }
 9792:     return;
 9793: }
 9794: 
 9795: sub reset_old_essays {
 9796:     undef(%old_essays);
 9797: }
 9798: 
 9799: sub gather_clicker_ids {
 9800:     my %clicker_ids;
 9801: 
 9802:     my $classlist = &Apache::loncoursedata::get_classlist();
 9803: 
 9804:     # Set up a couple variables.
 9805:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9806:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9807:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9808: 
 9809:     foreach my $student (keys(%$classlist)) {
 9810:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9811:         my $username = $classlist->{$student}->[$username_idx];
 9812:         my $domain   = $classlist->{$student}->[$domain_idx];
 9813:         my $clickers =
 9814: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9815:         foreach my $id (split(/\,/,$clickers)) {
 9816:             $id=~s/^[\#0]+//;
 9817:             $id=~s/[\-\:]//g;
 9818:             if (exists($clicker_ids{$id})) {
 9819: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9820:             } else {
 9821: 		$clicker_ids{$id}=$username.':'.$domain;
 9822:             }
 9823:         }
 9824:     }
 9825:     return %clicker_ids;
 9826: }
 9827: 
 9828: sub gather_adv_clicker_ids {
 9829:     my %clicker_ids;
 9830:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9831:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9832:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9833:     foreach my $element (sort(keys(%coursepersonnel))) {
 9834:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9835:             my ($puname,$pudom)=split(/\:/,$person);
 9836:             my $clickers =
 9837: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9838:             foreach my $id (split(/\,/,$clickers)) {
 9839: 		$id=~s/^[\#0]+//;
 9840:                 $id=~s/[\-\:]//g;
 9841: 		if (exists($clicker_ids{$id})) {
 9842: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9843: 		} else {
 9844: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9845: 		}
 9846:             }
 9847:         }
 9848:     }
 9849:     return %clicker_ids;
 9850: }
 9851: 
 9852: sub clicker_grading_parameters {
 9853:     return ('gradingmechanism' => 'scalar',
 9854:             'upfiletype' => 'scalar',
 9855:             'specificid' => 'scalar',
 9856:             'pcorrect' => 'scalar',
 9857:             'pincorrect' => 'scalar');
 9858: }
 9859: 
 9860: sub process_clicker {
 9861:     my ($r)=@_;
 9862:     my ($symb)=&get_symb($r);
 9863:     if (!$symb) {return '';}
 9864:     my $result=&checkforfile_js();
 9865:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 9866:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 9867:     $result.=$table;
 9868:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 9869:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 9870:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 9871:         '</b></td></tr>'."\n";
 9872:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 9873: # Attempt to restore parameters from last session, set defaults if not present
 9874:     my %Saveable_Parameters=&clicker_grading_parameters();
 9875:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9876:                                                  \%Saveable_Parameters);
 9877:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9878:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9879:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9880:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9881: 
 9882:     my %checked;
 9883:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9884:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9885:           $checked{$gradingmechanism}=' checked="checked"';
 9886:        }
 9887:     }
 9888: 
 9889:     my $upload=&mt("Upload File");
 9890:     my $type=&mt("Type");
 9891:     my $attendance=&mt("Award points just for participation");
 9892:     my $personnel=&mt("Correctness determined from response by course personnel");
 9893:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9894:     my $given=&mt("Correctness determined from given list of answers").' '.
 9895:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9896:     my $pcorrect=&mt("Percentage points for correct solution");
 9897:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9898:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9899:                                                    {'iclicker' => 'i>clicker',
 9900:                                                     'interwrite' => 'interwrite PRS',
 9901:                                                     'turning' => 'Turning Technologies'});
 9902:     $symb = &Apache::lonenc::check_encrypt($symb);
 9903:     $result.=<<ENDUPFORM;
 9904: <script type="text/javascript">
 9905: function sanitycheck() {
 9906: // Accept only integer percentages
 9907:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9908:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9909: // Find out grading choice
 9910:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9911:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9912:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9913:       }
 9914:    }
 9915: // By default, new choice equals user selection
 9916:    newgradingchoice=gradingchoice;
 9917: // Not good to give more points for false answers than correct ones
 9918:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9919:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9920:    }
 9921: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9922:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9923:       document.forms.gradesupload.pcorrect.value=100;
 9924:       document.forms.gradesupload.pincorrect.value=100;
 9925:    }
 9926: // If the values are different, cannot be attendance only
 9927:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9928:        (gradingchoice=='attendance')) {
 9929:        newgradingchoice='personnel';
 9930:    }
 9931: // Change grading choice to new one
 9932:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9933:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9934:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9935:       } else {
 9936:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9937:       }
 9938:    }
 9939: // Remember the old state
 9940:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9941: }
 9942: </script>
 9943: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9944: <input type="hidden" name="symb" value="$symb" />
 9945: <input type="hidden" name="command" value="processclickerfile" />
 9946: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9947: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9948: <input type="file" name="upfile" size="50" />
 9949: <br /><label>$type: $selectform</label>
 9950: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9951: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9952: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9953: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9954: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9955: <br />&nbsp;&nbsp;&nbsp;
 9956: <input type="text" name="givenanswer" size="50" />
 9957: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9958: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9959: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9960: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9961: </form>
 9962: ENDUPFORM
 9963:     $result.='</td></tr></table>'."\n".
 9964:              '</td></tr></table><br /><br />'."\n";
 9965:     $result.=&show_grading_menu_form($symb);
 9966:     return $result;
 9967: }
 9968: 
 9969: sub process_clicker_file {
 9970:     my ($r)=@_;
 9971:     my ($symb)=&get_symb($r);
 9972:     if (!$symb) {return '';}
 9973: 
 9974:     my %Saveable_Parameters=&clicker_grading_parameters();
 9975:     &Apache::loncommon::store_course_settings('grades_clicker',
 9976:                                               \%Saveable_Parameters);
 9977: 
 9978:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9979:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9980: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9981: 	return $result.&show_grading_menu_form($symb);
 9982:     }
 9983:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9984:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9985:         return $result.&show_grading_menu_form($symb);
 9986:     }
 9987:     my $foundgiven=0;
 9988:     if ($env{'form.gradingmechanism'} eq 'given') {
 9989:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9990:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9991:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9992:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9993:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9994:         $foundgiven=$#answers+1;
 9995:     }
 9996:     my %clicker_ids=&gather_clicker_ids();
 9997:     my %correct_ids;
 9998:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9999: 	%correct_ids=&gather_adv_clicker_ids();
10000:     }
10001:     if ($env{'form.gradingmechanism'} eq 'specific') {
10002: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10003: 	   $correct_id=~tr/a-z/A-Z/;
10004: 	   $correct_id=~s/\s//gs;
10005: 	   $correct_id=~s/^[\#0]+//;
10006:            $correct_id=~s/[\-\:]//g;
10007:            if ($correct_id) {
10008: 	      $correct_ids{$correct_id}='specified';
10009:            }
10010:         }
10011:     }
10012:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10013: 	$result.=&mt('Score based on attendance only');
10014:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10015:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10016:     } else {
10017: 	my $number=0;
10018: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10019: 	foreach my $id (sort(keys(%correct_ids))) {
10020: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10021: 	    if ($correct_ids{$id} eq 'specified') {
10022: 		$result.=&mt('specified');
10023: 	    } else {
10024: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10025: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10026: 	    }
10027: 	    $number++;
10028: 	}
10029:         $result.="</p>\n";
10030:         if ($number==0) {
10031:             $result .=
10032:                  &Apache::lonhtmlcommon::confirm_success(
10033:                      &mt('No IDs found to determine correct answer'),1);
10034:             return $result,.&show_grading_menu_form($symb);
10035:         }
10036:     }
10037:     if (length($env{'form.upfile'}) < 2) {
10038:         $result .=
10039:             &Apache::lonhtmlcommon::confirm_success(
10040:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10041:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10042:         return $result.&show_grading_menu_form($symb);
10043:     }
10044: 
10045: # Were able to get all the info needed, now analyze the file
10046: 
10047:     $result.=&Apache::loncommon::studentbrowser_javascript();
10048:     $symb = &Apache::lonenc::check_encrypt($symb);
10049:     my $heading=&mt('Scanning clicker file');
10050:     $result.=(<<ENDHEADER);
10051: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
10052: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
10053: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
10054: <form method="post" action="/adm/grades" name="clickeranalysis">
10055: <input type="hidden" name="symb" value="$symb" />
10056: <input type="hidden" name="command" value="assignclickergrades" />
10057: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10058: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10059: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10060: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10061: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10062: ENDHEADER
10063:     if ($env{'form.gradingmechanism'} eq 'given') {
10064:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10065:     } 
10066:     my %responses;
10067:     my @questiontitles;
10068:     my $errormsg='';
10069:     my $number=0;
10070:     if ($env{'form.upfiletype'} eq 'iclicker') {
10071: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10072:     }
10073:     if ($env{'form.upfiletype'} eq 'interwrite') {
10074:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10075:     }
10076:     if ($env{'form.upfiletype'} eq 'turning') {
10077:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10078:     }
10079:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10080:              '<input type="hidden" name="number" value="'.$number.'" />'.
10081:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10082:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10083:              '<br />';
10084:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10085:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10086:        return $result.&show_grading_menu_form($symb);
10087:     } 
10088: # Remember Question Titles
10089: # FIXME: Possibly need delimiter other than ":"
10090:     for (my $i=0;$i<$number;$i++) {
10091:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10092:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10093:     }
10094:     my $correct_count=0;
10095:     my $student_count=0;
10096:     my $unknown_count=0;
10097: # Match answers with usernames
10098: # FIXME: Possibly need delimiter other than ":"
10099:     foreach my $id (keys(%responses)) {
10100:        if ($correct_ids{$id}) {
10101:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10102:           $correct_count++;
10103:        } elsif ($clicker_ids{$id}) {
10104:           if ($clicker_ids{$id}=~/\,/) {
10105: # More than one user with the same clicker!
10106:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10107:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10108:                            "<select name='multi".$id."'>";
10109:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10110:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10111:              }
10112:              $result.='</select>';
10113:              $unknown_count++;
10114:           } else {
10115: # Good: found one and only one user with the right clicker
10116:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10117:              $student_count++;
10118:           }
10119:        } else {
10120:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10121:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10122:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10123:                    "\n".&mt("Domain").": ".
10124:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10125:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10126:           $unknown_count++;
10127:        }
10128:     }
10129:     $result.='<hr />'.
10130:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10131:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10132:        if ($correct_count==0) {
10133:           $errormsg.="Found no correct answers for grading!";
10134:        } elsif ($correct_count>1) {
10135:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10136:        }
10137:     }
10138:     if ($number<1) {
10139:        $errormsg.="Found no questions.";
10140:     }
10141:     if ($errormsg) {
10142:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10143:     } else {
10144:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10145:     }
10146:     $result.='</form></td></tr></table>'."\n".
10147:              '</td></tr></table><br /><br />'."\n";
10148:     return $result.&show_grading_menu_form($symb);
10149: }
10150: 
10151: sub iclicker_eval {
10152:     my ($questiontitles,$responses)=@_;
10153:     my $number=0;
10154:     my $errormsg='';
10155:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10156:         my %components=&Apache::loncommon::record_sep($line);
10157:         my @entries=map {$components{$_}} (sort(keys(%components)));
10158: 	if ($entries[0] eq 'Question') {
10159: 	    for (my $i=3;$i<$#entries;$i+=6) {
10160: 		$$questiontitles[$number]=$entries[$i];
10161: 		$number++;
10162: 	    }
10163: 	}
10164: 	if ($entries[0]=~/^\#/) {
10165: 	    my $id=$entries[0];
10166: 	    my @idresponses;
10167: 	    $id=~s/^[\#0]+//;
10168: 	    for (my $i=0;$i<$number;$i++) {
10169: 		my $idx=3+$i*6;
10170:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10171: 		push(@idresponses,$entries[$idx]);
10172: 	    }
10173: 	    $$responses{$id}=join(',',@idresponses);
10174: 	}
10175:     }
10176:     return ($errormsg,$number);
10177: }
10178: 
10179: sub interwrite_eval {
10180:     my ($questiontitles,$responses)=@_;
10181:     my $number=0;
10182:     my $errormsg='';
10183:     my $skipline=1;
10184:     my $questionnumber=0;
10185:     my %idresponses=();
10186:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10187:         my %components=&Apache::loncommon::record_sep($line);
10188:         my @entries=map {$components{$_}} (sort(keys(%components)));
10189:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10190:         if ($entries[1] eq 'Response') { $skipline=1; }
10191:         next if $skipline;
10192:         if ($entries[0]!=$questionnumber) {
10193:            $questionnumber=$entries[0];
10194:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10195:            $number++;
10196:         }
10197:         my $id=$entries[4];
10198:         $id=~s/^[\#0]+//;
10199:         $id=~s/^v\d*\://i;
10200:         $id=~s/[\-\:]//g;
10201:         $idresponses{$id}[$number]=$entries[6];
10202:     }
10203:     foreach my $id (keys(%idresponses)) {
10204:        $$responses{$id}=join(',',@{$idresponses{$id}});
10205:        $$responses{$id}=~s/^\s*\,//;
10206:     }
10207:     return ($errormsg,$number);
10208: }
10209: 
10210: sub turning_eval {
10211:     my ($questiontitles,$responses)=@_;
10212:     my $number=0;
10213:     my $errormsg='';
10214:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10215:         my %components=&Apache::loncommon::record_sep($line);
10216:         my @entries=map {$components{$_}} (sort(keys(%components)));
10217:         if ($#entries>$number) { $number=$#entries; }
10218:         my $id=$entries[0];
10219:         my @idresponses;
10220:         $id=~s/^[\#0]+//;
10221:         unless ($id) { next; }
10222:         for (my $idx=1;$idx<=$#entries;$idx++) {
10223:             $entries[$idx]=~s/\,/\;/g;
10224:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10225:             push(@idresponses,$entries[$idx]);
10226:         }
10227:         $$responses{$id}=join(',',@idresponses);
10228:     }
10229:     for (my $i=1; $i<=$number; $i++) {
10230:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10231:     }
10232:     return ($errormsg,$number);
10233: }
10234: 
10235: sub assign_clicker_grades {
10236:     my ($r)=@_;
10237:     my ($symb)=&get_symb($r);
10238:     if (!$symb) {return '';}
10239: # See which part we are saving to
10240:     my $res_error;
10241:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10242:     if ($res_error) {
10243:         return &navmap_errormsg();
10244:     }
10245: # FIXME: This should probably look for the first handgradeable part
10246:     my $part=$$partlist[0];
10247: # Start screen output
10248:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10249: 
10250:     $result .= '<br />'.
10251:                &Apache::loncommon::start_data_table().
10252:                &Apache::loncommon::start_data_table_header_row().
10253:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10254:                &Apache::loncommon::end_data_table_header_row().
10255:                &Apache::loncommon::start_data_table_row().'<td>';
10256: 
10257: # Get correct result
10258: # FIXME: Possibly need delimiter other than ":"
10259:     my @correct=();
10260:     my $gradingmechanism=$env{'form.gradingmechanism'};
10261:     my $number=$env{'form.number'};
10262:     if ($gradingmechanism ne 'attendance') {
10263:        foreach my $key (keys(%env)) {
10264:           if ($key=~/^form\.correct\:/) {
10265:              my @input=split(/\,/,$env{$key});
10266:              for (my $i=0;$i<=$#input;$i++) {
10267:                  if (($correct[$i]) && ($input[$i]) &&
10268:                      ($correct[$i] ne $input[$i])) {
10269:                     $result.='<br /><span class="LC_warning">'.
10270:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10271:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10272:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10273:                     $correct[$i]=$input[$i];
10274:                  }
10275:              }
10276:           }
10277:        }
10278:        for (my $i=0;$i<$number;$i++) {
10279:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10280:              $result.='<br /><span class="LC_error">'.
10281:                       &mt('No correct result given for question "[_1]"!',
10282:                           $env{'form.question:'.$i}).'</span>';
10283:           }
10284:        }
10285:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10286:     }
10287: # Start grading
10288:     my $pcorrect=$env{'form.pcorrect'};
10289:     my $pincorrect=$env{'form.pincorrect'};
10290:     my $storecount=0;
10291:     my %users=();
10292:     foreach my $key (keys(%env)) {
10293:        my $user='';
10294:        if ($key=~/^form\.student\:(.*)$/) {
10295:           $user=$1;
10296:        }
10297:        if ($key=~/^form\.unknown\:(.*)$/) {
10298:           my $id=$1;
10299:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10300:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10301:           } elsif ($env{'form.multi'.$id}) {
10302:              $user=$env{'form.multi'.$id};
10303:           }
10304:        }
10305:        if ($user) {
10306:           if ($users{$user}) {
10307:              $result.='<br /><span class="LC_warning">'.
10308:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10309:                       '</span><br />';
10310:           }
10311:           $users{$user}=1;
10312:           my @answer=split(/\,/,$env{$key});
10313:           my $sum=0;
10314:           my $realnumber=$number;
10315:           for (my $i=0;$i<$number;$i++) {
10316:              if  ($correct[$i] eq '-') {
10317:                 $realnumber--;
10318:              } elsif ($answer[$i]) {
10319:                 if ($gradingmechanism eq 'attendance') {
10320:                    $sum+=$pcorrect;
10321:                 } elsif ($correct[$i] eq '*') {
10322:                    $sum+=$pcorrect;
10323:                 } else {
10324: # We actually grade if correct or not
10325:                    my $increment=$pincorrect;
10326: # Special case: numerical answer "0"
10327:                    if ($correct[$i] eq '0') {
10328:                       if ($answer[$i]=~/^[0\.]+$/) {
10329:                          $increment=$pcorrect;
10330:                       }
10331: # General numerical answer, both evaluate to something non-zero
10332:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10333:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10334:                          $increment=$pcorrect;
10335:                       }
10336: # Must be just alphanumeric
10337:                    } elsif ($answer[$i] eq $correct[$i]) {
10338:                       $increment=$pcorrect;
10339:                    }
10340:                    $sum+=$increment;
10341:                 }
10342:              }
10343:           }
10344:           my $ave=$sum/(100*$realnumber);
10345: # Store
10346:           my ($username,$domain)=split(/\:/,$user);
10347:           my %grades=();
10348:           $grades{"resource.$part.solved"}='correct_by_override';
10349:           $grades{"resource.$part.awarded"}=$ave;
10350:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10351:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10352:                                                  $env{'request.course.id'},
10353:                                                  $domain,$username);
10354:           if ($returncode ne 'ok') {
10355:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10356:           } else {
10357:              $storecount++;
10358:           }
10359:        }
10360:     }
10361: # We are done
10362:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10363:              '</td>'.
10364:              &Apache::loncommon::end_data_table_row().
10365:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10366:     return $result.&show_grading_menu_form($symb);
10367: }
10368: 
10369: sub navmap_errormsg {
10370:     return '<div class="LC_error">'.
10371:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10372:            &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>').
10373:            '</div>';
10374: }
10375: 
10376: sub startpage {
10377:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10378:     if ($nomenu) {
10379:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10380:     } else {
10381:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10382:                                                  {'bread_crumbs' => $crumbs}));
10383:     }
10384:     unless ($nodisplayflag) {
10385:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10386:     }
10387: }
10388: 
10389: sub handler {
10390:     my $request=$_[0];
10391:     &reset_caches();
10392:     if ($request->header_only) {
10393:         &Apache::loncommon::content_type($request,'text/html');
10394:         $request->send_http_header;
10395:         return OK;
10396:     }
10397:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10398: 
10399:     my $symb=&get_symb($request,1);
10400:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10401:     my $command=$commands[0];
10402: 
10403:     if ($#commands > 0) {
10404: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10405:     }
10406: 
10407:     $ssi_error = 0;
10408:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10409:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10410:                                                     {'bread_crumbs' => $brcrum});
10411:     if ($symb eq '' && $command eq '') {
10412: 	if ($env{'user.adv'}) {
10413:             &Apache::loncommon::content_type($request,'text/html');
10414:             $request->send_http_header;
10415:             $request->print($start_page);
10416: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10417: 		($env{'form.codethree'})) {
10418: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10419: 		    $env{'form.codethree'};
10420: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10421: 		    &Apache::lonnet::checkin($token);
10422: 		if ($tsymb) {
10423: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10424: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10425: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10426: 					  ('grade_username' => $tuname,
10427: 					   'grade_domain' => $tudom,
10428: 					   'grade_courseid' => $tcrsid,
10429: 					   'grade_symb' => $tsymb)));
10430: 		    } else {
10431: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10432: 		    }
10433: 		} else {
10434: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10435: 		}
10436: 	    } else {
10437: 		$request->print(&Apache::lonxml::tokeninputfield());
10438: 	    }
10439:         } elsif ($env{'request.course.id'}) {
10440:             &init_perm(); 
10441:             if (!%perm) {
10442:                 $request->internal_redirect('/adm/quickgrades');
10443:                 return OK;
10444:             } else {
10445:                 &Apache::loncommon::content_type($request,'text/html');
10446:                 $request->send_http_header;
10447:                 $request->print($start_page);
10448:             }
10449:         }
10450:     } else {
10451:         &init_perm();
10452:         if (!$env{'request.course.id'}) {
10453:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10454:                     ($command =~ /^scantronupload/)) {
10455:                 # Not in a course.
10456:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10457:                 return HTTP_NOT_ACCEPTABLE;
10458:             }
10459:         } elsif (!%perm) {
10460:             $request->internal_redirect('/adm/quickgrades');
10461:         }
10462:         &Apache::loncommon::content_type($request,'text/html');
10463:         $request->send_http_header;
10464:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10465:             $request->print($start_page); 
10466:         }
10467: 	if ($command eq 'submission' && $perm{'vgr'}) {
10468:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10469:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10470:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10471:                     &choose_task_version_form($symb,$env{'form.student'},
10472:                                               $env{'form.userdom'});
10473:             }
10474:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10475:             if ($versionform) {
10476:                 $request->print($versionform);
10477:             }
10478:             $request->print('<br clear="all" />');
10479: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10480:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10481:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10482:                 &choose_task_version_form($symb,$env{'form.student'},
10483:                                           $env{'form.userdom'},
10484:                                           $env{'form.inhibitmenu'});
10485:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10486:             if ($versionform) {
10487:                 $request->print($versionform);
10488:             }
10489:             $request->print('<br clear="all" />');
10490:             $request->print(&show_previous_task_version($request,$symb));
10491: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10492: 	    &pickStudentPage($request);
10493: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10494: 	    &displayPage($request);
10495: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10496: 	    &updateGradeByPage($request);
10497: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10498: 	    &processGroup($request);
10499: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10500: 	    $request->print(&grading_menu($request));
10501: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10502: 	    $request->print(&submit_options($request));
10503: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10504: 	    $request->print(&viewgrades($request));
10505: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10506: 	    $request->print(&processHandGrade($request));
10507: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10508: 	    $request->print(&editgrades($request));
10509: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10510: 	    $request->print(&verifyreceipt($request));
10511:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10512:             $request->print(&process_clicker($request));
10513:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10514:             $request->print(&process_clicker_file($request));
10515:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10516:             $request->print(&assign_clicker_grades($request));
10517: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10518: 	    $request->print(&upcsvScores_form($request));
10519: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10520: 	    $request->print(&csvupload($request));
10521: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10522: 	    $request->print(&csvuploadmap($request));
10523: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10524: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10525: 		$request->print(&csvuploadoptions($request));
10526: 	    } else {
10527: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10528: 		    $env{'form.upfile_associate'} = 'reverse';
10529: 		} else {
10530: 		    $env{'form.upfile_associate'} = 'forward';
10531: 		}
10532: 		$request->print(&csvuploadmap($request));
10533: 	    }
10534: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10535: 	    $request->print(&csvuploadassign($request));
10536: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10537: 	    $request->print(&scantron_selectphase($request));
10538:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10539:  	    $request->print(&scantron_do_warning($request));
10540: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10541: 	    $request->print(&scantron_validate_file($request));
10542: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10543: 	    $request->print(&scantron_process_students($request));
10544:  	} elsif ($command eq 'scantronupload' && 
10545:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10546: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10547:  	    $request->print(&scantron_upload_scantron_data($request)); 
10548:  	} elsif ($command eq 'scantronupload_save' &&
10549:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10550: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10551:  	    $request->print(&scantron_upload_scantron_data_save($request));
10552:  	} elsif ($command eq 'scantron_download' &&
10553: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10554:  	    $request->print(&scantron_download_scantron_data($request));
10555:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10556:             $request->print(&checkscantron_results($request));     
10557: 	} elsif ($command) {
10558: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10559: 	}
10560:     }
10561:     if ($ssi_error) {
10562: 	&ssi_print_error($request);
10563:     }
10564:     $request->print(&Apache::loncommon::end_page());
10565:     &reset_caches();
10566:     return OK;
10567: }
10568: 
10569: 1;
10570: 
10571: __END__;
10572: 
10573: 
10574: =head1 NAME
10575: 
10576: Apache::grades
10577: 
10578: =head1 SYNOPSIS
10579: 
10580: Handles the viewing of grades.
10581: 
10582: This is part of the LearningOnline Network with CAPA project
10583: described at http://www.lon-capa.org.
10584: 
10585: =head1 OVERVIEW
10586: 
10587: Do an ssi with retries:
10588: While I'd love to factor out this with the vesrion in lonprintout,
10589: 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
10590: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10591: 
10592: At least the logic that drives this has been pulled out into loncommon.
10593: 
10594: 
10595: 
10596: ssi_with_retries - Does the server side include of a resource.
10597:                      if the ssi call returns an error we'll retry it up to
10598:                      the number of times requested by the caller.
10599:                      If we still have a problem, no text is appended to the
10600:                      output and we set some global variables.
10601:                      to indicate to the caller an SSI error occurred.  
10602:                      All of this is supposed to deal with the issues described
10603:                      in LON-CAPA BZ 5631 see:
10604:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10605:                      by informing the user that this happened.
10606: 
10607: Parameters:
10608:   resource   - The resource to include.  This is passed directly, without
10609:                interpretation to lonnet::ssi.
10610:   form       - The form hash parameters that guide the interpretation of the resource
10611:                
10612:   retries    - Number of retries allowed before giving up completely.
10613: Returns:
10614:   On success, returns the rendered resource identified by the resource parameter.
10615: Side Effects:
10616:   The following global variables can be set:
10617:    ssi_error                - If an unrecoverable error occurred this becomes true.
10618:                               It is up to the caller to initialize this to false
10619:                               if desired.
10620:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10621:                               of the resource that could not be rendered by the ssi
10622:                               call.
10623:    ssi_error_message   - The error string fetched from the ssi response
10624:                               in the event of an error.
10625: 
10626: 
10627: =head1 HANDLER SUBROUTINE
10628: 
10629: ssi_with_retries()
10630: 
10631: =head1 SUBROUTINES
10632: 
10633: =over
10634: 
10635: =item scantron_get_correction() : 
10636: 
10637:    Builds the interface screen to interact with the operator to fix a
10638:    specific error condition in a specific scanline
10639: 
10640:  Arguments:
10641:     $r           - Apache request object
10642:     $i           - number of the current scanline
10643:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10644:     $scan_config - hash ref as returned from &get_scantron_config()
10645:     $line        - full contents of the current scanline
10646:     $error       - error condition, valid values are
10647:                    'incorrectCODE', 'duplicateCODE',
10648:                    'doublebubble', 'missingbubble',
10649:                    'duplicateID', 'incorrectID'
10650:     $arg         - extra information needed
10651:        For errors:
10652:          - duplicateID   - paper number that this studentID was seen before on
10653:          - duplicateCODE - array ref of the paper numbers this CODE was
10654:                            seen on before
10655:          - incorrectCODE - current incorrect CODE 
10656:          - doublebubble  - array ref of the bubble lines that have double
10657:                            bubble errors
10658:          - missingbubble - array ref of the bubble lines that have missing
10659:                            bubble errors
10660: 
10661:    $randomorder - True if exam folder has randomorder set
10662:    $randompick  - True if exam folder has randompick set
10663:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10664:                      for current line to question number used for same question
10665:                      in "Master Seqence" (as seen by Course Coordinator).
10666:    $startline   - Reference to hash where key is question number (0 is first)
10667:                   and value is number of first bubble line for current student
10668:                   or code-based randompick and/or randomorder.
10669: 
10670: 
10671: =item  scantron_get_maxbubble() : 
10672: 
10673:    Arguments:
10674:        $nav_error  - Reference to scalar which is a flag to indicate a
10675:                       failure to retrieve a navmap object.
10676:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10677:        calling routine should trap the error condition and display the warning
10678:        found in &navmap_errormsg().
10679: 
10680:        $scantron_config - Reference to bubblesheet format configuration hash.
10681: 
10682:    Returns the maximum number of bubble lines that are expected to
10683:    occur. Does this by walking the selected sequence rendering the
10684:    resource and then checking &Apache::lonxml::get_problem_counter()
10685:    for what the current value of the problem counter is.
10686: 
10687:    Caches the results to $env{'form.scantron_maxbubble'},
10688:    $env{'form.scantron.bubble_lines.n'}, 
10689:    $env{'form.scantron.first_bubble_line.n'} and
10690:    $env{"form.scantron.sub_bubblelines.n"}
10691:    which are the total number of bubble lines, the number of bubble
10692:    lines for response n and number of the first bubble line for response n,
10693:    and a comma separated list of numbers of bubble lines for sub-questions
10694:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10695: 
10696: 
10697: =item  scantron_validate_missingbubbles() : 
10698: 
10699:    Validates all scanlines in the selected file to not have any
10700:     answers that don't have bubbles that have not been verified
10701:     to be bubble free.
10702: 
10703: =item  scantron_process_students() : 
10704: 
10705:    Routine that does the actual grading of the bubblesheet information.
10706: 
10707:    The parsed scanline hash is added to %env 
10708: 
10709:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10710:    foreach resource , with the form data of
10711: 
10712: 	'submitted'     =>'scantron' 
10713: 	'grade_target'  =>'grade',
10714: 	'grade_username'=> username of student
10715: 	'grade_domain'  => domain of student
10716: 	'grade_courseid'=> of course
10717: 	'grade_symb'    => symb of resource to grade
10718: 
10719:     This triggers a grading pass. The problem grading code takes care
10720:     of converting the bubbled letter information (now in %env) into a
10721:     valid submission.
10722: 
10723: =item  scantron_upload_scantron_data() :
10724: 
10725:     Creates the screen for adding a new bubblesheet data file to a course.
10726: 
10727: =item  scantron_upload_scantron_data_save() : 
10728: 
10729:    Adds a provided bubble information data file to the course if user
10730:    has the correct privileges to do so. 
10731: 
10732: =item  valid_file() :
10733: 
10734:    Validates that the requested bubble data file exists in the course.
10735: 
10736: =item  scantron_download_scantron_data() : 
10737: 
10738:    Shows a list of the three internal files (original, corrected,
10739:    skipped) for a specific bubblesheet data file that exists in the
10740:    course.
10741: 
10742: =item  scantron_validate_ID() : 
10743: 
10744:    Validates all scanlines in the selected file to not have any
10745:    invalid or underspecified student/employee IDs
10746: 
10747: =item navmap_errormsg() :
10748: 
10749:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10750:    Should be called whenever the request to instantiate a navmap object fails.  
10751: 
10752: =back
10753: 
10754: =cut

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