File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.28: download - view: text, annotated - select for diffs
Thu Feb 27 02:41:38 2014 UTC (10 years, 2 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  - Backport 1.711 (part), 1.712, 1.713, 1.715, 1.716, 1.717, 1.718, 1.719,
    1.720, 1.721, 1.722.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.28 2014/02/27 02:41:38 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: 	$answer =~ s-\n-<br />-g;
  469: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight(&HTML::Entities::encode($answer, '"<>&')).'</tt></blockquote>';
  470:     } elsif ( $response eq 'organic') {
  471:         my $result=&mt('Smile representation: [_1]',
  472:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  473: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  474: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  475: 	return $result;
  476:     } elsif ( $response eq 'Task') {
  477: 	if ( $answer eq 'SUBMITTED') {
  478: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  479: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  480: 	    return $result;
  481: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  482: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  483: 			       keys(%{$record}));
  484: 	    return join('<br />',($version,@matches));
  485: 			       
  486: 			       
  487: 	} else {
  488: 	    my $result =
  489: 		'<p>'
  490: 		.&mt('Overall result: [_1]',
  491: 		     $record->{$version."resource.$respid.$partid.status"})
  492: 		.'</p>';
  493: 	    
  494: 	    $result .= '<ul>';
  495: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  496: 			     keys(%{$record}));
  497: 	    foreach my $grade (sort(@grade)) {
  498: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  499: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  500: 				     $dim, $record->{$grade}).
  501: 			  '</li>';
  502: 	    }
  503: 	    $result.='</ul>';
  504: 	    return $result;
  505: 	}
  506:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  507:         # Respect multiple input fields, see Bug #5409 
  508: 	$answer = 
  509: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  510: 							      $answer);
  511:         return $answer;
  512:     }
  513:     return &HTML::Entities::encode($answer, '"<>&');
  514: }
  515: 
  516: #-- A couple of common js functions
  517: sub commonJSfunctions {
  518:     my $request = shift;
  519:     $request->print(<<COMMONJSFUNCTIONS);
  520: <script type="text/javascript" language="javascript">
  521:     function radioSelection(radioButton) {
  522: 	var selection=null;
  523: 	if (radioButton.length > 1) {
  524: 	    for (var i=0; i<radioButton.length; i++) {
  525: 		if (radioButton[i].checked) {
  526: 		    return radioButton[i].value;
  527: 		}
  528: 	    }
  529: 	} else {
  530: 	    if (radioButton.checked) return radioButton.value;
  531: 	}
  532: 	return selection;
  533:     }
  534: 
  535:     function pullDownSelection(selectOne) {
  536: 	var selection="";
  537: 	if (selectOne.length > 1) {
  538: 	    for (var i=0; i<selectOne.length; i++) {
  539: 		if (selectOne[i].selected) {
  540: 		    return selectOne[i].value;
  541: 		}
  542: 	    }
  543: 	} else {
  544:             // only one value it must be the selected one
  545: 	    return selectOne.value;
  546: 	}
  547:     }
  548: </script>
  549: COMMONJSFUNCTIONS
  550: }
  551: 
  552: #--- Dumps the class list with usernames,list of sections,
  553: #--- section, ids and fullnames for each user.
  554: sub getclasslist {
  555:     my ($getsec,$filterlist,$getgroup) = @_;
  556:     my @getsec;
  557:     my @getgroup;
  558:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  559:     if (!ref($getsec)) {
  560: 	if ($getsec ne '' && $getsec ne 'all') {
  561: 	    @getsec=($getsec);
  562: 	}
  563:     } else {
  564: 	@getsec=@{$getsec};
  565:     }
  566:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  567:     if (!ref($getgroup)) {
  568: 	if ($getgroup ne '' && $getgroup ne 'all') {
  569: 	    @getgroup=($getgroup);
  570: 	}
  571:     } else {
  572: 	@getgroup=@{$getgroup};
  573:     }
  574:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  575: 
  576:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  577:     # Bail out if we were unable to get the classlist
  578:     return if (! defined($classlist));
  579:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  580:     #
  581:     my %sections;
  582:     my %fullnames;
  583:     foreach my $student (keys(%$classlist)) {
  584:         my $end      = 
  585:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  586:         my $start    = 
  587:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  588:         my $id       = 
  589:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  590:         my $section  = 
  591:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  592:         my $fullname = 
  593:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  594:         my $status   = 
  595:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  596:         my $group   = 
  597:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  598: 	# filter students according to status selected
  599: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  600: 	    if (!($stu_status =~ $status)) {
  601: 		delete($classlist->{$student});
  602: 		next;
  603: 	    }
  604: 	}
  605: 	# filter students according to groups selected
  606: 	my @stu_groups = split(/,/,$group);
  607: 	if (@getgroup) {
  608: 	    my $exclude = 1;
  609: 	    foreach my $grp (@getgroup) {
  610: 	        foreach my $stu_group (@stu_groups) {
  611: 	            if ($stu_group eq $grp) {
  612: 	                $exclude = 0;
  613:     	            } 
  614: 	        }
  615:     	        if (($grp eq 'none') && !$group) {
  616:         	        $exclude = 0;
  617:         	}
  618: 	    }
  619: 	    if ($exclude) {
  620: 	        delete($classlist->{$student});
  621: 	    }
  622: 	}
  623: 	$section = ($section ne '' ? $section : 'none');
  624: 	if (&canview($section)) {
  625: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  626: 		$sections{$section}++;
  627: 		if ($classlist->{$student}) {
  628: 		    $fullnames{$student}=$fullname;
  629: 		}
  630: 	    } else {
  631: 		delete($classlist->{$student});
  632: 	    }
  633: 	} else {
  634: 	    delete($classlist->{$student});
  635: 	}
  636:     }
  637:     my %seen = ();
  638:     my @sections = sort(keys(%sections));
  639:     return ($classlist,\@sections,\%fullnames);
  640: }
  641: 
  642: sub canmodify {
  643:     my ($sec)=@_;
  644:     if ($perm{'mgr'}) {
  645: 	if (!defined($perm{'mgr_section'})) {
  646: 	    # can modify whole class
  647: 	    return 1;
  648: 	} else {
  649: 	    if ($sec eq $perm{'mgr_section'}) {
  650: 		#can modify the requested section
  651: 		return 1;
  652: 	    } else {
  653: 		# can't modify the request section
  654: 		return 0;
  655: 	    }
  656: 	}
  657:     }
  658:     #can't modify
  659:     return 0;
  660: }
  661: 
  662: sub canview {
  663:     my ($sec)=@_;
  664:     if ($perm{'vgr'}) {
  665: 	if (!defined($perm{'vgr_section'})) {
  666: 	    # can modify whole class
  667: 	    return 1;
  668: 	} else {
  669: 	    if ($sec eq $perm{'vgr_section'}) {
  670: 		#can modify the requested section
  671: 		return 1;
  672: 	    } else {
  673: 		# can't modify the request section
  674: 		return 0;
  675: 	    }
  676: 	}
  677:     }
  678:     #can't modify
  679:     return 0;
  680: }
  681: 
  682: #--- Retrieve the grade status of a student for all the parts
  683: sub student_gradeStatus {
  684:     my ($symb,$udom,$uname,$partlist) = @_;
  685:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  686:     my %partstatus = ();
  687:     foreach (@$partlist) {
  688: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  689: 	$status              = 'nothing' if ($status eq '');
  690: 	$partstatus{$_}      = $status;
  691: 	my $subkey           = "resource.$_.submitted_by";
  692: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  693:     }
  694:     return %partstatus;
  695: }
  696: 
  697: # hidden form and javascript that calls the form
  698: # Use by verifyscript and viewgrades
  699: # Shows a student's view of problem and submission
  700: sub jscriptNform {
  701:     my ($symb) = @_;
  702:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  703:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  704: 	'    function viewOneStudent(user,domain) {'."\n".
  705: 	'	document.onestudent.student.value = user;'."\n".
  706: 	'	document.onestudent.userdom.value = domain;'."\n".
  707: 	'	document.onestudent.submit();'."\n".
  708: 	'    }'."\n".
  709: 	'</script>'."\n";
  710:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  711: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  712: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  713: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  714: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  715: 	'<input type="hidden" name="command" value="submission" />'."\n".
  716: 	'<input type="hidden" name="student" value="" />'."\n".
  717: 	'<input type="hidden" name="userdom" value="" />'."\n".
  718: 	'</form>'."\n";
  719:     return $jscript;
  720: }
  721: 
  722: 
  723: 
  724: # Given the score (as a number [0-1] and the weight) what is the final
  725: # point value? This function will round to the nearest tenth, third,
  726: # or quarter if one of those is within the tolerance of .00001.
  727: sub compute_points {
  728:     my ($score, $weight) = @_;
  729:     
  730:     my $tolerance = .00001;
  731:     my $points = $score * $weight;
  732: 
  733:     # Check for nearness to 1/x.
  734:     my $check_for_nearness = sub {
  735:         my ($factor) = @_;
  736:         my $num = ($points * $factor) + $tolerance;
  737:         my $floored_num = floor($num);
  738:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  739:             return $floored_num / $factor;
  740:         }
  741:         return $points;
  742:     };
  743: 
  744:     $points = $check_for_nearness->(10);
  745:     $points = $check_for_nearness->(3);
  746:     $points = $check_for_nearness->(4);
  747:     
  748:     return $points;
  749: }
  750: 
  751: #------------------ End of general use routines --------------------
  752: 
  753: #
  754: # Find most similar essay
  755: #
  756: 
  757: sub most_similar {
  758:     my ($uname,$udom,$symb,$uessay)=@_;
  759: 
  760:     unless ($symb) { return ''; }
  761: 
  762:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  763: 
  764: # ignore spaces and punctuation
  765: 
  766:     $uessay=~s/\W+/ /gs;
  767: 
  768: # ignore empty submissions (occuring when only files are sent)
  769: 
  770:     unless ($uessay=~/\w+/s) { return ''; }
  771: 
  772: # these will be returned. Do not care if not at least 50 percent similar
  773:     my $limit=0.6;
  774:     my $sname='';
  775:     my $sdom='';
  776:     my $scrsid='';
  777:     my $sessay='';
  778: # go through all essays ...
  779:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  780: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  781: # ... except the same student
  782:         next if (($tname eq $uname) && ($tdom eq $udom));
  783: 	my $tessay=$old_essays{$symb}{$tkey};
  784: 	$tessay=~s/\W+/ /gs;
  785: # String similarity gives up if not even limit
  786: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  787: # Found one
  788: 	if ($tsimilar>$limit) {
  789: 	    $limit=$tsimilar;
  790: 	    $sname=$tname;
  791: 	    $sdom=$tdom;
  792: 	    $scrsid=$tcrsid;
  793: 	    $sessay=$old_essays{$symb}{$tkey};
  794: 	}
  795:     }
  796:     if ($limit>0.6) {
  797:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  798:     } else {
  799:        return ('','','','',0);
  800:     }
  801: }
  802: 
  803: #-------------------------------------------------------------------
  804: 
  805: #------------------------------------ Receipt Verification Routines
  806: #
  807: #--- Check whether a receipt number is valid.---
  808: sub verifyreceipt {
  809:     my $request  = shift;
  810: 
  811:     my $courseid = $env{'request.course.id'};
  812:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  813: 	$env{'form.receipt'};
  814:     $receipt     =~ s/[^\-\d]//g;
  815:     my ($symb)   = &get_symb($request);
  816: 
  817:     my $title.=
  818: 	'<h3><span class="LC_info">'.
  819: 	&mt('Verifying Receipt No. [_1]',$receipt).
  820: 	'</span></h3>'."\n".
  821: 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
  822: 	'</h4>'."\n";
  823: 
  824:     my ($string,$contents,$matches) = ('','',0);
  825:     my (undef,undef,$fullname) = &getclasslist('all','0');
  826:     
  827:     my $receiptparts=0;
  828:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  829: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  830:     my $parts=['0'];
  831:     if ($receiptparts) {
  832:         my $res_error; 
  833:         ($parts)=&response_type($symb,\$res_error);
  834:         if ($res_error) {
  835:             return &navmap_errormsg();
  836:         } 
  837:     }
  838:     
  839:     my $header = 
  840: 	&Apache::loncommon::start_data_table().
  841: 	&Apache::loncommon::start_data_table_header_row().
  842: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  843: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  844: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  845:     if ($receiptparts) {
  846: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  847:     }
  848:     $header.=
  849: 	&Apache::loncommon::end_data_table_header_row();
  850: 
  851:     foreach (sort 
  852: 	     {
  853: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  854: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  855: 		 }
  856: 		 return $a cmp $b;
  857: 	     } (keys(%$fullname))) {
  858: 	my ($uname,$udom)=split(/\:/);
  859: 	foreach my $part (@$parts) {
  860: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  861: 		$contents.=
  862: 		    &Apache::loncommon::start_data_table_row().
  863: 		    '<td>&nbsp;'."\n".
  864: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  865: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  866: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  867: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  868: 		if ($receiptparts) {
  869: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  870: 		}
  871: 		$contents.= 
  872: 		    &Apache::loncommon::end_data_table_row()."\n";
  873: 		
  874: 		$matches++;
  875: 	    }
  876: 	}
  877:     }
  878:     if ($matches == 0) {
  879:         $string = $title
  880:                  .'<p class="LC_warning">'
  881:                  .&mt('No match found for the above receipt number.')
  882:                  .'</p>';
  883:     } else {
  884: 	$string = &jscriptNform($symb).$title.
  885: 	    '<p>'.
  886: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  887: 	    '</p>'.
  888: 	    $header.
  889: 	    $contents.
  890: 	    &Apache::loncommon::end_data_table()."\n";
  891:     }
  892:     return $string.&show_grading_menu_form($symb);
  893: }
  894: 
  895: #--- This is called by a number of programs.
  896: #--- Called from the Grading Menu - View/Grade an individual student
  897: #--- Also called directly when one clicks on the subm button 
  898: #    on the problem page.
  899: sub listStudents {
  900:     my ($request) = shift;
  901: 
  902:     my ($symb) = &get_symb($request);
  903:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  904:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  905:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  906:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  907:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  908:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  909:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  910: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  911: 
  912:     my $result='<h3><span class="LC_info">&nbsp;'
  913: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  914: 	.'</span></h3>';
  915: 
  916:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  917: 
  918:     my %lt = &Apache::lonlocal::texthash (
  919: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  920: 		'single'   => 'Please select the student before clicking on the Next button.',
  921: 	     );
  922:     $request->print(<<LISTJAVASCRIPT);
  923: <script type="text/javascript" language="javascript">
  924:     function checkSelect(checkBox) {
  925: 	var ctr=0;
  926: 	var sense="";
  927: 	if (checkBox.length > 1) {
  928: 	    for (var i=0; i<checkBox.length; i++) {
  929: 		if (checkBox[i].checked) {
  930: 		    ctr++;
  931: 		}
  932: 	    }
  933: 	    sense = '$lt{'multiple'}';
  934: 	} else {
  935: 	    if (checkBox.checked) {
  936: 		ctr = 1;
  937: 	    }
  938: 	    sense = '$lt{'single'}';
  939: 	}
  940: 	if (ctr == 0) {
  941: 	    alert(sense);
  942: 	    return false;
  943: 	}
  944: 	document.gradesub.submit();
  945:     }
  946: 
  947:     function reLoadList(formname) {
  948: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  949: 	formname.command.value = 'submission';
  950: 	formname.submit();
  951:     }
  952: </script>
  953: LISTJAVASCRIPT
  954: 
  955:     &commonJSfunctions($request);
  956:     $request->print($result);
  957: 
  958:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  959:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  960:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  961: 	"\n".$table;
  962: 	
  963:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  964:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  965:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  966:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  967:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  968:                   .&Apache::lonhtmlcommon::row_closure();
  969:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  970:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  971:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  972:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  973:                   .&Apache::lonhtmlcommon::row_closure();
  974: 
  975:     my $submission_options;
  976:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  977: 	$submission_options.=
  978: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  979:     }
  980:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  981:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  982:     $env{'form.Status'} = $saveStatus;
  983:     $submission_options.=
  984:         '<span class="LC_nobreak">'.
  985:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  986:         &mt('last submission only').' </label></span>'."\n".
  987:         '<span class="LC_nobreak">'.
  988:         '<label><input type="radio" name="lastSub" value="last" /> '.
  989:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  990:         '<span class="LC_nobreak">'.
  991:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  992:         &mt('by dates and submissions').'</label></span>'."\n".
  993:         '<span class="LC_nobreak">'.
  994:         '<label><input type="radio" name="lastSub" value="all" /> '.
  995:         &mt('all details').'</label></span>';
  996:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  997:                   .$submission_options
  998:                   .&Apache::lonhtmlcommon::row_closure();
  999: 
 1000:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1001:                   .'<select name="increment">'
 1002:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1003:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1004:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1005:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1006:                   .'</select>'
 1007:                   .&Apache::lonhtmlcommon::row_closure();
 1008: 
 1009:     $gradeTable .= 
 1010:         &build_section_inputs().
 1011: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1012: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1013: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1014: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1015: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1016: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1017: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1018: 
 1019:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1020: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1021:     } else {
 1022:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1023:                       .&Apache::lonhtmlcommon::StatusOptions(
 1024:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1025:                       .&Apache::lonhtmlcommon::row_closure();
 1026:     }
 1027: 
 1028:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1029:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1030:                   .&Apache::lonhtmlcommon::row_closure(1)
 1031:                   .&Apache::lonhtmlcommon::end_pick_box();
 1032: 
 1033:     $gradeTable .= '<p>'
 1034:                   .&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"
 1035:                   .'<input type="hidden" name="command" value="processGroup" />'
 1036:                   .'</p>';
 1037: 
 1038: # checkall buttons
 1039:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1040:     $gradeTable.='<input type="button" '."\n".
 1041:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1042:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1043:     $gradeTable.=&check_buttons();
 1044:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1045:     $gradeTable.= &Apache::loncommon::start_data_table().
 1046: 	&Apache::loncommon::start_data_table_header_row();
 1047:     my $loop = 0;
 1048:     while ($loop < 2) {
 1049: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1050: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1051: 	if ($env{'form.showgrading'} eq 'yes' 
 1052: 	    && $submitonly ne 'queued'
 1053: 	    && $submitonly ne 'all') {
 1054: 	    foreach my $part (sort(@$partlist)) {
 1055: 		my $display_part=
 1056: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1057: 		$gradeTable.=
 1058: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1059: 	    }
 1060: 	} elsif ($submitonly eq 'queued') {
 1061: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1062: 	}
 1063: 	$loop++;
 1064: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1065:     }
 1066:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1067: 
 1068:     my $ctr = 0;
 1069:     foreach my $student (sort 
 1070: 			 {
 1071: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1072: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1073: 			     }
 1074: 			     return $a cmp $b;
 1075: 			 }
 1076: 			 (keys(%$fullname))) {
 1077: 	my ($uname,$udom) = split(/:/,$student);
 1078: 
 1079: 	my %status = ();
 1080: 
 1081: 	if ($submitonly eq 'queued') {
 1082: 	    my %queue_status = 
 1083: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1084: 							$udom,$uname);
 1085: 	    next if (!defined($queue_status{'gradingqueue'}));
 1086: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1087: 	}
 1088: 
 1089: 	if ($env{'form.showgrading'} eq 'yes' 
 1090: 	    && $submitonly ne 'queued'
 1091: 	    && $submitonly ne 'all') {
 1092: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1093: 	    my $submitted = 0;
 1094: 	    my $graded = 0;
 1095: 	    my $incorrect = 0;
 1096: 	    foreach (keys(%status)) {
 1097: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1098: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1099: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1100: 		
 1101: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1102: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1103: 		    $submitted = 0;
 1104: 		    my ($part)=split(/\./,$partid);
 1105: 		    $gradeTable.='<input type="hidden" name="'.
 1106: 			$student.':'.$part.':submitted_by" value="'.
 1107: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1108: 		}
 1109: 	    }
 1110: 	    
 1111: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1112: 				     $submitonly eq 'incorrect' ||
 1113: 				     $submitonly eq 'graded'));
 1114: 	    next if (!$graded && ($submitonly eq 'graded'));
 1115: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1116: 	}
 1117: 
 1118: 	$ctr++;
 1119: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1120:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1121: 	if ( $perm{'vgr'} eq 'F' ) {
 1122: 	    if ($ctr%2 ==1) {
 1123: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1124: 	    }
 1125: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1126:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1127:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1128: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1129: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1130: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1131: 
 1132: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1133: 		foreach (sort(keys(%status))) {
 1134: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1135: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1136: 		}
 1137: 	    }
 1138: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1139: 	    if ($ctr%2 ==0) {
 1140: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1141: 	    }
 1142: 	}
 1143:     }
 1144:     if ($ctr%2 ==1) {
 1145: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1146: 	    if ($env{'form.showgrading'} eq 'yes' 
 1147: 		&& $submitonly ne 'queued'
 1148: 		&& $submitonly ne 'all') {
 1149: 		foreach (@$partlist) {
 1150: 		    $gradeTable.='<td>&nbsp;</td>';
 1151: 		}
 1152: 	    } elsif ($submitonly eq 'queued') {
 1153: 		$gradeTable.='<td>&nbsp;</td>';
 1154: 	    }
 1155: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1156:     }
 1157: 
 1158:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1159:         '<input type="button" '.
 1160:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1161:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1162:     if ($ctr == 0) {
 1163: 	my $num_students=(scalar(keys(%$fullname)));
 1164: 	if ($num_students eq 0) {
 1165: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1166: 	} else {
 1167: 	    my $submissions='submissions';
 1168: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1169: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1170: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1171: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1172: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1173: 		    $num_students).
 1174: 		'</span><br />';
 1175: 	}
 1176:     } elsif ($ctr == 1) {
 1177: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1178:     }
 1179:     $gradeTable.=&show_grading_menu_form($symb);
 1180:     $request->print($gradeTable);
 1181:     return '';
 1182: }
 1183: 
 1184: #---- Called from the listStudents routine
 1185: 
 1186: sub check_script {
 1187:     my ($form, $type)=@_;
 1188:     my $chkallscript='<script type="text/javascript">
 1189:     function checkall() {
 1190:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1191:             ele = document.forms.'.$form.'.elements[i];
 1192:             if (ele.name == "'.$type.'") {
 1193:             document.forms.'.$form.'.elements[i].checked=true;
 1194:                                        }
 1195:         }
 1196:     }
 1197: 
 1198:     function checksec() {
 1199:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1200:             ele = document.forms.'.$form.'.elements[i];
 1201:            string = document.forms.'.$form.'.chksec.value;
 1202:            if
 1203:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1204:               document.forms.'.$form.'.elements[i].checked=true;
 1205:             }
 1206:         }
 1207:     }
 1208: 
 1209: 
 1210:     function uncheckall() {
 1211:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1212:             ele = document.forms.'.$form.'.elements[i];
 1213:             if (ele.name == "'.$type.'") {
 1214:             document.forms.'.$form.'.elements[i].checked=false;
 1215:                                        }
 1216:         }
 1217:     }
 1218: 
 1219: </script>'."\n";
 1220:     return $chkallscript;
 1221: }
 1222: 
 1223: sub check_buttons {
 1224:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1225:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1226:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1227:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1228:     return $buttons;
 1229: }
 1230: 
 1231: #     Displays the submissions for one student or a group of students
 1232: sub processGroup {
 1233:     my ($request)  = shift;
 1234:     my $ctr        = 0;
 1235:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1236:     my $total      = scalar(@stuchecked)-1;
 1237: 
 1238:     foreach my $student (@stuchecked) {
 1239: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1240: 	$env{'form.student'}        = $uname;
 1241: 	$env{'form.userdom'}        = $udom;
 1242: 	$env{'form.fullname'}       = $fullname;
 1243: 	&submission($request,$ctr,$total);
 1244: 	$ctr++;
 1245:     }
 1246:     return '';
 1247: }
 1248: 
 1249: #------------------------------------------------------------------------------------
 1250: #
 1251: #-------------------------- Next few routines handles grading by student, essentially
 1252: #                           handles essay response type problem/part
 1253: #
 1254: #--- Javascript to handle the submission page functionality ---
 1255: sub sub_page_js {
 1256:     my $request = shift;
 1257: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1258:     $request->print(<<SUBJAVASCRIPT);
 1259: <script type="text/javascript" language="javascript">
 1260:     function updateRadio(formname,id,weight) {
 1261: 	var gradeBox = formname["GD_BOX"+id];
 1262: 	var radioButton = formname["RADVAL"+id];
 1263: 	var oldpts = formname["oldpts"+id].value;
 1264: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1265: 	gradeBox.value = pts;
 1266: 	var resetbox = false;
 1267: 	if (isNaN(pts) || pts < 0) {
 1268: 	    alert("$alertmsg"+pts);
 1269: 	    for (var i=0; i<radioButton.length; i++) {
 1270: 		if (radioButton[i].checked) {
 1271: 		    gradeBox.value = i;
 1272: 		    resetbox = true;
 1273: 		}
 1274: 	    }
 1275: 	    if (!resetbox) {
 1276: 		formtextbox.value = "";
 1277: 	    }
 1278: 	    return;
 1279: 	}
 1280: 
 1281: 	if (pts > weight) {
 1282: 	    var resp = confirm("You entered a value ("+pts+
 1283: 			       ") greater than the weight for the part. Accept?");
 1284: 	    if (resp == false) {
 1285: 		gradeBox.value = oldpts;
 1286: 		return;
 1287: 	    }
 1288: 	}
 1289: 
 1290: 	for (var i=0; i<radioButton.length; i++) {
 1291: 	    radioButton[i].checked=false;
 1292: 	    if (pts == i && pts != "") {
 1293: 		radioButton[i].checked=true;
 1294: 	    }
 1295: 	}
 1296: 	updateSelect(formname,id);
 1297: 	formname["stores"+id].value = "0";
 1298:     }
 1299: 
 1300:     function writeBox(formname,id,pts) {
 1301: 	var gradeBox = formname["GD_BOX"+id];
 1302: 	if (checkSolved(formname,id) == 'update') {
 1303: 	    gradeBox.value = pts;
 1304: 	} else {
 1305: 	    var oldpts = formname["oldpts"+id].value;
 1306: 	    gradeBox.value = oldpts;
 1307: 	    var radioButton = formname["RADVAL"+id];
 1308: 	    for (var i=0; i<radioButton.length; i++) {
 1309: 		radioButton[i].checked=false;
 1310: 		if (i == oldpts) {
 1311: 		    radioButton[i].checked=true;
 1312: 		}
 1313: 	    }
 1314: 	}
 1315: 	formname["stores"+id].value = "0";
 1316: 	updateSelect(formname,id);
 1317: 	return;
 1318:     }
 1319: 
 1320:     function clearRadBox(formname,id) {
 1321: 	if (checkSolved(formname,id) == 'noupdate') {
 1322: 	    updateSelect(formname,id);
 1323: 	    return;
 1324: 	}
 1325: 	gradeSelect = formname["GD_SEL"+id];
 1326: 	for (var i=0; i<gradeSelect.length; i++) {
 1327: 	    if (gradeSelect[i].selected) {
 1328: 		var selectx=i;
 1329: 	    }
 1330: 	}
 1331: 	var stores = formname["stores"+id];
 1332: 	if (selectx == stores.value) { return };
 1333: 	var gradeBox = formname["GD_BOX"+id];
 1334: 	gradeBox.value = "";
 1335: 	var radioButton = formname["RADVAL"+id];
 1336: 	for (var i=0; i<radioButton.length; i++) {
 1337: 	    radioButton[i].checked=false;
 1338: 	}
 1339: 	stores.value = selectx;
 1340:     }
 1341: 
 1342:     function checkSolved(formname,id) {
 1343: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1344: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1345: 	    if (!reply) {return "noupdate";}
 1346: 	    formname.overRideScore.value = 'yes';
 1347: 	}
 1348: 	return "update";
 1349:     }
 1350: 
 1351:     function updateSelect(formname,id) {
 1352: 	formname["GD_SEL"+id][0].selected = true;
 1353: 	return;
 1354:     }
 1355: 
 1356: //=========== Check that a point is assigned for all the parts  ============
 1357:     function checksubmit(formname,val,total,parttot) {
 1358: 	formname.gradeOpt.value = val;
 1359: 	if (val == "Save & Next") {
 1360: 	    for (i=0;i<=total;i++) {
 1361: 		for (j=0;j<parttot;j++) {
 1362: 		    var partid = formname["partid"+i+"_"+j].value;
 1363: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1364: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1365: 			if (points == "") {
 1366: 			    var name = formname["name"+i].value;
 1367: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1368: 			    var resp = confirm("You did not assign a score for "+studentID+
 1369: 					       ", part "+partid+". Continue?");
 1370: 			    if (resp == false) {
 1371: 				formname["GD_BOX"+i+"_"+partid].focus();
 1372: 				return false;
 1373: 			    }
 1374: 			}
 1375: 		    }
 1376: 		    
 1377: 		}
 1378: 	    }
 1379: 	    
 1380: 	}
 1381: 	if (val == "Grade Student") {
 1382: 	    formname.showgrading.value = "yes";
 1383: 	    if (formname.Status.value == "") {
 1384: 		formname.Status.value = "Active";
 1385: 	    }
 1386: 	    formname.studentNo.value = total;
 1387: 	}
 1388: 	formname.submit();
 1389:     }
 1390: 
 1391: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1392:     function checkSubmitPage(formname,total) {
 1393: 	noscore = new Array(100);
 1394: 	var ptr = 0;
 1395: 	for (i=1;i<total;i++) {
 1396: 	    var partid = formname["q_"+i].value;
 1397: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1398: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1399: 		var status = formname["solved"+i+"_"+partid].value;
 1400: 		if (points == "" && status != "correct_by_student") {
 1401: 		    noscore[ptr] = i;
 1402: 		    ptr++;
 1403: 		}
 1404: 	    }
 1405: 	}
 1406: 	if (ptr != 0) {
 1407: 	    var sense = ptr == 1 ? ": " : "s: ";
 1408: 	    var prolist = "";
 1409: 	    if (ptr == 1) {
 1410: 		prolist = noscore[0];
 1411: 	    } else {
 1412: 		var i = 0;
 1413: 		while (i < ptr-1) {
 1414: 		    prolist += noscore[i]+", ";
 1415: 		    i++;
 1416: 		}
 1417: 		prolist += "and "+noscore[i];
 1418: 	    }
 1419: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1420: 	    if (resp == false) {
 1421: 		return false;
 1422: 	    }
 1423: 	}
 1424: 
 1425: 	formname.submit();
 1426:     }
 1427: </script>
 1428: SUBJAVASCRIPT
 1429: }
 1430: 
 1431: #--- javascript for essay type problem --
 1432: sub sub_page_kw_js {
 1433:     my $request = shift;
 1434:     my $iconpath = $request->dir_config('lonIconsURL');
 1435:     &commonJSfunctions($request);
 1436: 
 1437:     my $inner_js_msg_central=<<INNERJS;
 1438:     <script text="text/javascript">
 1439:     function checkInput() {
 1440:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1441:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1442:       var usrctr = document.msgcenter.usrctr.value;
 1443:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1444:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1445: 
 1446:       var msgchk = "";
 1447:       if (document.msgcenter.subchk.checked) {
 1448:          msgchk = "msgsub,";
 1449:       }
 1450:       var includemsg = 0;
 1451:       for (var i=1; i<=nmsg; i++) {
 1452:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1453:           var frmmsg = document.msgcenter["msg"+i];
 1454:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1455:           var showflg = opener.document.SCORE["shownOnce"+i];
 1456:           showflg.value = "1";
 1457:           var chkbox = document.msgcenter["msgn"+i];
 1458:           if (chkbox.checked) {
 1459:              msgchk += "savemsg"+i+",";
 1460:              includemsg = 1;
 1461:           }
 1462:       }
 1463:       if (document.msgcenter.newmsgchk.checked) {
 1464:          msgchk += "newmsg"+usrctr;
 1465:          includemsg = 1;
 1466:       }
 1467:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1468:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1469:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1470:       includemsg.value = msgchk;
 1471: 
 1472:       self.close()
 1473: 
 1474:     }
 1475:     </script>
 1476: INNERJS
 1477: 
 1478:     my $inner_js_highlight_central=<<INNERJS;
 1479:  <script type="text/javascript">
 1480:     function updateChoice(flag) {
 1481:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1482:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1483:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1484:       opener.document.SCORE.refresh.value = "on";
 1485:       if (opener.document.SCORE.keywords.value!=""){
 1486:          opener.document.SCORE.submit();
 1487:       }
 1488:       self.close()
 1489:     }
 1490: </script>
 1491: INNERJS
 1492: 
 1493:     my $start_page_msg_central = 
 1494:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1495: 				       {'js_ready'  => 1,
 1496: 					'only_body' => 1,
 1497: 					'bgcolor'   =>'#FFFFFF',});
 1498:     my $end_page_msg_central = 
 1499: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1500: 
 1501: 
 1502:     my $start_page_highlight_central = 
 1503:         &Apache::loncommon::start_page('Highlight Central',
 1504: 				       $inner_js_highlight_central,
 1505: 				       {'js_ready'  => 1,
 1506: 					'only_body' => 1,
 1507: 					'bgcolor'   =>'#FFFFFF',});
 1508:     my $end_page_highlight_central = 
 1509: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1510: 
 1511:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1512:     $docopen=~s/^document\.//;
 1513:     my %lt = &Apache::lonlocal::texthash(
 1514:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1515:                 plse => 'Please select a word or group of words from document and then click this link.',
 1516:                 adds => 'Add selection to keyword list? Edit if desired.',
 1517:                 comp => 'Compose Message for: ',
 1518:                 incl => 'Include',
 1519:                 type => 'Type',
 1520:                 subj => 'Subject',
 1521:                 mesa => 'Message',
 1522:                 new  => 'New',
 1523:                 save => 'Save',
 1524:                 canc => 'Cancel',
 1525:                 kehi => 'Keyword Highlight Options',
 1526:                 txtc => 'Text Color',
 1527:                 font => 'Font Size',
 1528:                 fnst => 'Font Style',
 1529:                 col1 => 'red',
 1530:                 col2 => 'green',
 1531:                 col3 => 'blue',
 1532:                 siz1 => 'normal',
 1533:                 siz2 => '+1',
 1534:                 siz3 => '+2',
 1535:                 sty1 => 'normal',
 1536:                 sty2 => 'italic',
 1537:                 sty3 => 'bold',
 1538:              );
 1539:     $request->print(<<SUBJAVASCRIPT);
 1540: <script type="text/javascript" language="javascript">
 1541: 
 1542: //===================== Show list of keywords ====================
 1543:   function keywords(formname) {
 1544:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1545:     if (nret==null) return;
 1546:     formname.keywords.value = nret;
 1547: 
 1548:     if (formname.keywords.value != "") {
 1549: 	formname.refresh.value = "on";
 1550: 	formname.submit();
 1551:     }
 1552:     return;
 1553:   }
 1554: 
 1555: //===================== Script to view submitted by ==================
 1556:   function viewSubmitter(submitter) {
 1557:     document.SCORE.refresh.value = "on";
 1558:     document.SCORE.NCT.value = "1";
 1559:     document.SCORE.unamedom0.value = submitter;
 1560:     document.SCORE.submit();
 1561:     return;
 1562:   }
 1563: 
 1564: //===================== Script to add keyword(s) ==================
 1565:   function getSel() {
 1566:     if (document.getSelection) txt = document.getSelection();
 1567:     else if (document.selection) txt = document.selection.createRange().text;
 1568:     else return;
 1569:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1570:     if (cleantxt=="") {
 1571: 	alert("$lt{'plse'}");
 1572: 	return;
 1573:     }
 1574:     var nret = prompt("$lt{'adds'}",cleantxt);
 1575:     if (nret==null) return;
 1576:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1577:     if (document.SCORE.keywords.value != "") {
 1578: 	document.SCORE.refresh.value = "on";
 1579: 	document.SCORE.submit();
 1580:     }
 1581:     return;
 1582:   }
 1583: 
 1584: //====================== Script for composing message ==============
 1585:    // preload images
 1586:    img1 = new Image();
 1587:    img1.src = "$iconpath/mailbkgrd.gif";
 1588:    img2 = new Image();
 1589:    img2.src = "$iconpath/mailto.gif";
 1590: 
 1591:   function msgCenter(msgform,usrctr,fullname) {
 1592:     var Nmsg  = msgform.savemsgN.value;
 1593:     savedMsgHeader(Nmsg,usrctr,fullname);
 1594:     var subject = msgform.msgsub.value;
 1595:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1596:     re = /msgsub/;
 1597:     var shwsel = "";
 1598:     if (re.test(msgchk)) { shwsel = "checked" }
 1599:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1600:     displaySubject(checkEntities(subject),shwsel);
 1601:     for (var i=1; i<=Nmsg; i++) {
 1602: 	var testmsg = "savemsg"+i+",";
 1603: 	re = new RegExp(testmsg,"g");
 1604: 	shwsel = "";
 1605: 	if (re.test(msgchk)) { shwsel = "checked" }
 1606: 	var message = document.SCORE["savemsg"+i].value;
 1607: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1608: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1609: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1610:     }
 1611:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1612:     shwsel = "";
 1613:     re = /newmsg/;
 1614:     if (re.test(msgchk)) { shwsel = "checked" }
 1615:     newMsg(newmsg,shwsel);
 1616:     msgTail(); 
 1617:     return;
 1618:   }
 1619: 
 1620:   function checkEntities(strx) {
 1621:     if (strx.length == 0) return strx;
 1622:     var orgStr = ["&", "<", ">", '"']; 
 1623:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1624:     var counter = 0;
 1625:     while (counter < 4) {
 1626: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1627: 	counter++;
 1628:     }
 1629:     return strx;
 1630:   }
 1631: 
 1632:   function strReplace(strx, orgStr, newStr) {
 1633:     return strx.split(orgStr).join(newStr);
 1634:   }
 1635: 
 1636:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1637:     var height = 70*Nmsg+250;
 1638:     if (height > 600) {
 1639: 	height = 600;
 1640:     }
 1641:     var xpos = (screen.width-600)/2;
 1642:     xpos = (xpos < 0) ? '0' : xpos;
 1643:     var ypos = (screen.height-height)/2-30;
 1644:     ypos = (ypos < 0) ? '0' : ypos;
 1645: 
 1646:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1647:     pWin.focus();
 1648:     pDoc = pWin.document;
 1649:     pDoc.$docopen;
 1650:     pDoc.write('$start_page_msg_central');
 1651: 
 1652:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1653:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1654:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1655: 
 1656:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1657:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1658:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1659: }
 1660:     function displaySubject(msg,shwsel) {
 1661:     pDoc = pWin.document;
 1662:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1663:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1664:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1665:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1666: }
 1667: 
 1668:   function displaySavedMsg(ctr,msg,shwsel) {
 1669:     pDoc = pWin.document;
 1670:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1671:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1672:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1673:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1674: }
 1675: 
 1676:   function newMsg(newmsg,shwsel) {
 1677:     pDoc = pWin.document;
 1678:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1679:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1680:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1681:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1682: }
 1683: 
 1684:   function msgTail() {
 1685:     pDoc = pWin.document;
 1686:     pDoc.write("<\\/table>");
 1687:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1688:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1689:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1690:     pDoc.write("<\\/form>");
 1691:     pDoc.write('$end_page_msg_central');
 1692:     pDoc.close();
 1693: }
 1694: 
 1695: //====================== Script for keyword highlight options ==============
 1696:   function kwhighlight() {
 1697:     var kwclr    = document.SCORE.kwclr.value;
 1698:     var kwsize   = document.SCORE.kwsize.value;
 1699:     var kwstyle  = document.SCORE.kwstyle.value;
 1700:     var redsel = "";
 1701:     var grnsel = "";
 1702:     var blusel = "";
 1703:     var txtcol1 = "$lt{'col1'}";
 1704:     var txtcol2 = "$lt{'col2'}";
 1705:     var txtcol3 = "$lt{'col3'}";
 1706:     var txtsiz1 = "$lt{'siz1'}";
 1707:     var txtsiz2 = "$lt{'siz2'}";
 1708:     var txtsiz3 = "$lt{'siz3'}";
 1709:     var txtsty1 = "$lt{'sty1'}";
 1710:     var txtsty2 = "$lt{'sty2'}";
 1711:     var txtsty3 = "$lt{'sty3'}";
 1712:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1713:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1714:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1715:     var sznsel = "";
 1716:     var sz1sel = "";
 1717:     var sz2sel = "";
 1718:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1719:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1720:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1721:     var synsel = "";
 1722:     var syisel = "";
 1723:     var sybsel = "";
 1724:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1725:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1726:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1727:     highlightCentral();
 1728:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1729:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1730:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1731:     highlightend();
 1732:     return;
 1733:   }
 1734: 
 1735:   function highlightCentral() {
 1736: //    if (window.hwdWin) window.hwdWin.close();
 1737:     var xpos = (screen.width-400)/2;
 1738:     xpos = (xpos < 0) ? '0' : xpos;
 1739:     var ypos = (screen.height-330)/2-30;
 1740:     ypos = (ypos < 0) ? '0' : ypos;
 1741: 
 1742:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1743:     hwdWin.focus();
 1744:     var hDoc = hwdWin.document;
 1745:     hDoc.$docopen;
 1746:     hDoc.write('$start_page_highlight_central');
 1747:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1748:     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
 1749: 
 1750:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1751:     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
 1752:   }
 1753: 
 1754:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1755:     var hDoc = hwdWin.document;
 1756:     hDoc.write("<tr>");
 1757:     hDoc.write("<td align=\\"left\\">");
 1758:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1759:     hDoc.write("<td align=\\"left\\">");
 1760:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1761:     hDoc.write("<td align=\\"left\\">");
 1762:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1763:     hDoc.write("<\\/tr>");
 1764:   }
 1765: 
 1766:   function highlightend() { 
 1767:     var hDoc = hwdWin.document;
 1768:     hDoc.write("<\\/table><br \\/>");
 1769:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1770:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1771:     hDoc.write("<\\/form>");
 1772:     hDoc.write('$end_page_highlight_central');
 1773:     hDoc.close();
 1774:   }
 1775: 
 1776: </script>
 1777: SUBJAVASCRIPT
 1778: }
 1779: 
 1780: sub get_increment {
 1781:     my $increment = $env{'form.increment'};
 1782:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1783:         $increment != .1) {
 1784:         $increment = 1;
 1785:     }
 1786:     return $increment;
 1787: }
 1788: 
 1789: sub gradeBox_start {
 1790:     return (
 1791:         &Apache::loncommon::start_data_table()
 1792:        .&Apache::loncommon::start_data_table_header_row()
 1793:        .'<th>'.&mt('Part').'</th>'
 1794:        .'<th>'.&mt('Points').'</th>'
 1795:        .'<th>&nbsp;</th>'
 1796:        .'<th>'.&mt('Assign Grade').'</th>'
 1797:        .'<th>'.&mt('Weight').'</th>'
 1798:        .'<th>'.&mt('Grade Status').'</th>'
 1799:        .&Apache::loncommon::end_data_table_header_row()
 1800:     );
 1801: }
 1802: 
 1803: sub gradeBox_end {
 1804:     return (
 1805:         &Apache::loncommon::end_data_table()
 1806:     );
 1807: }
 1808: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1809: sub gradeBox {
 1810:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1811:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1812: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1813:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1814:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1815:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1816:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1817:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1818: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1819:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1820:     my $display_part= &get_display_part($partid,$symb);
 1821:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1822: 				       [$partid]);
 1823:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1824:     if ($last_resets{$partid}) {
 1825:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1826:     }
 1827:     my $result=&Apache::loncommon::start_data_table_row();
 1828:     my $ctr = 0;
 1829:     my $thisweight = 0;
 1830:     my $increment = &get_increment();
 1831: 
 1832:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1833:     while ($thisweight<=$wgt) {
 1834: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1835:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1836: 	    $thisweight.')" value="'.$thisweight.'" '.
 1837: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1838: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1839:         $thisweight += $increment;
 1840: 	$ctr++;
 1841:     }
 1842:     $radio.='</tr></table>';
 1843: 
 1844:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1845: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1846: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1847: 	$wgt.')" /></td>'."\n";
 1848:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1849: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1850: 	' </td>'."\n";
 1851:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1852: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1853:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1854: 	$line.='<option></option>'.
 1855: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1856:     } else {
 1857: 	$line.='<option selected="selected"></option>'.
 1858: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1859:     }
 1860:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1861: 
 1862: 
 1863:     $result .= 
 1864: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1865:     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
 1866:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1867: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1868: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1869: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1870:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1871:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1872:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1873:         $aggtries.'" />'."\n";
 1874:     my $res_error;
 1875:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1876:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1877:     if ($res_error) {
 1878:         return &navmap_errormsg();
 1879:     }
 1880:     return $result;
 1881: }
 1882: 
 1883: sub handback_box {
 1884:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1885:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1886:     my (@respids);
 1887:     my @part_response_id = &flatten_responseType($responseType);
 1888:     foreach my $part_response_id (@part_response_id) {
 1889:     	my ($part,$resp) = @{ $part_response_id };
 1890:         if ($part eq $partid) {
 1891:             push(@respids,$resp);
 1892:         }
 1893:     }
 1894:     my $result;
 1895:     foreach my $respid (@respids) {
 1896: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1897: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1898: 	next if (!@$files);
 1899: 	my $file_counter = 0;
 1900: 	foreach my $file (@$files) {
 1901: 	    if ($file =~ /\/portfolio\//) {
 1902:                 $file_counter++;
 1903:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1904:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1905:     	        $file_disp = "$name.$ext";
 1906:     	        $file = $file_path.$file_disp;
 1907:     	        $result.=&mt('Return commented version of [_1] to student.',
 1908:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1909:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1910:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1911: 	    }
 1912: 	}
 1913:         if ($file_counter) {
 1914:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1915:                        '<span class="LC_info">'.
 1916:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1917:         }
 1918:     }
 1919:     return $result;    
 1920: }
 1921: 
 1922: sub show_problem {
 1923:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1924:     my $rendered;
 1925:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1926:     &Apache::lonxml::remember_problem_counter();
 1927:     if ($mode eq 'both' or $mode eq 'text') {
 1928: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1929: 						       $env{'request.course.id'},
 1930: 						       undef,\%form);
 1931:     }
 1932:     if ($removeform) {
 1933: 	$rendered=~s|<form(.*?)>||g;
 1934: 	$rendered=~s|</form>||g;
 1935: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1936:     }
 1937:     my $companswer;
 1938:     if ($mode eq 'both' or $mode eq 'answer') {
 1939: 	&Apache::lonxml::restore_problem_counter();
 1940: 	$companswer=
 1941: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1942: 						    $env{'request.course.id'},
 1943: 						    %form);
 1944:     }
 1945:     if ($removeform) {
 1946: 	$companswer=~s|<form(.*?)>||g;
 1947: 	$companswer=~s|</form>||g;
 1948: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1949:     }
 1950:     my $renderheading = &mt('View of the problem');
 1951:     my $answerheading = &mt('Correct answer');
 1952:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1953:         my $stu_fullname = $env{'form.fullname'};
 1954:         if ($stu_fullname eq '') {
 1955:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1956:         }
 1957:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1958:         if ($forwhom ne '') {
 1959:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1960:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1961:         }
 1962:     }
 1963:     $rendered=
 1964:         '<div class="LC_Box">'
 1965:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1966:        .$rendered
 1967:        .'</div>';
 1968:     $companswer=
 1969:         '<div class="LC_Box">'
 1970:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1971:        .$companswer
 1972:        .'</div>';
 1973:     my $result;
 1974:     if ($mode eq 'both') {
 1975:         $result=$rendered.$companswer;
 1976:     } elsif ($mode eq 'text') {
 1977:         $result=$rendered;
 1978:     } elsif ($mode eq 'answer') {
 1979:         $result=$companswer;
 1980:     }
 1981:     return $result;
 1982: }
 1983: 
 1984: sub files_exist {
 1985:     my ($r, $symb) = @_;
 1986:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1987: 
 1988:     foreach my $student (@students) {
 1989:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1990:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1991: 					      $udom,$uname);
 1992:         my ($string,$timestamp)= &get_last_submission(\%record);
 1993:         foreach my $submission (@$string) {
 1994:             my ($partid,$respid) =
 1995: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1996:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1997: 					   \%record);
 1998:             return 1 if (@$files);
 1999:         }
 2000:     }
 2001:     return 0;
 2002: }
 2003: 
 2004: sub download_all_link {
 2005:     my ($r,$symb) = @_;
 2006:     my $all_students = 
 2007: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2008: 
 2009:     my $parts =
 2010: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2011: 
 2012:     my $identifier = &Apache::loncommon::get_cgi_id();
 2013:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2014:                              'cgi.'.$identifier.'.symb' => $symb,
 2015:                              'cgi.'.$identifier.'.parts' => $parts,});
 2016:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2017: 	      &mt('Download All Submitted Documents').'</a>');
 2018:     return
 2019: }
 2020: 
 2021: sub build_section_inputs {
 2022:     my $section_inputs;
 2023:     if ($env{'form.section'} eq '') {
 2024:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2025:     } else {
 2026:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2027:         foreach my $section (@sections) {
 2028:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2029:         }
 2030:     }
 2031:     return $section_inputs;
 2032: }
 2033: 
 2034: # --------------------------- show submissions of a student, option to grade 
 2035: sub submission {
 2036:     my ($request,$counter,$total) = @_;
 2037:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2038:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2039:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2040:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2041:     my ($symb) = &get_symb($request); 
 2042:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2043: 
 2044:     if (!&canview($usec)) {
 2045:         $request->print(
 2046:             '<span class="LC_warning">'.
 2047:             &mt('Unable to view requested student.').
 2048:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2049:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2050:             '</span>');
 2051: 	$request->print(&show_grading_menu_form($symb));
 2052: 	return;
 2053:     }
 2054: 
 2055:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2056:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2057:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2058:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2059:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2060: 	'" src="'.$request->dir_config('lonIconsURL').
 2061: 	'/check.gif" height="16" border="0" />';
 2062: 
 2063:     # header info
 2064:     if ($counter == 0) {
 2065: 	&sub_page_js($request);
 2066: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2067: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2068: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2069: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2070: 	    &download_all_link($request, $symb);
 2071: 	}
 2072: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2073: 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
 2074: 
 2075: 	# option to display problem, only once else it cause problems 
 2076:         # with the form later since the problem has a form.
 2077: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2078: 	    my $mode;
 2079: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2080: 		$mode='both';
 2081: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2082: 		$mode='text';
 2083: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2084: 		$mode='answer';
 2085: 	    }
 2086: 	    &Apache::lonxml::clear_problem_counter();
 2087: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2088: 	}
 2089: 
 2090: 	# kwclr is the only variable that is guaranteed not to be blank 
 2091:         # if this subroutine has been called once.
 2092: 	my %keyhash = ();
 2093: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2094: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2095: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2096: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2097: 
 2098: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2099: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2100: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2101: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2102: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2103: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2104: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2105: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2106: 	}
 2107: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2108: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2109: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2110: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2111: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2112: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2113: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2114: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2115: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2116: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2117: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2118: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2119: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2120: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2121: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2122: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2123: 			&build_section_inputs().
 2124: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2125: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2126: 			'<input type="hidden" name="NCT"'.
 2127: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2128: 	if ($env{'form.handgrade'} eq 'yes') {
 2129: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2130: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2131: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2132: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2133: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2134: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2135: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2136: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2137: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2138: 	    }
 2139: 	}
 2140: 	
 2141: 	my ($cts,$prnmsg) = (1,'');
 2142: 	while ($cts <= $env{'form.savemsgN'}) {
 2143: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2144: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2145: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2146: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2147: 		'" />'."\n".
 2148: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2149: 	    $cts++;
 2150: 	}
 2151: 	$request->print($prnmsg);
 2152: 
 2153: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2154: 
 2155:             my %lt = &Apache::lonlocal::texthash(
 2156:                           keyh => 'Keyword Highlighting for Essays',
 2157:                           keyw => 'Keyword Options',
 2158:                           list => 'List',
 2159:                           past => 'Paste Selection to List',
 2160:                           high => 'Highlight Attribute',
 2161:                      );
 2162: #
 2163: # Print out the keyword options line
 2164: #
 2165:             $request->print(
 2166:                 '<div class="LC_columnSection">'
 2167:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2168:                .&Apache::lonhtmlcommon::funclist_from_array(
 2169:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2170:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2171:  class="page">'.$lt{'past'}.'</a>',
 2172:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2173:                     {legend => $lt{'keyw'}})
 2174:                .'</fieldset></div>'
 2175:             );
 2176: 
 2177: #
 2178: # Load the other essays for similarity check
 2179: #
 2180:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2181: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2182: 	    $apath=&escape($apath);
 2183: 	    $apath=~s/\W/\_/gs;
 2184:             &init_old_essays($symb,$apath,$adom,$aname);
 2185:         }
 2186:     }
 2187: 
 2188: # This is where output for one specific student would start
 2189:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2190:     $request->print(
 2191:         "\n\n"
 2192:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2193:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2194:        ."\n"
 2195:     );
 2196: 
 2197:     # Show additional functions if allowed
 2198:     if ($perm{'vgr'}) {
 2199:         $request->print(
 2200:             &Apache::loncommon::track_student_link(
 2201:                 'View recent activity',
 2202:                 $uname,$udom,'check')
 2203:            .' '
 2204:         );
 2205:     }
 2206:     if ($perm{'opa'}) {
 2207:         $request->print(
 2208:             &Apache::loncommon::pprmlink(
 2209:                 &mt('Set/Change parameters'),
 2210:                 $uname,$udom,$symb,'check'));
 2211:     }
 2212: 
 2213:     # Show Problem
 2214:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2215: 	my $mode;
 2216: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2217: 	    $mode='both';
 2218: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2219: 	    $mode='text';
 2220: 	} elsif ($env{'form.vAns'} eq 'all') {
 2221: 	    $mode='answer';
 2222: 	}
 2223: 	&Apache::lonxml::clear_problem_counter();
 2224: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2225:     }
 2226: 
 2227:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2228:     my $res_error;
 2229:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2230:     if ($res_error) {
 2231:         $request->print(&navmap_errormsg());
 2232:         return;
 2233:     }
 2234: 
 2235:     # Display student info
 2236:     $request->print(($counter == 0 ? '' : '<br />'));
 2237: 
 2238:     my $result='<div class="LC_Box">'
 2239:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2240:     $result.='<input type="hidden" name="name'.$counter.
 2241:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2242:     if ($env{'form.handgrade'} eq 'no') {
 2243:         $result.='<p class="LC_info">'
 2244:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2245:                 ."</p>\n";
 2246:     }
 2247: 
 2248:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2249:     my $fullname;
 2250:     my $col_fullnames = [];
 2251:     if ($env{'form.handgrade'} eq 'yes') {
 2252: 	(my $sub_result,$fullname,$col_fullnames)=
 2253: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2254: 				 $counter);
 2255: 	$result.=$sub_result;
 2256:     }
 2257:     $request->print($result."\n");
 2258: 
 2259:     # print student answer/submission
 2260:     # Options are (1) Handgraded submission only
 2261:     #             (2) Last submission, includes submission that is not handgraded 
 2262:     #                  (for multi-response type part)
 2263:     #             (3) Last submission plus the parts info
 2264:     #             (4) The whole record for this student
 2265: 
 2266: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2267: 	
 2268: 	my $lastsubonly;
 2269: 
 2270:         if ($$timestamp eq '') {
 2271:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2272:         } else {
 2273:             $lastsubonly =
 2274:                 '<div class="LC_grade_submissions_body">'
 2275:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2276: 
 2277: 	    my %seenparts;
 2278: 	    my @part_response_id = &flatten_responseType($responseType);
 2279: 	    foreach my $part (@part_response_id) {
 2280: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2281: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2282: 
 2283: 		my ($partid,$respid) = @{ $part };
 2284: 		my $display_part=&get_display_part($partid,$symb);
 2285: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2286: 		    if (exists($seenparts{$partid})) { next; }
 2287: 		    $seenparts{$partid}=1;
 2288:                     $request->print(
 2289:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2290:                         ' <b>'.&mt('Collaborative submission by: [_1]',
 2291:                                    '<a href="javascript:viewSubmitter(\''.
 2292:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
 2293:                                    '\');" target="_self">'.
 2294:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2295:                         '<br />');
 2296: 		    next;
 2297: 		}
 2298: 		my $responsetype = $responseType->{$partid}->{$respid};
 2299: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2300:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2301:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2302:                         ' <span class="LC_internal_info">'.
 2303:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2304:                         '</span>&nbsp; &nbsp;'.
 2305: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2306: 		    next;
 2307: 		}
 2308: 		foreach my $submission (@$string) {
 2309: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2310: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2311: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2312: 		    # Similarity check
 2313: 		    my $similar='';
 2314:                     my ($type,$trial,$rndseed);
 2315:                     if ($hide eq 'rand') {
 2316:                         $type = 'randomizetry';
 2317:                         $trial = $record{"resource.$partid.tries"};
 2318:                         $rndseed = $record{"resource.$partid.rndseed"};
 2319:                     }
 2320: 		    if ($env{'form.checkPlag'}) {
 2321: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2322: 			    &most_similar($uname,$udom,$symb,$subval);
 2323: 			if ($osim) {
 2324: 			    $osim=int($osim*100.0);
 2325: 			    my %old_course_desc = 
 2326: 				&Apache::lonnet::coursedescription($ocrsid,
 2327: 								   {'one_time' => 1});
 2328: 
 2329:                             if ($hide eq 'anon') {
 2330:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2331:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2332:                             } else {
 2333: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2334: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2335: 				        $osim,
 2336: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2337: 				        $old_course_desc{'description'},
 2338: 				        $old_course_desc{'num'},
 2339: 				        $old_course_desc{'domain'}).
 2340: 				    '</span></h3><blockquote><i>'.
 2341: 				    &keywords_highlight($oessay).
 2342: 				    '</i></blockquote><hr />';
 2343:                             }
 2344: 			}
 2345: 		    }
 2346: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2347:                                          undef,$type,$trial,$rndseed);
 2348:                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
 2349:                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2350: 			my $display_part=&get_display_part($partid,$symb);
 2351:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2352:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2353:                             ' <span class="LC_internal_info">'.
 2354:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2355:                             '</span>&nbsp; &nbsp;';
 2356: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2357: 			if (@$files) {
 2358:                             if ($hide eq 'anon') {
 2359:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2360:                             } else {
 2361:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2362:                                             .'<br /><span class="LC_warning">';
 2363:                                 if(@$files == 1) {
 2364:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2365:                                 } else {
 2366:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2367:                                 }
 2368:                                 $lastsubonly .= '</span>';
 2369: 
 2370:                                 foreach my $file (@$files) {
 2371:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2372:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2373:                                 }
 2374:                             }
 2375: 			    $lastsubonly.='<br />';
 2376: 			}
 2377:                         if ($hide eq 'anon') {
 2378:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2379:                         } else {
 2380: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
 2381: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2382: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2383:                         }
 2384: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2385: 			$lastsubonly.='</div>';
 2386: 		    }
 2387: 		}
 2388: 	    }
 2389: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2390: 	}
 2391: 	$request->print($lastsubonly);
 2392:    if ($env{'form.lastSub'} eq 'datesub') {
 2393: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2394: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2395:     }
 2396:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2397: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2398: 								 $env{'request.course.id'},
 2399: 								 $last,'.submission',
 2400: 								 'Apache::grades::keywords_highlight'));
 2401:     }
 2402: 
 2403:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2404: 	.$udom.'" />'."\n");
 2405:     # return if view submission with no grading option
 2406:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2407: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2408: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2409: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2410: 	$toGrade.='</div>'."\n";
 2411: 	if (($env{'form.command'} eq 'submission') || 
 2412: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2413: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2414: 	}
 2415: 	$request->print($toGrade);
 2416: 	return;
 2417:     } else {
 2418: 	$request->print('</div>'."\n");
 2419:     }
 2420: 
 2421:     # essay grading message center
 2422:     if ($env{'form.handgrade'} eq 'yes') {
 2423: 	my $result='<div class="LC_grade_message_center">';
 2424:     
 2425: 	$result.='<div class="LC_grade_message_center_header">'.
 2426: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2427: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2428: 	my $msgfor = $givenn.' '.$lastname;
 2429: 	if (scalar(@$col_fullnames) > 0) {
 2430: 	    my $lastone = pop(@$col_fullnames);
 2431: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2432: 	}
 2433: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2434: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2435: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2436: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2437: 	    ',\''.$msgfor.'\');" target="_self">'.
 2438: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2439: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2440: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2441: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2442: 	    '<br />&nbsp;('.
 2443: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2444: 	$result.='</div></div>';
 2445: 	$request->print($result);
 2446:     }
 2447: 
 2448:     my %seen = ();
 2449:     my @partlist;
 2450:     my @gradePartRespid;
 2451:     my @part_response_id = &flatten_responseType($responseType);
 2452:     $request->print(
 2453:         '<div class="LC_Box">'
 2454:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2455:     );
 2456:     $request->print(&gradeBox_start());
 2457:     foreach my $part_response_id (@part_response_id) {
 2458:     	my ($partid,$respid) = @{ $part_response_id };
 2459: 	my $part_resp = join('_',@{ $part_response_id });
 2460: 	next if ($seen{$partid} > 0);
 2461: 	$seen{$partid}++;
 2462: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2463: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2464: 	push(@partlist,$partid);
 2465: 	push(@gradePartRespid,$partid.'.'.$respid);
 2466: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2467:     }
 2468:     $request->print(&gradeBox_end()); # </div>
 2469:     $request->print('</div>');
 2470: 
 2471:     $request->print('<div class="LC_grade_info_links">');
 2472:     $request->print('</div>');
 2473: 
 2474:     $result='<input type="hidden" name="partlist'.$counter.
 2475: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2476:     $result.='<input type="hidden" name="gradePartRespid'.
 2477: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2478:     my $ctr = 0;
 2479:     while ($ctr < scalar(@partlist)) {
 2480: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2481: 	    $partlist[$ctr].'" />'."\n";
 2482: 	$ctr++;
 2483:     }
 2484:     $request->print($result.''."\n");
 2485: 
 2486: # Done with printing info for one student
 2487: 
 2488:     $request->print('</div>');#LC_grade_show_user
 2489: 
 2490: 
 2491:     # print end of form
 2492:     if ($counter == $total) {
 2493:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2494: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2495: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2496: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2497: 	my $ntstu ='<select name="NTSTU">'.
 2498: 	    '<option>1</option><option>2</option>'.
 2499: 	    '<option>3</option><option>5</option>'.
 2500: 	    '<option>7</option><option>10</option></select>'."\n";
 2501: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2502: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2503:         $endform.=&mt('[_1]student(s)',$ntstu);
 2504: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2505: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2506: 	    '<input type="button" value="'.&mt('Next').'" '.
 2507: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2508:         $endform.='<span class="LC_warning">'.
 2509:                   &mt('(Next and Previous (student) do not save the scores.)').
 2510:                   '</span>'."\n" ;
 2511:         $endform.="<input type='hidden' value='".&get_increment().
 2512:             "' name='increment' />";
 2513: 	$endform.='</td></tr></table></form>';
 2514: 	$endform.=&show_grading_menu_form($symb);
 2515: 	$request->print($endform);
 2516:     }
 2517:     return '';
 2518: }
 2519: 
 2520: sub check_collaborators {
 2521:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2522:     my ($result,@col_fullnames);
 2523:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2524:     foreach my $part (keys(%$handgrade)) {
 2525: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2526: 					'.maxcollaborators',
 2527: 					$symb,$udom,$uname);
 2528: 	next if ($ncol <= 0);
 2529: 	$part =~ s/\_/\./g;
 2530: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2531: 	my (@good_collaborators, @bad_collaborators);
 2532: 	foreach my $possible_collaborator
 2533: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2534: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2535: 	    next if ($possible_collaborator eq '');
 2536: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2537: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2538: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2539: 	    # Doing this grep allows 'fuzzy' specification
 2540: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2541: 			       keys(%$classlist));
 2542: 	    if (! scalar(@matches)) {
 2543: 		push(@bad_collaborators, $possible_collaborator);
 2544: 	    } else {
 2545: 		push(@good_collaborators, @matches);
 2546: 	    }
 2547: 	}
 2548: 	if (scalar(@good_collaborators) != 0) {
 2549: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2550: 	    foreach my $name (@good_collaborators) {
 2551: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2552: 		push(@col_fullnames, $givenn.' '.$lastname);
 2553: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2554: 	    }
 2555: 	    $result.='</ol><br />'."\n";
 2556: 	    my ($part)=split(/\./,$part);
 2557: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2558: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2559: 		"\n";
 2560: 	}
 2561: 	if (scalar(@bad_collaborators) > 0) {
 2562: 	    $result.='<div class="LC_warning">';
 2563: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2564: 	    $result .= '</div>';
 2565: 	}         
 2566: 	if (scalar(@bad_collaborators > $ncol)) {
 2567: 	    $result .= '<div class="LC_warning">';
 2568: 	    $result .= &mt('This student has submitted too many '.
 2569: 		'collaborators.  Maximum is [_1].',$ncol);
 2570: 	    $result .= '</div>';
 2571: 	}
 2572:     }
 2573:     return ($result,$fullname,\@col_fullnames);
 2574: }
 2575: 
 2576: #--- Retrieve the last submission for all the parts
 2577: sub get_last_submission {
 2578:     my ($returnhash)=@_;
 2579:     my (@string,$timestamp,%lasthidden);
 2580:     if ($$returnhash{'version'}) {
 2581: 	my %lasthash=();
 2582: 	my ($version);
 2583: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2584: 	    foreach my $key (sort(split(/\:/,
 2585: 					$$returnhash{$version.':keys'}))) {
 2586: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2587: 		$timestamp = 
 2588: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2589: 	    }
 2590: 	}
 2591:         my (%typeparts,%randombytry);
 2592:         my $showsurv = 
 2593:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2594:         foreach my $key (sort(keys(%lasthash))) {
 2595:             if ($key =~ /\.type$/) {
 2596:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2597:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2598:                     ($lasthash{$key} eq 'randomizetry')) {
 2599:                     my ($ign,@parts) = split(/\./,$key);
 2600:                     pop(@parts);
 2601:                     my $id = join('.',@parts);
 2602:                     if ($lasthash{$key} eq 'randomizetry') {
 2603:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2604:                     } else {
 2605:                         unless ($showsurv) {
 2606:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2607:                         }
 2608:                     }
 2609:                     delete($lasthash{$key});
 2610:                 }
 2611:             }
 2612:         }
 2613:         my @hidden = keys(%typeparts);
 2614:         my @randomize = keys(%randombytry);
 2615: 	foreach my $key (keys(%lasthash)) {
 2616: 	    next if ($key !~ /\.submission$/);
 2617:             my $hide;
 2618:             if (@hidden) {
 2619:                 foreach my $id (@hidden) {
 2620:                     if ($key =~ /^\Q$id\E/) {
 2621:                         $hide = 'anon';
 2622:                         last;
 2623:                     }
 2624:                 }
 2625:             }
 2626:             unless ($hide) {
 2627:                 if (@randomize) {
 2628:                     foreach my $id (@hidden) {
 2629:                         if ($key =~ /^\Q$id\E/) {
 2630:                             $hide = 'rand';
 2631:                             last;
 2632:                         }
 2633:                     }
 2634:                 }
 2635:             }
 2636: 	    my ($partid,$foo) = split(/submission$/,$key);
 2637: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2638: 		'<span class="LC_warning">'.&mt('Draft Copy').'</span> ' : '';
 2639:             push(@string, join(':', $key, $hide, $draft.(
 2640:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2641:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2642: 	}
 2643:     }
 2644:     if (!@string) {
 2645: 	$string[0] =
 2646: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2647:     }
 2648:     return (\@string,\$timestamp);
 2649: }
 2650: 
 2651: #--- High light keywords, with style choosen by user.
 2652: sub keywords_highlight {
 2653:     my $string    = shift;
 2654:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2655:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2656:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2657:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2658:     foreach my $keyword (@keylist) {
 2659: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2660:     }
 2661:     return $string;
 2662: }
 2663: 
 2664: # For Tasks provide a mechanism to display previous version for one specific student
 2665: 
 2666: sub show_previous_task_version {
 2667:     my ($request,$symb) = @_;
 2668:     if ($symb eq '') {
 2669:         $request->print(
 2670:             '<span class="LC_error">'.
 2671:             &mt('Unable to handle ambiguous references.').
 2672:             '</span>');
 2673:         return '';
 2674:     }
 2675:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2676:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2677:     if (!&canview($usec)) {
 2678:         $request->print('<span class="LC_warning">'.
 2679:                         &mt('Unable to view previous version for requested student.').
 2680:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2681:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}.').
 2682:                         '</span>');
 2683:         return;
 2684:     }
 2685:     my $mode = 'both';
 2686:     my $isTask = ($symb =~/\.task$/);
 2687:     if ($isTask) {
 2688:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2689:             if ($env{'form.fullname'} eq '') {
 2690:                 $env{'form.fullname'} =
 2691:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2692:             }
 2693:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2694:             $request->print("\n\n".
 2695:                             '<div class="LC_grade_show_user">'.
 2696:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2697:                             '</h2>'."\n");
 2698:             &Apache::lonxml::clear_problem_counter();
 2699:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2700:                             {'previousversion' => $env{'form.previousversion'} }));
 2701:             $request->print("\n</div>");
 2702:         }
 2703:     }
 2704:     return;
 2705: }
 2706: 
 2707: sub choose_task_version_form {
 2708:     my ($symb,$uname,$udom,$nomenu) = @_;
 2709:     my $isTask = ($symb =~/\.task$/);
 2710:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2711:     if ($isTask) {
 2712:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2713:                                               $udom,$uname);
 2714:         if (($record{'resource.0.version'} eq '') ||
 2715:             ($record{'resource.0.version'} < 2)) {
 2716:             return ($record{'resource.0.version'},
 2717:                     $record{'resource.0.version'},$result,$js);
 2718:         } else {
 2719:             $current = $record{'resource.0.version'};
 2720:         }
 2721:         if ($env{'form.previousversion'}) {
 2722:             $displayed = $env{'form.previousversion'};
 2723:             $rowtitle = &mt('Choose another version:')
 2724:         } else {
 2725:             $displayed = $current;
 2726:             $rowtitle = &mt('Show earlier version:');
 2727:         }
 2728:         $result = '<div class="LC_left_float">';
 2729:         my $list;
 2730:         my $numversions = 0;
 2731:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2732:             if ($i == $current) {
 2733:                 if (!$env{'form.previousversion'} || $nomenu) {
 2734:                     next;
 2735:                 } else {
 2736:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2737:                     $numversions ++;
 2738:                 }
 2739:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2740:                 unless ($i == $env{'form.previousversion'}) {
 2741:                     $numversions ++;
 2742:                 }
 2743:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2744:             }
 2745:         }
 2746:         if ($numversions) {
 2747:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2748:             $result .=
 2749:                 '<form name="getprev" method="post" action=""'.
 2750:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2751:                 &Apache::loncommon::start_data_table().
 2752:                 &Apache::loncommon::start_data_table_row().
 2753:                 '<th align="left">'.$rowtitle.'</th>'.
 2754:                 '<td><select name="version">'.
 2755:                 '<option>'.&mt('Select').'</option>'.
 2756:                 $list.
 2757:                 '</select></td>'.
 2758:                 &Apache::loncommon::end_data_table_row();
 2759:             unless ($nomenu) {
 2760:                 $result .= &Apache::loncommon::start_data_table_row().
 2761:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2762:                 '<td><span class="LC_nobreak">'.
 2763:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2764:                 &mt('Yes').'</label>'.
 2765:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2766:                 '</span></td>'.
 2767:                 &Apache::loncommon::end_data_table_row();
 2768:             }
 2769:             $result .=
 2770:                 &Apache::loncommon::start_data_table_row().
 2771:                 '<th align="left">&nbsp;</th>'.
 2772:                 '<td>'.
 2773:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2774:                 '</td>'.
 2775:                 &Apache::loncommon::end_data_table_row().
 2776:                 &Apache::loncommon::end_data_table().
 2777:                 '</form>';
 2778:             $js = &previous_display_javascript($nomenu,$current);
 2779:         } elsif ($displayed && $nomenu) {
 2780:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2781:         } else {
 2782:             $result .= &mt('No previous versions to show for this student');
 2783:         }
 2784:         $result .= '</div>';
 2785:     }
 2786:     return ($current,$displayed,$result,$js);
 2787: }
 2788: 
 2789: sub previous_display_javascript {
 2790:     my ($nomenu,$current) = @_;
 2791:     my $js = <<"JSONE";
 2792: <script type="text/javascript">
 2793: // <![CDATA[
 2794: function previousVersion(uname,udom,symb) {
 2795:     var current = '$current';
 2796:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2797:     var prevstr = new RegExp("^\\\\d+\$");
 2798:     if (!prevstr.test(version)) {
 2799:         return false;
 2800:     }
 2801:     var url = '';
 2802:     if (version == current) {
 2803:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2804:     } else {
 2805:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2806:     }
 2807: JSONE
 2808:     if ($nomenu) {
 2809:         $js .= <<"JSTWO";
 2810:     document.location.href = url;
 2811: JSTWO
 2812:     } else {
 2813:         $js .= <<"JSTHREE";
 2814:     var newwin = 0;
 2815:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2816:         if (document.getprev.prevwin[i].checked == true) {
 2817:             newwin = document.getprev.prevwin[i].value;
 2818:         }
 2819:     }
 2820:     if (newwin == 1) {
 2821:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2822:         url = url+'&inhibitmenu=yes';
 2823:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2824:             previousWin = window.open(url,'',options,1);
 2825:         } else {
 2826:             previousWin.location.href = url;
 2827:         }
 2828:         previousWin.focus();
 2829:         return false;
 2830:     } else {
 2831:         document.location.href = url;
 2832:         return false;
 2833:     }
 2834: JSTHREE
 2835:     }
 2836:     $js .= <<"ENDJS";
 2837:     return false;
 2838: }
 2839: // ]]>
 2840: </script>
 2841: ENDJS
 2842: 
 2843: }
 2844: 
 2845: #--- Called from submission routine
 2846: sub processHandGrade {
 2847:     my ($request) = shift;
 2848:     my ($symb)   = &get_symb($request);
 2849:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2850:     my $button = $env{'form.gradeOpt'};
 2851:     my $ngrade = $env{'form.NCT'};
 2852:     my $ntstu  = $env{'form.NTSTU'};
 2853:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2854:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2855: 
 2856:     if ($button eq 'Save & Next') {
 2857: 	my $ctr = 0;
 2858: 	while ($ctr < $ngrade) {
 2859: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2860: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2861: 	    if ($errorflag eq 'no_score') {
 2862: 		$ctr++;
 2863: 		next;
 2864: 	    }
 2865: 	    if ($errorflag eq 'not_allowed') {
 2866:                 $request->print(
 2867:                     '<span class="LC_error">'
 2868:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2869:                    .'</span>');
 2870: 		$ctr++;
 2871: 		next;
 2872: 	    }
 2873: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2874: 	    my ($subject,$message,$msgstatus) = ('','','');
 2875: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2876:             my ($feedurl,$showsymb) =
 2877: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2878: 	    my $messagetail;
 2879: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2880: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2881: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2882: 		$subject.=' ['.$restitle.']';
 2883: 		my (@msgnum) = split(/,/,$includemsg);
 2884: 		foreach (@msgnum) {
 2885: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2886: 		}
 2887: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2888: 		if ($env{'form.withgrades'.$ctr}) {
 2889: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2890: 		    $messagetail = " for <a href=\"".
 2891: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2892: 		}
 2893: 		$msgstatus = 
 2894:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2895: 						     $message.$messagetail,
 2896:                                                      undef,$feedurl,undef,
 2897:                                                      undef,undef,$showsymb,
 2898:                                                      $restitle);
 2899: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2900: 				$msgstatus.'<br />');
 2901: 	    }
 2902: 	    if ($env{'form.collaborator'.$ctr}) {
 2903: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2904: 		foreach my $collabstr (@collabstrs) {
 2905: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2906: 		    foreach my $collaborator (@collaborators) {
 2907: 			my ($errorflag,$pts,$wgt) = 
 2908: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2909: 					   $env{'form.unamedom'.$ctr},$part);
 2910: 			if ($errorflag eq 'not_allowed') {
 2911: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2912: 			    next;
 2913: 			} elsif ($message ne '') {
 2914: 			    my ($baseurl,$showsymb) = 
 2915: 				&get_feedurl_and_symb($symb,$collaborator,
 2916: 						      $udom);
 2917: 			    if ($env{'form.withgrades'.$ctr}) {
 2918: 				$messagetail = " for <a href=\"".
 2919:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2920: 			    }
 2921: 			    $msgstatus = 
 2922: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2923: 			}
 2924: 		    }
 2925: 		}
 2926: 	    }
 2927: 	    $ctr++;
 2928: 	}
 2929:     }
 2930: 
 2931:     if ($env{'form.handgrade'} eq 'yes') {
 2932: 	# Keywords sorted in alphabatical order
 2933: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2934: 	my %keyhash = ();
 2935: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2936: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2937: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2938: 	$env{'form.keywords'} = join(' ',@keywords);
 2939: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2940: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2941: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2942: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2943: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2944: 
 2945: 	# message center - Order of message gets changed. Blank line is eliminated.
 2946: 	# New messages are saved in env for the next student.
 2947: 	# All messages are saved in nohist_handgrade.db
 2948: 	my ($ctr,$idx) = (1,1);
 2949: 	while ($ctr <= $env{'form.savemsgN'}) {
 2950: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2951: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2952: 		$idx++;
 2953: 	    }
 2954: 	    $ctr++;
 2955: 	}
 2956: 	$ctr = 0;
 2957: 	while ($ctr < $ngrade) {
 2958: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2959: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2960: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2961: 		$idx++;
 2962: 	    }
 2963: 	    $ctr++;
 2964: 	}
 2965: 	$env{'form.savemsgN'} = --$idx;
 2966: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2967: 	my $putresult = &Apache::lonnet::put
 2968: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2969:     }
 2970:     # Called by Save & Refresh from Highlight Attribute Window
 2971:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2972:     if ($env{'form.refresh'} eq 'on') {
 2973: 	my ($ctr,$total) = (0,0);
 2974: 	while ($ctr < $ngrade) {
 2975: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2976: 	    $ctr++;
 2977: 	}
 2978: 	$env{'form.NTSTU'}=$ngrade;
 2979: 	$ctr = 0;
 2980: 	while ($ctr < $total) {
 2981: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2982: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2983: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2984: 	    &submission($request,$ctr,$total-1);
 2985: 	    $ctr++;
 2986: 	}
 2987: 	return '';
 2988:     }
 2989: 
 2990: # Go directly to grade student - from submission or link from chart page
 2991:     if ($button eq 'Grade Student') {
 2992: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2993: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2994: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2995: 	$env{'form.fullname'} = $$fullname{$processUser};
 2996: 	&submission($request,0,0);
 2997: 	return '';
 2998:     }
 2999: 
 3000:     # Get the next/previous one or group of students
 3001:     my $firststu = $env{'form.unamedom0'};
 3002:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3003:     my $ctr = 2;
 3004:     while ($laststu eq '') {
 3005: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3006: 	$ctr++;
 3007: 	$laststu = $firststu if ($ctr > $ngrade);
 3008:     }
 3009: 
 3010:     my (@parsedlist,@nextlist);
 3011:     my ($nextflg) = 0;
 3012:     foreach my $item (sort 
 3013: 	     {
 3014: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3015: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3016: 		 }
 3017: 		 return $a cmp $b;
 3018: 	     } (keys(%$fullname))) {
 3019: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3020: 	    push(@parsedlist,$item);
 3021: 	}
 3022: 	$nextflg = 1 if ($item eq $laststu);
 3023: 	if ($button eq 'Previous') {
 3024: 	    last if ($item eq $firststu);
 3025: 	    push(@parsedlist,$item);
 3026: 	}
 3027:     }
 3028:     $ctr = 0;
 3029:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3030:     my $res_error;
 3031:     my ($partlist) = &response_type($symb,\$res_error);
 3032:     if ($res_error) {
 3033:         $request->print(&navmap_errormsg());
 3034:         return;
 3035:     }
 3036:     foreach my $student (@parsedlist) {
 3037: 	my $submitonly=$env{'form.submitonly'};
 3038: 	my ($uname,$udom) = split(/:/,$student);
 3039: 	
 3040: 	if ($submitonly eq 'queued') {
 3041: 	    my %queue_status = 
 3042: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3043: 							$udom,$uname);
 3044: 	    next if (!defined($queue_status{'gradingqueue'}));
 3045: 	}
 3046: 
 3047: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3048: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3049: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3050: 	    my $submitted = 0;
 3051: 	    my $ungraded = 0;
 3052: 	    my $incorrect = 0;
 3053: 	    foreach my $item (keys(%status)) {
 3054: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3055: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3056: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3057: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3058: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3059: 		    $submitted = 0;
 3060: 		}
 3061: 	    }
 3062: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3063: 				     $submitonly eq 'incorrect' ||
 3064: 				     $submitonly eq 'graded'));
 3065: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3066: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3067: 	}
 3068: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3069: 	last if ($ctr == $ntstu);
 3070: 	$ctr++;
 3071:     }
 3072: 
 3073:     $ctr = 0;
 3074:     my $total = scalar(@nextlist)-1;
 3075: 
 3076:     foreach (sort(@nextlist)) {
 3077: 	my ($uname,$udom,$submitter) = split(/:/);
 3078: 	$env{'form.student'}  = $uname;
 3079: 	$env{'form.userdom'}  = $udom;
 3080: 	$env{'form.fullname'} = $$fullname{$_};
 3081: 	&submission($request,$ctr,$total);
 3082: 	$ctr++;
 3083:     }
 3084:     if ($total < 0) {
 3085: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3086: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3087: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3088: 	$the_end.=&show_grading_menu_form($symb);
 3089: 	$request->print($the_end);
 3090:     }
 3091:     return '';
 3092: }
 3093: 
 3094: #---- Save the score and award for each student, if changed
 3095: sub saveHandGrade {
 3096:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3097:     my @version_parts;
 3098:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3099: 					   $env{'request.course.id'});
 3100:     if (!&canmodify($usec)) { return('not_allowed'); }
 3101:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3102:     my @parts_graded;
 3103:     my %newrecord  = ();
 3104:     my ($pts,$wgt) = ('','');
 3105:     my %aggregate = ();
 3106:     my $aggregateflag = 0;
 3107:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3108:     foreach my $new_part (@parts) {
 3109: 	#collaborator ($submi may vary for different parts
 3110: 	if ($submitter && $new_part ne $part) { next; }
 3111: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3112: 	if ($dropMenu eq 'excused') {
 3113: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3114: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3115: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3116: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3117: 		}
 3118: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3119: 	    }
 3120: 	} elsif ($dropMenu eq 'reset status'
 3121: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3122: 	    foreach my $key (keys(%record)) {
 3123: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3124: 	    }
 3125: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3126: 		"$env{'user.name'}:$env{'user.domain'}";
 3127:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3128: 
 3129:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3130: 					       [$new_part]);
 3131:             my $aggtries =$totaltries;
 3132:             if ($last_resets{$new_part}) {
 3133:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3134: 					   $new_part);
 3135:             }
 3136: 
 3137:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3138:             if ($aggtries > 0) {
 3139:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3140:                 $aggregateflag = 1;
 3141:             }
 3142: 	} elsif ($dropMenu eq '') {
 3143: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3144: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3145: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3146: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3147: 		next;
 3148: 	    }
 3149: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3150: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3151: 	    my $partial= $pts/$wgt;
 3152: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3153: 		#do not update score for part if not changed.
 3154:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3155: 		next;
 3156: 	    } else {
 3157: 	        push(@parts_graded,$new_part);
 3158: 	    }
 3159: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3160: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3161: 	    }
 3162: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3163: 	    if ($partial == 0) {
 3164: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3165: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3166: 		}
 3167: 	    } else {
 3168: 		if ($record{$reckey} ne 'correct_by_override') {
 3169: 		    $newrecord{$reckey} = 'correct_by_override';
 3170: 		}
 3171: 	    }	    
 3172: 	    if ($submitter && 
 3173: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3174: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3175: 	    }
 3176: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3177: 		"$env{'user.name'}:$env{'user.domain'}";
 3178: 	}
 3179: 	# unless problem has been graded, set flag to version the submitted files
 3180: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3181: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3182: 	        $dropMenu eq 'reset status')
 3183: 	   {
 3184: 	    push(@version_parts,$new_part);
 3185: 	}
 3186:     }
 3187:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3188:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3189: 
 3190:     if (%newrecord) {
 3191:         if (@version_parts) {
 3192:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3193:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3194: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3195: 	    foreach my $new_part (@version_parts) {
 3196: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3197: 				$new_part,\%newrecord);
 3198: 	    }
 3199:         }
 3200: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3201: 				$env{'request.course.id'},$domain,$stuname);
 3202: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3203: 				     $cdom,$cnum,$domain,$stuname);
 3204:     }
 3205:     if ($aggregateflag) {
 3206:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3207: 			      $cdom,$cnum);
 3208:     }
 3209:     return ('',$pts,$wgt);
 3210: }
 3211: 
 3212: sub check_and_remove_from_queue {
 3213:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3214:     my @ungraded_parts;
 3215:     foreach my $part (@{$parts}) {
 3216: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3217: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3218: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3219: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3220: 		) {
 3221: 	    push(@ungraded_parts, $part);
 3222: 	}
 3223:     }
 3224:     if ( !@ungraded_parts ) {
 3225: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3226: 					       $cnum,$domain,$stuname);
 3227:     }
 3228: }
 3229: 
 3230: sub handback_files {
 3231:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3232:     my $portfolio_root = '/userfiles/portfolio';
 3233:     my $res_error;
 3234:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3235:     if ($res_error) {
 3236:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3237:         return;
 3238:     }
 3239:     my @handedback;
 3240:     my $file_msg;
 3241:     my @part_response_id = &flatten_responseType($responseType);
 3242:     foreach my $part_response_id (@part_response_id) {
 3243:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3244: 	my $part_resp = join('_',@{ $part_response_id });
 3245:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3246:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3247:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3248: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3249:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3250:                     my ($directory,$answer_file) = 
 3251:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3252:                     my ($answer_name,$answer_ver,$answer_ext) =
 3253: 		        &file_name_version_ext($answer_file);
 3254: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3255:                     my $getpropath = 1;
 3256:                     my ($dir_list,$listerror) =
 3257:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3258:                                                  $domain,$stuname,$getpropath);
 3259: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3260:                     # fix filename
 3261:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3262:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3263:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3264:             	                                $save_file_name);
 3265:                     if ($result !~ m|^/uploaded/|) {
 3266:                         $request->print('<br /><span class="LC_error">'.
 3267:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3268:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3269:                                         '</span>');
 3270:                     } else {
 3271:                         # mark the file as read only
 3272:                         push(@handedback,$save_file_name);
 3273: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3274: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3275: 			}
 3276:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3277: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3278: 
 3279:                     }
 3280:                     $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>'));
 3281:                 }
 3282:             }
 3283:         }
 3284:     }
 3285:     if (@handedback > 0) {
 3286:         $request->print('<br />');
 3287:         my @what = ($symb,$env{'request.course.id'},'handback');
 3288:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3289:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3290:         my ($subject,$message);
 3291:         if (scalar(@handedback) == 1) {
 3292:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3293:         } else {
 3294:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3295:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3296:         }
 3297:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3298:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3299:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3300:         my ($feedurl,$showsymb) =
 3301:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3302:         my $restitle = &Apache::lonnet::gettitle($symb);
 3303:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3304:         my $msgstatus =
 3305:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3306:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3307:                  $restitle);
 3308:         if ($msgstatus) {
 3309:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3310:         }
 3311:     }
 3312:     return;
 3313: }
 3314: 
 3315: sub get_feedurl_and_symb {
 3316:     my ($symb,$uname,$udom) = @_;
 3317:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3318:     $url = &Apache::lonnet::clutter($url);
 3319:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3320: 					$symb,$udom,$uname);
 3321:     if ($encrypturl =~ /^yes$/i) {
 3322: 	&Apache::lonenc::encrypted(\$url,1);
 3323: 	&Apache::lonenc::encrypted(\$symb,1);
 3324:     }
 3325:     return ($url,$symb);
 3326: }
 3327: 
 3328: sub get_submitted_files {
 3329:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3330:     my @files;
 3331:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3332:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3333:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3334:     	    push(@files,$file_url.$file);
 3335:         }
 3336:     }
 3337:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3338:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3339:     }
 3340:     return (\@files);
 3341: }
 3342: 
 3343: # ----------- Provides number of tries since last reset.
 3344: sub get_num_tries {
 3345:     my ($record,$last_reset,$part) = @_;
 3346:     my $timestamp = '';
 3347:     my $num_tries = 0;
 3348:     if ($$record{'version'}) {
 3349:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3350:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3351:                 $timestamp = $$record{$version.':timestamp'};
 3352:                 if ($timestamp > $last_reset) {
 3353:                     $num_tries ++;
 3354:                 } else {
 3355:                     last;
 3356:                 }
 3357:             }
 3358:         }
 3359:     }
 3360:     return $num_tries;
 3361: }
 3362: 
 3363: # ----------- Determine decrements required in aggregate totals 
 3364: sub decrement_aggs {
 3365:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3366:     my %decrement = (
 3367:                         attempts => 0,
 3368:                         users => 0,
 3369:                         correct => 0
 3370:                     );
 3371:     $decrement{'attempts'} = $aggtries;
 3372:     if ($solvedstatus =~ /^correct/) {
 3373:         $decrement{'correct'} = 1;
 3374:     }
 3375:     if ($aggtries == $totaltries) {
 3376:         $decrement{'users'} = 1;
 3377:     }
 3378:     foreach my $type (keys(%decrement)) {
 3379:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3380:     }
 3381:     return;
 3382: }
 3383: 
 3384: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3385: sub get_last_resets {
 3386:     my ($symb,$courseid,$partids) =@_;
 3387:     my %last_resets;
 3388:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3389:     my $cname = $env{'course.'.$courseid.'.num'};
 3390:     my @keys;
 3391:     foreach my $part (@{$partids}) {
 3392: 	push(@keys,"$symb\0$part\0resettime");
 3393:     }
 3394:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3395: 				     $cdom,$cname);
 3396:     foreach my $part (@{$partids}) {
 3397: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3398:     }
 3399:     return %last_resets;
 3400: }
 3401: 
 3402: # ----------- Handles creating versions for portfolio files as answers
 3403: sub version_portfiles {
 3404:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3405:     my $version_parts = join('|',@$v_flag);
 3406:     my @returned_keys;
 3407:     my $parts = join('|', @$parts_graded);
 3408:     my $portfolio_root = '/userfiles/portfolio';
 3409:     foreach my $key (keys(%$record)) {
 3410:         my $new_portfiles;
 3411:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3412:             my @versioned_portfiles;
 3413:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3414:             foreach my $file (@portfiles) {
 3415:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3416:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3417: 		my ($answer_name,$answer_ver,$answer_ext) =
 3418: 		    &file_name_version_ext($answer_file);
 3419:                 my $getpropath = 1;
 3420:                 my ($dir_list,$listerror) =
 3421:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3422:                                              $stu_name,$getpropath);
 3423:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3424:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3425:                 if ($new_answer ne 'problem getting file') {
 3426:                     push(@versioned_portfiles, $directory.$new_answer);
 3427:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3428:                         [$directory.$new_answer],
 3429:                         [$symb,$env{'request.course.id'},'graded']);
 3430:                 }
 3431:             }
 3432:             $$record{$key} = join(',',@versioned_portfiles);
 3433:             push(@returned_keys,$key);
 3434:         }
 3435:     } 
 3436:     return (@returned_keys);   
 3437: }
 3438: 
 3439: sub get_next_version {
 3440:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3441:     my $version;
 3442:     if (ref($dir_list) eq 'ARRAY') {
 3443:         foreach my $row (@{$dir_list}) {
 3444:             my ($file) = split(/\&/,$row,2);
 3445:             my ($file_name,$file_version,$file_ext) =
 3446: 	        &file_name_version_ext($file);
 3447:             if (($file_name eq $answer_name) && 
 3448: 	        ($file_ext eq $answer_ext)) {
 3449:                 # gets here if filename and extension match, 
 3450:                 # regardless of version
 3451:                 if ($file_version ne '') {
 3452:                     # a versioned file is found  so save it for later
 3453:                     if ($file_version > $version) {
 3454: 		        $version = $file_version;
 3455:                     }
 3456: 	        }
 3457:             }
 3458:         }
 3459:     }
 3460:     $version ++;
 3461:     return($version);
 3462: }
 3463: 
 3464: sub version_selected_portfile {
 3465:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3466:     my ($answer_name,$answer_ver,$answer_ext) =
 3467:         &file_name_version_ext($file_name);
 3468:     my $new_answer;
 3469:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3470:     if($env{'form.copy'} eq '-1') {
 3471:         $new_answer = 'problem getting file';
 3472:     } else {
 3473:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3474:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3475:                             $stu_name,$domain,'copy',
 3476: 		        '/portfolio'.$directory.$new_answer);
 3477:     }    
 3478:     return ($new_answer);
 3479: }
 3480: 
 3481: sub file_name_version_ext {
 3482:     my ($file)=@_;
 3483:     my @file_parts = split(/\./, $file);
 3484:     my ($name,$version,$ext);
 3485:     if (@file_parts > 1) {
 3486: 	$ext=pop(@file_parts);
 3487: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3488: 	    $version=pop(@file_parts);
 3489: 	}
 3490: 	$name=join('.',@file_parts);
 3491:     } else {
 3492: 	$name=join('.',@file_parts);
 3493:     }
 3494:     return($name,$version,$ext);
 3495: }
 3496: 
 3497: #--------------------------------------------------------------------------------------
 3498: #
 3499: #-------------------------- Next few routines handles grading by section or whole class
 3500: #
 3501: #--- Javascript to handle grading by section or whole class
 3502: sub viewgrades_js {
 3503:     my ($request) = shift;
 3504: 
 3505:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3506:     $request->print(<<VIEWJAVASCRIPT);
 3507: <script type="text/javascript" language="javascript">
 3508:    function writePoint(partid,weight,point) {
 3509: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3510: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3511: 	if (point == "textval") {
 3512: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3513: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3514: 		alert("$alertmsg"+parseFloat(point));
 3515: 		var resetbox = false;
 3516: 		for (var i=0; i<radioButton.length; i++) {
 3517: 		    if (radioButton[i].checked) {
 3518: 			textbox.value = i;
 3519: 			resetbox = true;
 3520: 		    }
 3521: 		}
 3522: 		if (!resetbox) {
 3523: 		    textbox.value = "";
 3524: 		}
 3525: 		return;
 3526: 	    }
 3527: 	    if (parseFloat(point) > parseFloat(weight)) {
 3528: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3529: 				   ") greater than the weight for the part. Accept?");
 3530: 		if (resp == false) {
 3531: 		    textbox.value = "";
 3532: 		    return;
 3533: 		}
 3534: 	    }
 3535: 	    for (var i=0; i<radioButton.length; i++) {
 3536: 		radioButton[i].checked=false;
 3537: 		if (parseFloat(point) == i) {
 3538: 		    radioButton[i].checked=true;
 3539: 		}
 3540: 	    }
 3541: 
 3542: 	} else {
 3543: 	    textbox.value = parseFloat(point);
 3544: 	}
 3545: 	for (i=0;i<document.classgrade.total.value;i++) {
 3546: 	    var user = document.classgrade["ctr"+i].value;
 3547: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3548: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3549: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3550: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3551: 	    if (saveval != "correct") {
 3552: 		scorename.value = point;
 3553: 		if (selname[0].selected != true) {
 3554: 		    selname[0].selected = true;
 3555: 		}
 3556: 	    }
 3557: 	}
 3558: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3559:     }
 3560: 
 3561:     function writeRadText(partid,weight) {
 3562: 	var selval   = document.classgrade["SELVAL_"+partid];
 3563: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3564:         var override = document.classgrade["FORCE_"+partid].checked;
 3565: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3566: 	if (selval[1].selected || selval[2].selected) {
 3567: 	    for (var i=0; i<radioButton.length; i++) {
 3568: 		radioButton[i].checked=false;
 3569: 
 3570: 	    }
 3571: 	    textbox.value = "";
 3572: 
 3573: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3574: 		var user = document.classgrade["ctr"+i].value;
 3575: 		user = user.replace(new RegExp(':', 'g'),"_");
 3576: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3577: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3578: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3579: 		if ((saveval != "correct") || override) {
 3580: 		    scorename.value = "";
 3581: 		    if (selval[1].selected) {
 3582: 			selname[1].selected = true;
 3583: 		    } else {
 3584: 			selname[2].selected = true;
 3585: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3586: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3587: 		    }
 3588: 		}
 3589: 	    }
 3590: 	} else {
 3591: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3592: 		var user = document.classgrade["ctr"+i].value;
 3593: 		user = user.replace(new RegExp(':', 'g'),"_");
 3594: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3595: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3596: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3597: 		if ((saveval != "correct") || override) {
 3598: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3599: 		    selname[0].selected = true;
 3600: 		}
 3601: 	    }
 3602: 	}	    
 3603:     }
 3604: 
 3605:     function changeSelect(partid,user) {
 3606: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3607: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3608: 	var point  = textbox.value;
 3609: 	var weight = document.classgrade["weight_"+partid].value;
 3610: 
 3611: 	if (isNaN(point) || parseFloat(point) < 0) {
 3612: 	    alert("$alertmsg"+parseFloat(point));
 3613: 	    textbox.value = "";
 3614: 	    return;
 3615: 	}
 3616: 	if (parseFloat(point) > parseFloat(weight)) {
 3617: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3618: 			       ") greater than the weight of the part. Accept?");
 3619: 	    if (resp == false) {
 3620: 		textbox.value = "";
 3621: 		return;
 3622: 	    }
 3623: 	}
 3624: 	selval[0].selected = true;
 3625:     }
 3626: 
 3627:     function changeOneScore(partid,user) {
 3628: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3629: 	if (selval[1].selected || selval[2].selected) {
 3630: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3631: 	    if (selval[2].selected) {
 3632: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3633: 	    }
 3634:         }
 3635:     }
 3636: 
 3637:     function resetEntry(numpart) {
 3638: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3639: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3640: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3641: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3642: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3643: 	    for (var i=0; i<radioButton.length; i++) {
 3644: 		radioButton[i].checked=false;
 3645: 
 3646: 	    }
 3647: 	    textbox.value = "";
 3648: 	    selval[0].selected = true;
 3649: 
 3650: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3651: 		var user = document.classgrade["ctr"+i].value;
 3652: 		user = user.replace(new RegExp(':', 'g'),"_");
 3653: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3654: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3655: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3656: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3657: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3658: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3659: 		if (saveselval == "excused") {
 3660: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3661: 		} else {
 3662: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3663: 		}
 3664: 	    }
 3665: 	}
 3666:     }
 3667: 
 3668: </script>
 3669: VIEWJAVASCRIPT
 3670: }
 3671: 
 3672: #--- show scores for a section or whole class w/ option to change/update a score
 3673: sub viewgrades {
 3674:     my ($request) = shift;
 3675:     &viewgrades_js($request);
 3676: 
 3677:     my ($symb) = &get_symb($request);
 3678:     #need to make sure we have the correct data for later EXT calls, 
 3679:     #thus invalidate the cache
 3680:     &Apache::lonnet::devalidatecourseresdata(
 3681:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3682:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3683:     &Apache::lonnet::clear_EXT_cache_status();
 3684: 
 3685:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3686:     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3687: 
 3688:     #view individual student submission form - called using Javascript viewOneStudent
 3689:     $result.=&jscriptNform($symb);
 3690: 
 3691:     #beginning of class grading form
 3692:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3693:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3694: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3695: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3696: 	&build_section_inputs().
 3697: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3698: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3699: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3700: 
 3701:     my ($common_header,$specific_header);
 3702:     if ($env{'form.section'} eq 'all') {
 3703: 	$common_header = &mt('Assign Common Grade to Class');
 3704:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3705:     } elsif ($env{'form.section'} eq 'none') {
 3706:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3707: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3708:     } else {
 3709:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3710:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3711: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3712:     }
 3713:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3714:     #radio buttons/text box for assigning points for a section or class.
 3715:     #handles different parts of a problem
 3716:     my $res_error;
 3717:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3718:     if ($res_error) {
 3719:         return &navmap_errormsg();
 3720:     }
 3721:     my %weight = ();
 3722:     my $ctsparts = 0;
 3723:     my %seen = ();
 3724:     my @part_response_id = &flatten_responseType($responseType);
 3725:     foreach my $part_response_id (@part_response_id) {
 3726:     	my ($partid,$respid) = @{ $part_response_id };
 3727: 	my $part_resp = join('_',@{ $part_response_id });
 3728: 	next if $seen{$partid};
 3729: 	$seen{$partid}++;
 3730: 	my $handgrade=$$handgrade{$part_resp};
 3731: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3732: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3733: 
 3734: 	my $display_part=&get_display_part($partid,$symb);
 3735: 	my $radio.='<table border="0"><tr>';  
 3736: 	my $ctr = 0;
 3737: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3738: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3739: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3740: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3741: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3742: 	    $ctr++;
 3743: 	}
 3744: 	$radio.='</tr></table>';
 3745: 	my $line = '<input type="text" name="TEXTVAL_'.
 3746: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3747: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3748: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3749: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3750:                 '<select name="SELVAL_'.$partid.'" '.
 3751: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 3752: 		$weight{$partid}.')"> '.
 3753: 	    '<option selected="selected"> </option>'.
 3754: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3755: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3756: 	    '</select></td>'.
 3757:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3758: 	$line.='<input type="hidden" name="partid_'.
 3759: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3760: 	$line.='<input type="hidden" name="weight_'.
 3761: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3762: 
 3763: 	$result.=
 3764: 	    &Apache::loncommon::start_data_table_row()."\n".
 3765: 	    '<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>'.
 3766: 	    &Apache::loncommon::end_data_table_row()."\n";
 3767: 	$ctsparts++;
 3768:     }
 3769:     $result.=&Apache::loncommon::end_data_table()."\n".
 3770: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3771:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3772: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3773: 
 3774:     #table listing all the students in a section/class
 3775:     #header of table
 3776:     $result.= '<h3>'.$specific_header.'</h3>'.
 3777:               &Apache::loncommon::start_data_table().
 3778: 	      &Apache::loncommon::start_data_table_header_row().
 3779: 	      '<th>'.&mt('No.').'</th>'.
 3780: 	      '<th>'.&nameUserString('header')."</th>\n";
 3781:     my $partserror;
 3782:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3783:     if ($partserror) {
 3784:         return &navmap_errormsg();
 3785:     }
 3786:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3787:     my @partids = ();
 3788:     foreach my $part (@parts) {
 3789: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3790:         my $narrowtext = &mt('Tries');
 3791: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3792: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3793: 	my ($partid) = &split_part_type($part);
 3794:         push(@partids,$partid);
 3795: 	my $display_part=&get_display_part($partid,$symb);
 3796: 	if ($display =~ /^Partial Credit Factor/) {
 3797: 	    $result.='<th>'.
 3798:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3799:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3800: 	    next;
 3801: 	    
 3802: 	} else {
 3803: 	    if ($display =~ /Problem Status/) {
 3804: 		my $grade_status_mt = &mt('Grade Status');
 3805: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3806: 	    }
 3807: 	    my $part_mt = &mt('Part:');
 3808: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3809: 	}
 3810: 
 3811: 	$result.='<th>'.$display.'</th>'."\n";
 3812:     }
 3813:     $result.=&Apache::loncommon::end_data_table_header_row();
 3814: 
 3815:     my %last_resets = 
 3816: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3817: 
 3818:     #get info for each student
 3819:     #list all the students - with points and grade status
 3820:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3821:     my $ctr = 0;
 3822:     foreach (sort 
 3823: 	     {
 3824: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3825: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3826: 		 }
 3827: 		 return $a cmp $b;
 3828: 	     } (keys(%$fullname))) {
 3829: 	$ctr++;
 3830: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3831: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3832:     }
 3833:     $result.=&Apache::loncommon::end_data_table();
 3834:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3835:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3836: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3837:     if (scalar(%$fullname) eq 0) {
 3838: 	my $colspan=3+scalar(@parts);
 3839: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3840:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3841: 	$result='<span class="LC_warning">'.
 3842: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3843: 	        $section_display, $stu_status).
 3844: 	    '</span>';
 3845:     }
 3846:     $result.=&show_grading_menu_form($symb);
 3847:     return $result;
 3848: }
 3849: 
 3850: #--- call by previous routine to display each student
 3851: sub viewstudentgrade {
 3852:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3853:     my ($uname,$udom) = split(/:/,$student);
 3854:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3855:     my %aggregates = (); 
 3856:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3857: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3858: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3859: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3860: 	'\');" target="_self">'.$fullname.'</a> '.
 3861: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3862:     $student=~s/:/_/; # colon doen't work in javascript for names
 3863:     foreach my $apart (@$parts) {
 3864: 	my ($part,$type) = &split_part_type($apart);
 3865: 	my $score=$record{"resource.$part.$type"};
 3866:         $result.='<td align="center">';
 3867:         my ($aggtries,$totaltries);
 3868:         unless (exists($aggregates{$part})) {
 3869: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3870: 
 3871: 	    $aggtries = $totaltries;
 3872:             if ($$last_resets{$part}) {  
 3873:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3874: 					   $part);
 3875:             }
 3876:             $result.='<input type="hidden" name="'.
 3877:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3878:             $result.='<input type="hidden" name="'.
 3879:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3880:             $aggregates{$part} = 1;
 3881:         }
 3882: 	if ($type eq 'awarded') {
 3883: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3884: 	    $result.='<input type="hidden" name="'.
 3885: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3886: 	    $result.='<input type="text" name="'.
 3887: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3888:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3889: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3890: 	} elsif ($type eq 'solved') {
 3891: 	    my ($status,$foo)=split(/_/,$score,2);
 3892: 	    $status = 'nothing' if ($status eq '');
 3893: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3894: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3895: 	    $result.='&nbsp;<select name="'.
 3896: 		'GD_'.$student.'_'.$part.'_solved" '.
 3897:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3898: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3899: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3900: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3901: 	    $result.="</select>&nbsp;</td>\n";
 3902: 	} else {
 3903: 	    $result.='<input type="hidden" name="'.
 3904: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3905: 		    "\n";
 3906: 	    $result.='<input type="text" name="'.
 3907: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3908: 		'value="'.$score.'" size="4" /></td>'."\n";
 3909: 	}
 3910:     }
 3911:     $result.=&Apache::loncommon::end_data_table_row();
 3912:     return $result;
 3913: }
 3914: 
 3915: #--- change scores for all the students in a section/class
 3916: #    record does not get update if unchanged
 3917: sub editgrades {
 3918:     my ($request) = @_;
 3919: 
 3920:     my ($symb)=&get_symb($request);
 3921:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3922:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3923:     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3924:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 3925: 
 3926:     my $result= &Apache::loncommon::start_data_table().
 3927: 	&Apache::loncommon::start_data_table_header_row().
 3928: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3929: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3930:     my %scoreptr = (
 3931: 		    'correct'  =>'correct_by_override',
 3932: 		    'incorrect'=>'incorrect_by_override',
 3933: 		    'excused'  =>'excused',
 3934: 		    'ungraded' =>'ungraded_attempted',
 3935:                     'credited' =>'credit_attempted',
 3936: 		    'nothing'  => '',
 3937: 		    );
 3938:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3939: 
 3940:     my (@partid);
 3941:     my %weight = ();
 3942:     my %columns = ();
 3943:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3944: 
 3945:     my $partserror;
 3946:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3947:     if ($partserror) {
 3948:         return &navmap_errormsg();
 3949:     }
 3950:     my $header;
 3951:     while ($ctr < $env{'form.totalparts'}) {
 3952: 	my $partid = $env{'form.partid_'.$ctr};
 3953: 	push(@partid,$partid);
 3954: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3955: 	$ctr++;
 3956:     }
 3957:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3958:     foreach my $partid (@partid) {
 3959: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3960: 	    '<th align="center">'.&mt('New Score').'</th>';
 3961: 	$columns{$partid}=2;
 3962: 	foreach my $stores (@parts) {
 3963: 	    my ($part,$type) = &split_part_type($stores);
 3964: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3965: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3966: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3967: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3968:             my $narrowtext = &mt('Tries');
 3969: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3970: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3971: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3972: 	    $columns{$partid}+=2;
 3973: 	}
 3974:     }
 3975:     foreach my $partid (@partid) {
 3976: 	my $display_part=&get_display_part($partid,$symb);
 3977: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3978: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3979: 	    '</th>';
 3980: 
 3981:     }
 3982:     $result .= &Apache::loncommon::end_data_table_header_row().
 3983: 	&Apache::loncommon::start_data_table_header_row().
 3984: 	$header.
 3985: 	&Apache::loncommon::end_data_table_header_row();
 3986:     my @noupdate;
 3987:     my ($updateCtr,$noupdateCtr) = (1,1);
 3988:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3989: 	my $line;
 3990: 	my $user = $env{'form.ctr'.$i};
 3991: 	my ($uname,$udom)=split(/:/,$user);
 3992: 	my %newrecord;
 3993: 	my $updateflag = 0;
 3994: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3995: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3996: 	if (!&canmodify($usec)) {
 3997: 	    my $numcols=scalar(@partid)*4+2;
 3998: 	    push(@noupdate,
 3999: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 4000: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 4001: 	    next;
 4002: 	}
 4003:         my %aggregate = ();
 4004:         my $aggregateflag = 0;
 4005: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4006: 	foreach (@partid) {
 4007: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4008: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4009: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4010: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4011: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4012: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4013: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4014: 	    my $score;
 4015: 	    if ($partial eq '') {
 4016: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4017: 	    } elsif ($partial > 0) {
 4018: 		$score = 'correct_by_override';
 4019: 	    } elsif ($partial == 0) {
 4020: 		$score = 'incorrect_by_override';
 4021: 	    }
 4022: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4023: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4024: 
 4025: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4026: 		"$env{'user.name'}:$env{'user.domain'}";
 4027: 	    if ($dropMenu eq 'reset status' &&
 4028: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4029: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4030: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4031: 		$newrecord{'resource.'.$_.'.award'} = '';
 4032: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4033: 		$updateflag = 1;
 4034:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4035:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4036:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4037:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4038:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4039:                     $aggregateflag = 1;
 4040:                 }
 4041: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4042: 		$updateflag = 1;
 4043: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4044: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4045: 		$rec_update++;
 4046: 	    }
 4047: 
 4048: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4049: 		'<td align="center">'.$awarded.
 4050: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4051: 
 4052: 
 4053: 	    my $partid=$_;
 4054: 	    foreach my $stores (@parts) {
 4055: 		my ($part,$type) = &split_part_type($stores);
 4056: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4057: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4058: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4059: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4060: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4061: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4062: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4063: 		    $updateflag=1;
 4064: 		}
 4065: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4066: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4067: 	    }
 4068: 	}
 4069: 	$line.="\n";
 4070: 
 4071: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4072: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4073: 
 4074: 	if ($updateflag) {
 4075: 	    $count++;
 4076: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4077: 				    $udom,$uname);
 4078: 
 4079: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4080: 					      $cnum,$udom,$uname)) {
 4081: 		# need to figure out if should be in queue.
 4082: 		my %record =  
 4083: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4084: 					     $udom,$uname);
 4085: 		my $all_graded = 1;
 4086: 		my $none_graded = 1;
 4087: 		foreach my $part (@parts) {
 4088: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4089: 			$all_graded = 0;
 4090: 		    } else {
 4091: 			$none_graded = 0;
 4092: 		    }
 4093: 		}
 4094: 
 4095: 		if ($all_graded || $none_graded) {
 4096: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4097: 							   $symb,$cdom,$cnum,
 4098: 							   $udom,$uname);
 4099: 		}
 4100: 	    }
 4101: 
 4102: 	    $result.=&Apache::loncommon::start_data_table_row().
 4103: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4104: 		&Apache::loncommon::end_data_table_row();
 4105: 	    $updateCtr++;
 4106: 	} else {
 4107: 	    push(@noupdate,
 4108: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4109: 	    $noupdateCtr++;
 4110: 	}
 4111:         if ($aggregateflag) {
 4112:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4113: 				  $cdom,$cnum);
 4114:         }
 4115:     }
 4116:     if (@noupdate) {
 4117: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4118: 	my $numcols=scalar(@partid)*4+2;
 4119: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4120: 	    '<td align="center" colspan="'.$numcols.'">'.
 4121: 	    &mt('No Changes Occurred For the Students Below').
 4122: 	    '</td>'.
 4123: 	    &Apache::loncommon::end_data_table_row();
 4124: 	foreach my $line (@noupdate) {
 4125: 	    $result.=
 4126: 		&Apache::loncommon::start_data_table_row().
 4127: 		$line.
 4128: 		&Apache::loncommon::end_data_table_row();
 4129: 	}
 4130:     }
 4131:     $result .= &Apache::loncommon::end_data_table().
 4132: 	&show_grading_menu_form($symb);
 4133:     my $msg = '<p><b>'.
 4134: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4135: 	    $rec_update,$count).'</b><br />'.
 4136: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4137: 	'</b></p>';
 4138:     return $title.$msg.$result;
 4139: }
 4140: 
 4141: sub split_part_type {
 4142:     my ($partstr) = @_;
 4143:     my ($temp,@allparts)=split(/_/,$partstr);
 4144:     my $type=pop(@allparts);
 4145:     my $part=join('_',@allparts);
 4146:     return ($part,$type);
 4147: }
 4148: 
 4149: #------------- end of section for handling grading by section/class ---------
 4150: #
 4151: #----------------------------------------------------------------------------
 4152: 
 4153: 
 4154: #----------------------------------------------------------------------------
 4155: #
 4156: #-------------------------- Next few routines handles grading by csv upload
 4157: #
 4158: #--- Javascript to handle csv upload
 4159: sub csvupload_javascript_reverse_associate {
 4160:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4161:     my $error2=&mt('You need to specify at least one grading field');
 4162:   return(<<ENDPICK);
 4163:   function verify(vf) {
 4164:     var foundsomething=0;
 4165:     var founduname=0;
 4166:     var foundID=0;
 4167:     for (i=0;i<=vf.nfields.value;i++) {
 4168:       tw=eval('vf.f'+i+'.selectedIndex');
 4169:       if (i==0 && tw!=0) { foundID=1; }
 4170:       if (i==1 && tw!=0) { founduname=1; }
 4171:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4172:     }
 4173:     if (founduname==0 && foundID==0) {
 4174: 	alert('$error1');
 4175: 	return;
 4176:     }
 4177:     if (foundsomething==0) {
 4178: 	alert('$error2');
 4179: 	return;
 4180:     }
 4181:     vf.submit();
 4182:   }
 4183:   function flip(vf,tf) {
 4184:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4185:     var i;
 4186:     for (i=0;i<=vf.nfields.value;i++) {
 4187:       //can not pick the same destination field for both name and domain
 4188:       if (((i ==0)||(i ==1)) && 
 4189:           ((tf==0)||(tf==1)) && 
 4190:           (i!=tf) &&
 4191:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4192:         eval('vf.f'+i+'.selectedIndex=0;')
 4193:       }
 4194:     }
 4195:   }
 4196: ENDPICK
 4197: }
 4198: 
 4199: sub csvupload_javascript_forward_associate {
 4200:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4201:     my $error2=&mt('You need to specify at least one grading field');
 4202:   return(<<ENDPICK);
 4203:   function verify(vf) {
 4204:     var foundsomething=0;
 4205:     var founduname=0;
 4206:     var foundID=0;
 4207:     for (i=0;i<=vf.nfields.value;i++) {
 4208:       tw=eval('vf.f'+i+'.selectedIndex');
 4209:       if (tw==1) { foundID=1; }
 4210:       if (tw==2) { founduname=1; }
 4211:       if (tw>3) { foundsomething=1; }
 4212:     }
 4213:     if (founduname==0 && foundID==0) {
 4214: 	alert('$error1');
 4215: 	return;
 4216:     }
 4217:     if (foundsomething==0) {
 4218: 	alert('$error2');
 4219: 	return;
 4220:     }
 4221:     vf.submit();
 4222:   }
 4223:   function flip(vf,tf) {
 4224:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4225:     var i;
 4226:     //can not pick the same destination field twice
 4227:     for (i=0;i<=vf.nfields.value;i++) {
 4228:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4229:         eval('vf.f'+i+'.selectedIndex=0;')
 4230:       }
 4231:     }
 4232:   }
 4233: ENDPICK
 4234: }
 4235: 
 4236: sub csvuploadmap_header {
 4237:     my ($request,$symb,$datatoken,$distotal)= @_;
 4238:     my $javascript;
 4239:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4240: 	$javascript=&csvupload_javascript_reverse_associate();
 4241:     } else {
 4242: 	$javascript=&csvupload_javascript_forward_associate();
 4243:     }
 4244: 
 4245:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4246:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4247:     my $ignore=&mt('Ignore First Line');
 4248:     $symb = &Apache::lonenc::check_encrypt($symb);
 4249:     $request->print(<<ENDPICK);
 4250: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4251: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4252: $result
 4253: <hr />
 4254: <h3>Identify fields</h3>
 4255: Total number of records found in file: $distotal <hr />
 4256: Enter as many fields as you can. The system will inform you and bring you back
 4257: to this page if the data selected is insufficient to run your class.<hr />
 4258: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4259: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4260: <input type="hidden" name="associate"  value="" />
 4261: <input type="hidden" name="phase"      value="three" />
 4262: <input type="hidden" name="datatoken"  value="$datatoken" />
 4263: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4264: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4265: <input type="hidden" name="upfile_associate" 
 4266:                                        value="$env{'form.upfile_associate'}" />
 4267: <input type="hidden" name="symb"       value="$symb" />
 4268: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4269: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4270: <input type="hidden" name="command"    value="csvuploadoptions" />
 4271: <hr />
 4272: <script type="text/javascript" language="Javascript">
 4273: $javascript
 4274: </script>
 4275: ENDPICK
 4276:     return '';
 4277: 
 4278: }
 4279: 
 4280: sub csvupload_fields {
 4281:     my ($symb,$errorref) = @_;
 4282:     my (@parts) = &getpartlist($symb,$errorref);
 4283:     if (ref($errorref)) {
 4284:         if ($$errorref) {
 4285:             return;
 4286:         }
 4287:     }
 4288: 
 4289:     my @fields=(['ID','Student/Employee ID'],
 4290: 		['username','Student Username'],
 4291: 		['domain','Student Domain']);
 4292:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4293:     foreach my $part (sort(@parts)) {
 4294: 	my @datum;
 4295: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4296: 	my $name=$part;
 4297: 	if  (!$display) { $display = $name; }
 4298: 	@datum=($name,$display);
 4299: 	if ($name=~/^stores_(.*)_awarded/) {
 4300: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4301: 	}
 4302: 	push(@fields,\@datum);
 4303:     }
 4304:     return (@fields);
 4305: }
 4306: 
 4307: sub csvuploadmap_footer {
 4308:     my ($request,$i,$keyfields) =@_;
 4309:     my $buttontext = &mt('Assign Grades');
 4310:     $request->print(<<ENDPICK);
 4311: </table>
 4312: <input type="hidden" name="nfields" value="$i" />
 4313: <input type="hidden" name="keyfields" value="$keyfields" />
 4314: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4315: </form>
 4316: ENDPICK
 4317: }
 4318: 
 4319: sub checkforfile_js {
 4320:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4321:     my $result =<<CSVFORMJS;
 4322: <script type="text/javascript" language="javascript">
 4323:     function checkUpload(formname) {
 4324: 	if (formname.upfile.value == "") {
 4325: 	    alert("$alertmsg");
 4326: 	    return false;
 4327: 	}
 4328: 	formname.submit();
 4329:     }
 4330:     </script>
 4331: CSVFORMJS
 4332:     return $result;
 4333: }
 4334: 
 4335: sub upcsvScores_form {
 4336:     my ($request) = shift;
 4337:     my ($symb)=&get_symb($request);
 4338:     if (!$symb) {return '';}
 4339:     my $result=&checkforfile_js();
 4340:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4341:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4342:     $result.=$table;
 4343:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4344:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4345:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4346: 	'</b></td></tr>'."\n";
 4347:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4348:     my $upload=&mt("Upload Scores");
 4349:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4350:     my $ignore=&mt('Ignore First Line');
 4351:     $symb = &Apache::lonenc::check_encrypt($symb);
 4352:     $result.=<<ENDUPFORM;
 4353: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4354: <input type="hidden" name="symb" value="$symb" />
 4355: <input type="hidden" name="command" value="csvuploadmap" />
 4356: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4357: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4358: $upfile_select
 4359: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4360: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4361: </form>
 4362: ENDUPFORM
 4363:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4364:                            &mt("How do I create a CSV file from a spreadsheet"))
 4365:     .'</td></tr></table>'."\n";
 4366:     $result.='</td></tr></table><br /><br />'."\n";
 4367:     $result.=&show_grading_menu_form($symb);
 4368:     return $result;
 4369: }
 4370: 
 4371: 
 4372: sub csvuploadmap {
 4373:     my ($request)= @_;
 4374:     my ($symb)=&get_symb($request);
 4375:     if (!$symb) {return '';}
 4376: 
 4377:     my $datatoken;
 4378:     if (!$env{'form.datatoken'}) {
 4379: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4380:     } else {
 4381: 	$datatoken=$env{'form.datatoken'};
 4382: 	&Apache::loncommon::load_tmp_file($request);
 4383:     }
 4384:     my @records=&Apache::loncommon::upfile_record_sep();
 4385:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4386:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4387:     my ($i,$keyfields);
 4388:     if (@records) {
 4389:         my $fieldserror;
 4390: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4391:         if ($fieldserror) {
 4392:             $request->print(&navmap_errormsg());
 4393:             return;
 4394:         }
 4395: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4396: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4397: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4398: 							  \@fields);
 4399: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4400: 	    chop($keyfields);
 4401: 	} else {
 4402: 	    unshift(@fields,['none','']);
 4403: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4404: 							    \@fields);
 4405:             foreach my $rec (@records) {
 4406:                 my %temp = &Apache::loncommon::record_sep($rec);
 4407:                 if (%temp) {
 4408:                     $keyfields=join(',',sort(keys(%temp)));
 4409:                     last;
 4410:                 }
 4411:             }
 4412: 	}
 4413:     }
 4414:     &csvuploadmap_footer($request,$i,$keyfields);
 4415:     $request->print(&show_grading_menu_form($symb));
 4416: 
 4417:     return '';
 4418: }
 4419: 
 4420: sub csvuploadoptions {
 4421:     my ($request)= @_;
 4422:     my ($symb)=&get_symb($request);
 4423:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4424:     my $ignore=&mt('Ignore First Line');
 4425:     $request->print(<<ENDPICK);
 4426: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4427: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4428: <input type="hidden" name="command"    value="csvuploadassign" />
 4429: <!--
 4430: <p>
 4431: <label>
 4432:    <input type="checkbox" name="show_full_results" />
 4433:    Show a table of all changes
 4434: </label>
 4435: </p>
 4436: -->
 4437: <p>
 4438: <label>
 4439:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4440:    Overwrite any existing score
 4441: </label>
 4442: </p>
 4443: ENDPICK
 4444:     my %fields=&get_fields();
 4445:     if (!defined($fields{'domain'})) {
 4446: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4447: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4448:     }
 4449:     foreach my $key (sort(keys(%env))) {
 4450: 	if ($key !~ /^form\.(.*)$/) { next; }
 4451: 	my $cleankey=$1;
 4452: 	if ($cleankey eq 'command') { next; }
 4453: 	$request->print('<input type="hidden" name="'.$cleankey.
 4454: 			'"  value="'.$env{$key}.'" />'."\n");
 4455:     }
 4456:     # FIXME do a check for any duplicated user ids...
 4457:     # FIXME do a check for any invalid user ids?...
 4458:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4459: <hr /></form>'."\n");
 4460:     $request->print(&show_grading_menu_form($symb));
 4461:     return '';
 4462: }
 4463: 
 4464: sub get_fields {
 4465:     my %fields;
 4466:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4467:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4468: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4469: 	    if ($env{'form.f'.$i} ne 'none') {
 4470: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4471: 	    }
 4472: 	} else {
 4473: 	    if ($env{'form.f'.$i} ne 'none') {
 4474: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4475: 	    }
 4476: 	}
 4477:     }
 4478:     return %fields;
 4479: }
 4480: 
 4481: sub csvuploadassign {
 4482:     my ($request)= @_;
 4483:     my ($symb)=&get_symb($request);
 4484:     if (!$symb) {return '';}
 4485:     my $error_msg = '';
 4486:     &Apache::loncommon::load_tmp_file($request);
 4487:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4488:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4489:     my %fields=&get_fields();
 4490:     $request->print('<h3>Assigning Grades</h3>');
 4491:     my $courseid=$env{'request.course.id'};
 4492:     my ($classlist) = &getclasslist('all',0);
 4493:     my @notallowed;
 4494:     my @skipped;
 4495:     my @warnings;
 4496:     my $countdone=0;
 4497:     foreach my $grade (@gradedata) {
 4498: 	my %entries=&Apache::loncommon::record_sep($grade);
 4499: 	my $domain;
 4500: 	if ($entries{$fields{'domain'}}) {
 4501: 	    $domain=$entries{$fields{'domain'}};
 4502: 	} else {
 4503: 	    $domain=$env{'form.default_domain'};
 4504: 	}
 4505: 	$domain=~s/\s//g;
 4506: 	my $username=$entries{$fields{'username'}};
 4507: 	$username=~s/\s//g;
 4508: 	if (!$username) {
 4509: 	    my $id=$entries{$fields{'ID'}};
 4510: 	    $id=~s/\s//g;
 4511: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4512: 	    $username=$ids{$id};
 4513: 	}
 4514: 	if (!exists($$classlist{"$username:$domain"})) {
 4515: 	    my $id=$entries{$fields{'ID'}};
 4516: 	    $id=~s/\s//g;
 4517: 	    if ($id) {
 4518: 		push(@skipped,"$id:$domain");
 4519: 	    } else {
 4520: 		push(@skipped,"$username:$domain");
 4521: 	    }
 4522: 	    next;
 4523: 	}
 4524: 	my $usec=$classlist->{"$username:$domain"}[5];
 4525: 	if (!&canmodify($usec)) {
 4526: 	    push(@notallowed,"$username:$domain");
 4527: 	    next;
 4528: 	}
 4529: 	my %points;
 4530: 	my %grades;
 4531: 	foreach my $dest (keys(%fields)) {
 4532: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4533: 		$dest eq 'domain') { next; }
 4534: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4535: 	    if ($dest=~/stores_(.*)_points/) {
 4536: 		my $part=$1;
 4537: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4538: 					      $symb,$domain,$username);
 4539:                 if ($wgt) {
 4540:                     $entries{$fields{$dest}}=~s/\s//g;
 4541:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4542:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4543:                                           : 'correct_by_override';
 4544:                     if ($pcr>1) {
 4545:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4546:                     }
 4547:                     $grades{"resource.$part.awarded"}=$pcr;
 4548:                     $grades{"resource.$part.solved"}=$award;
 4549:                     $points{$part}=1;
 4550:                 } else {
 4551:                     $error_msg = "<br />" .
 4552:                         &mt("Some point values were assigned"
 4553:                             ." for problems with a weight "
 4554:                             ."of zero. These values were "
 4555:                             ."ignored.");
 4556:                 }
 4557: 	    } else {
 4558: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4559: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4560: 		my $store_key=$dest;
 4561: 		$store_key=~s/^stores/resource/;
 4562: 		$store_key=~s/_/\./g;
 4563: 		$grades{$store_key}=$entries{$fields{$dest}};
 4564: 	    }
 4565: 	}
 4566: 	if (! %grades) { 
 4567:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4568:         } else {
 4569: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4570: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4571: 					   $env{'request.course.id'},
 4572: 					   $domain,$username);
 4573: 	   if ($result eq 'ok') {
 4574: 	      $request->print('.');
 4575: # Remove from grading queue
 4576:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4577:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4578:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4579:                                              $domain,$username);
 4580: 	   } else {
 4581: 	      $request->print("<p><span class=\"LC_error\">".
 4582:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4583:                                   "$username:$domain",$result)."</span></p>");
 4584: 	   }
 4585: 	   $request->rflush();
 4586: 	   $countdone++;
 4587:         }
 4588:     }
 4589:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4590:     if (@warnings) {
 4591:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4592:         $request->print(join(', ',@warnings));
 4593:     }
 4594:     if (@skipped) {
 4595: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4596:         $request->print(join(', ',@skipped));
 4597:     }
 4598:     if (@notallowed) {
 4599: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4600: 	$request->print(join(', ',@notallowed));
 4601:     }
 4602:     $request->print("<br />\n");
 4603:     $request->print(&show_grading_menu_form($symb));
 4604:     return $error_msg;
 4605: }
 4606: #------------- end of section for handling csv file upload ---------
 4607: #
 4608: #-------------------------------------------------------------------
 4609: #
 4610: #-------------- Next few routines handle grading by page/sequence
 4611: #
 4612: #--- Select a page/sequence and a student to grade
 4613: sub pickStudentPage {
 4614:     my ($request) = shift;
 4615: 
 4616:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4617:     $request->print(<<LISTJAVASCRIPT);
 4618: <script type="text/javascript" language="javascript">
 4619: 
 4620: function checkPickOne(formname) {
 4621:     if (radioSelection(formname.student) == null) {
 4622: 	alert("$alertmsg");
 4623: 	return;
 4624:     }
 4625:     ptr = pullDownSelection(formname.selectpage);
 4626:     formname.page.value = formname["page"+ptr].value;
 4627:     formname.title.value = formname["title"+ptr].value;
 4628:     formname.submit();
 4629: }
 4630: 
 4631: </script>
 4632: LISTJAVASCRIPT
 4633:     &commonJSfunctions($request);
 4634:     my ($symb) = &get_symb($request);
 4635:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4636:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4637:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4638: 
 4639:     my $result='<h3><span class="LC_info">&nbsp;'.
 4640: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4641: 
 4642:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4643:     my $map_error;
 4644:     my ($titles,$symbx) = &getSymbMap($map_error);
 4645:     if ($map_error) {
 4646:         $request->print(&navmap_errormsg());
 4647:         return; 
 4648:     }
 4649:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4650: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4651: #    my $type=($curpage =~ /\.(page|sequence)/);
 4652:     my $select = '<select name="selectpage">'."\n";
 4653:     my $ctr=0;
 4654:     foreach (@$titles) {
 4655: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4656: 	$select.='<option value="'.$ctr.'" '.
 4657: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4658: 	    '>'.$showtitle.'</option>'."\n";
 4659: 	$ctr++;
 4660:     }
 4661:     $select.= '</select>';
 4662:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4663: 
 4664:     $ctr=0;
 4665:     foreach (@$titles) {
 4666: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4667: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4668: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4669: 	$ctr++;
 4670:     }
 4671:     $result.='<input type="hidden" name="page" />'."\n".
 4672: 	'<input type="hidden" name="title" />'."\n";
 4673: 
 4674:     my $options =
 4675: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4676: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4677:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4678: 
 4679:     $options =
 4680: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4681: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4682: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4683:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4684:     
 4685:     $result.=&build_section_inputs();
 4686:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4687:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4688: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4689: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4690: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4691: 
 4692:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4693: 
 4694:     $result.='&nbsp;<input type="button" '.
 4695:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4696: 
 4697:     $request->print($result);
 4698: 
 4699:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4700: 	&Apache::loncommon::start_data_table().
 4701: 	&Apache::loncommon::start_data_table_header_row().
 4702: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4703: 	'<th>'.&nameUserString('header').'</th>'.
 4704: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4705: 	'<th>'.&nameUserString('header').'</th>'.
 4706: 	&Apache::loncommon::end_data_table_header_row();
 4707:  
 4708:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4709:     my $ptr = 1;
 4710:     foreach my $student (sort 
 4711: 			 {
 4712: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4713: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4714: 			     }
 4715: 			     return $a cmp $b;
 4716: 			 } (keys(%$fullname))) {
 4717: 	my ($uname,$udom) = split(/:/,$student);
 4718: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4719:                                   : '</td>');
 4720: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4721: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4722: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4723: 	$studentTable.=
 4724: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4725:                          : '');
 4726: 	$ptr++;
 4727:     }
 4728:     if ($ptr%2 == 0) {
 4729: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4730: 	    &Apache::loncommon::end_data_table_row();
 4731:     }
 4732:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4733:     $studentTable.='<input type="button" '.
 4734:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4735: 
 4736:     $studentTable.=&show_grading_menu_form($symb);
 4737:     $request->print($studentTable);
 4738: 
 4739:     return '';
 4740: }
 4741: 
 4742: sub getSymbMap {
 4743:     my ($map_error) = @_;
 4744:     my $navmap = Apache::lonnavmaps::navmap->new();
 4745:     unless (ref($navmap)) {
 4746:         if (ref($map_error)) {
 4747:             $$map_error = 'navmap';
 4748:         }
 4749:         return;
 4750:     }
 4751:     my %symbx = ();
 4752:     my @titles = ();
 4753:     my $minder = 0;
 4754: 
 4755:     # Gather every sequence that has problems.
 4756:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4757: 					       1,0,1);
 4758:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4759: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4760: 	    my $title = $minder.'.'.
 4761: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4762: 	    push(@titles, $title); # minder in case two titles are identical
 4763: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4764: 	    $minder++;
 4765: 	}
 4766:     }
 4767:     return \@titles,\%symbx;
 4768: }
 4769: 
 4770: #
 4771: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4772: sub displayPage {
 4773:     my ($request) = shift;
 4774: 
 4775:     my ($symb) = &get_symb($request);
 4776:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4777:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4778:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4779:     my $pageTitle = $env{'form.page'};
 4780:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4781:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4782:     my $usec=$classlist->{$env{'form.student'}}[5];
 4783: 
 4784:     #need to make sure we have the correct data for later EXT calls, 
 4785:     #thus invalidate the cache
 4786:     &Apache::lonnet::devalidatecourseresdata(
 4787:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4788:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4789:     &Apache::lonnet::clear_EXT_cache_status();
 4790: 
 4791:     if (!&canview($usec)) {
 4792: 	$request->print('<span class="LC_warning">'.
 4793:                         &mt('Unable to view requested student. ([_1])',
 4794:                             $env{'form.student'}).
 4795:                         '</span>');
 4796:         $request->print(&show_grading_menu_form($symb));
 4797:         return;
 4798:     }
 4799:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4800:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4801: 	'</h3>'."\n";
 4802:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4803:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4804: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4805:     } else {
 4806: 	delete($env{'form.CODE'});
 4807:     }
 4808:     &sub_page_js($request);
 4809:     $request->print($result);
 4810: 
 4811:     my $navmap = Apache::lonnavmaps::navmap->new();
 4812:     unless (ref($navmap)) {
 4813:         $request->print(&navmap_errormsg());
 4814:         $request->print(&show_grading_menu_form($symb));
 4815:         return;
 4816:     }
 4817:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4818:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4819:     if (!$map) {
 4820: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4821: 	$request->print(&show_grading_menu_form($symb));
 4822: 	return; 
 4823:     }
 4824:     my $iterator = $navmap->getIterator($map->map_start(),
 4825: 					$map->map_finish());
 4826: 
 4827:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4828: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4829: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4830: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4831: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4832: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4833: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4834: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4835: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4836: 
 4837:     if (defined($env{'form.CODE'})) {
 4838: 	$studentTable.=
 4839: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4840:     }
 4841:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4842: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4843: 
 4844:     $studentTable.='&nbsp;<span class="LC_info">'.
 4845:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4846:         '</span>'."\n".
 4847: 	&Apache::loncommon::start_data_table().
 4848: 	&Apache::loncommon::start_data_table_header_row().
 4849: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4850: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4851: 	&Apache::loncommon::end_data_table_header_row();
 4852: 
 4853:     &Apache::lonxml::clear_problem_counter();
 4854:     my ($depth,$question,$prob) = (1,1,1);
 4855:     $iterator->next(); # skip the first BEGIN_MAP
 4856:     my $curRes = $iterator->next(); # for "current resource"
 4857:     while ($depth > 0) {
 4858:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4859:         if($curRes == $iterator->END_MAP) { $depth--; }
 4860: 
 4861:         if (ref($curRes) && $curRes->is_problem()) {
 4862: 	    my $parts = $curRes->parts();
 4863:             my $title = $curRes->compTitle();
 4864: 	    my $symbx = $curRes->symb();
 4865: 	    $studentTable.=
 4866: 		&Apache::loncommon::start_data_table_row().
 4867: 		'<td align="center" valign="top" >'.$prob.
 4868: 		(scalar(@{$parts}) == 1 ? '' 
 4869: 		                        : '<br />('.&mt('[_1]parts',
 4870: 							scalar(@{$parts}).'&nbsp;').')'
 4871: 		 ).
 4872: 		 '</td>';
 4873: 	    $studentTable.='<td valign="top">';
 4874: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4875: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4876: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4877: 					     undef,'both',\%form);
 4878: 	    } else {
 4879: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4880: 		$companswer =~ s|<form(.*?)>||g;
 4881: 		$companswer =~ s|</form>||g;
 4882: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4883: #		    $companswer =~ s/$1/ /ms;
 4884: #		    $request->print('match='.$1."<br />\n");
 4885: #		}
 4886: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4887: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4888: 	    }
 4889: 
 4890: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4891: 
 4892: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4893: 		if ($record{'version'} eq '') {
 4894: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4895: 		} else {
 4896: 		    my %responseType = ();
 4897: 		    foreach my $partid (@{$parts}) {
 4898: 			my @responseIds =$curRes->responseIds($partid);
 4899: 			my @responseType =$curRes->responseType($partid);
 4900: 			my %responseIds;
 4901: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4902: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4903: 			}
 4904: 			$responseType{$partid} = \%responseIds;
 4905: 		    }
 4906: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4907: 
 4908: 		}
 4909: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4910: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4911: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4912: 									$env{'request.course.id'},
 4913: 									'','.submission');
 4914:  
 4915: 	    }
 4916: 	    if (&canmodify($usec)) {
 4917:             $studentTable.=&gradeBox_start();
 4918: 		foreach my $partid (@{$parts}) {
 4919: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4920: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4921: 		    $question++;
 4922: 		}
 4923:             $studentTable.=&gradeBox_end();
 4924: 		$prob++;
 4925: 	    }
 4926: 	    $studentTable.='</td></tr>';
 4927: 
 4928: 	}
 4929:         $curRes = $iterator->next();
 4930:     }
 4931: 
 4932:     $studentTable.=
 4933:         '</table>'."\n".
 4934:         '<input type="button" value="'.&mt('Save').'" '.
 4935:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4936:         '</form>'."\n";
 4937:     $studentTable.=&show_grading_menu_form($symb);
 4938:     $request->print($studentTable);
 4939: 
 4940:     return '';
 4941: }
 4942: 
 4943: sub displaySubByDates {
 4944:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4945:     my $isCODE=0;
 4946:     my $isTask = ($symb =~/\.task$/);
 4947:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4948:     my $studentTable=&Apache::loncommon::start_data_table().
 4949: 	&Apache::loncommon::start_data_table_header_row().
 4950: 	'<th>'.&mt('Date/Time').'</th>'.
 4951: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4952:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4953: 	'<th>'.&mt('Submission').'</th>'.
 4954: 	'<th>'.&mt('Status').'</th>'.
 4955: 	&Apache::loncommon::end_data_table_header_row();
 4956:     my ($version);
 4957:     my %mark;
 4958:     my %orders;
 4959:     $mark{'correct_by_student'} = $checkIcon;
 4960:     if (!exists($$record{'1:timestamp'})) {
 4961: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4962:     }
 4963: 
 4964:     my $interaction;
 4965:     my $no_increment = 1;
 4966:     my %lastrndseed;
 4967:     for ($version=1;$version<=$$record{'version'};$version++) {
 4968: 	my $timestamp = 
 4969: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4970: 	if (exists($$record{$version.':resource.0.version'})) {
 4971: 	    $interaction = $$record{$version.':resource.0.version'};
 4972: 	}
 4973:         if ($isTask && $env{'form.previousversion'}) {
 4974:             next unless ($interaction == $env{'form.previousversion'});
 4975:         }
 4976: 	my $where = ($isTask ? "$version:resource.$interaction"
 4977: 		             : "$version:resource");
 4978: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4979: 	    '<td>'.$timestamp.'</td>';
 4980: 	if ($isCODE) {
 4981: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4982: 	}
 4983:         if ($isTask) {
 4984:             $studentTable.='<td>'.$interaction.'</td>';
 4985:         }
 4986: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4987: 	my @displaySub = ();
 4988: 	foreach my $partid (@{$parts}) {
 4989:             my ($hidden,$type);
 4990:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4991:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4992:                 $hidden = 1;
 4993:             }
 4994: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4995: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4996: 	    
 4997: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4998: 	    my $display_part=&get_display_part($partid,$symb);
 4999: 	    foreach my $matchKey (@matchKey) {
 5000: 		if (exists($$record{$version.':'.$matchKey}) &&
 5001: 		    $$record{$version.':'.$matchKey} ne '') {
 5002:                     
 5003: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5004: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5005:                     $displaySub[0].='<span class="LC_nobreak">';
 5006:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5007:                                    .' <span class="LC_internal_info">'
 5008:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5009:                                    .'</span>'
 5010:                                    .' <b>';
 5011:                     if ($hidden) {
 5012:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5013:                     } else {
 5014:                         my ($trial,$rndseed,$newvariation);
 5015:                         if ($type eq 'randomizetry') {
 5016:                             $trial = $$record{"$where.$partid.tries"};
 5017:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5018:                         }
 5019: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5020: 			    $displaySub[0].=&mt('Trial not counted');
 5021: 		        } else {
 5022: 			    $displaySub[0].=&mt('Trial: [_1]',
 5023: 					    $$record{"$where.$partid.tries"});
 5024:                             if ($rndseed || $lastrndseed{$partid}) {
 5025:                                 if ($rndseed ne $lastrndseed{$partid}) {
 5026:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5027:                                 }
 5028:                             }
 5029: 		        }
 5030: 		        my $responseType=($isTask ? 'Task'
 5031:                                               : $responseType->{$partid}->{$responseId});
 5032: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5033: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5034: 			    $orders{$partid}->{$responseId}=
 5035: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5036:                                            $no_increment,$type,$trial,$rndseed);
 5037: 		        }
 5038: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5039: 		        $displaySub[0].='&nbsp; '.
 5040: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5041:                     }
 5042: 		}
 5043: 	    }
 5044: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5045: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5046: 				    $$record{"$where.$partid.checkedin"},
 5047: 				    $$record{"$where.$partid.checkedin.slot"}).
 5048: 					'<br />';
 5049: 	    }
 5050: 	    if (exists $$record{"$where.$partid.award"}) {
 5051: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5052: 		    lc($$record{"$where.$partid.award"}).' '.
 5053: 		    $mark{$$record{"$where.$partid.solved"}}.
 5054: 		    '<br />';
 5055: 	    }
 5056: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5057: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5058: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5059: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5060: 		$displaySub[2].=
 5061: 		    $$record{"$version:resource.$partid.regrader"}.
 5062: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5063: 	    }
 5064: 	}
 5065: 	# needed because old essay regrader has not parts info
 5066: 	if (exists $$record{"$version:resource.regrader"}) {
 5067: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5068: 	}
 5069: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5070: 	if ($displaySub[2]) {
 5071: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5072: 	}
 5073: 	$studentTable.='&nbsp;</td>'.
 5074: 	    &Apache::loncommon::end_data_table_row();
 5075:     }
 5076:     $studentTable.=&Apache::loncommon::end_data_table();
 5077:     return $studentTable;
 5078: }
 5079: 
 5080: sub updateGradeByPage {
 5081:     my ($request) = shift;
 5082: 
 5083:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5084:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5085:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5086:     my $pageTitle = $env{'form.page'};
 5087:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5088:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5089:     my $usec=$classlist->{$env{'form.student'}}[5];
 5090:     if (!&canmodify($usec)) {
 5091: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5092: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5093: 	return;
 5094:     }
 5095:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5096:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5097: 	'</h3>'."\n";
 5098: 
 5099:     $request->print($result);
 5100: 
 5101: 
 5102:     my $navmap = Apache::lonnavmaps::navmap->new();
 5103:     unless (ref($navmap)) {
 5104:         $request->print(&navmap_errormsg());
 5105:         return;
 5106:     }
 5107:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5108:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5109:     if (!$map) {
 5110: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5111: 	my ($symb)=&get_symb($request);
 5112: 	$request->print(&show_grading_menu_form($symb));
 5113: 	return; 
 5114:     }
 5115:     my $iterator = $navmap->getIterator($map->map_start(),
 5116: 					$map->map_finish());
 5117: 
 5118:     my $studentTable=
 5119: 	&Apache::loncommon::start_data_table().
 5120: 	&Apache::loncommon::start_data_table_header_row().
 5121: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5122: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5123: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5124: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5125: 	&Apache::loncommon::end_data_table_header_row();
 5126: 
 5127:     $iterator->next(); # skip the first BEGIN_MAP
 5128:     my $curRes = $iterator->next(); # for "current resource"
 5129:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 5130:     while ($depth > 0) {
 5131:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5132:         if($curRes == $iterator->END_MAP) { $depth--; }
 5133: 
 5134:         if (ref($curRes) && $curRes->is_problem()) {
 5135: 	    my $parts = $curRes->parts();
 5136:             my $title = $curRes->compTitle();
 5137: 	    my $symbx = $curRes->symb();
 5138: 	    $studentTable.=
 5139: 		&Apache::loncommon::start_data_table_row().
 5140: 		'<td align="center" valign="top" >'.$prob.
 5141: 		(scalar(@{$parts}) == 1 ? '' 
 5142:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5143: 		.')').'</td>';
 5144: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5145: 
 5146: 	    my %newrecord=();
 5147: 	    my @displayPts=();
 5148:             my %aggregate = ();
 5149:             my $aggregateflag = 0;
 5150: 	    foreach my $partid (@{$parts}) {
 5151: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5152: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5153: 
 5154: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5155: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5156: 		my $partial = $newpts/$wgt;
 5157: 		my $score;
 5158: 		if ($partial > 0) {
 5159: 		    $score = 'correct_by_override';
 5160: 		} elsif ($newpts ne '') { #empty is taken as 0
 5161: 		    $score = 'incorrect_by_override';
 5162: 		}
 5163: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5164: 		if ($dropMenu eq 'excused') {
 5165: 		    $partial = '';
 5166: 		    $score = 'excused';
 5167: 		} elsif ($dropMenu eq 'reset status'
 5168: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5169: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5170: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5171: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5172: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5173: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5174: 		    $changeflag++;
 5175: 		    $newpts = '';
 5176:                     
 5177:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5178:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5179:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5180:                     if ($aggtries > 0) {
 5181:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5182:                         $aggregateflag = 1;
 5183:                     }
 5184: 		}
 5185: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5186: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5187: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5188: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5189: 		    '&nbsp;<br />';
 5190: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5191: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5192: 		    '&nbsp;<br />';
 5193: 		$question++;
 5194: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5195: 
 5196: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5197: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5198: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5199: 		    if (scalar(keys(%newrecord)) > 0);
 5200: 
 5201: 		$changeflag++;
 5202: 	    }
 5203: 	    if (scalar(keys(%newrecord)) > 0) {
 5204: 		my %record = 
 5205: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5206: 					     $udom,$uname);
 5207: 
 5208: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5209: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5210: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5211: 		    $newrecord{'resource.CODE'} = '';
 5212: 		}
 5213: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5214: 					$udom,$uname);
 5215: 		%record = &Apache::lonnet::restore($symbx,
 5216: 						   $env{'request.course.id'},
 5217: 						   $udom,$uname);
 5218: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5219: 					     $cdom,$cnum,$udom,$uname);
 5220: 	    }
 5221: 	    
 5222:             if ($aggregateflag) {
 5223:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5224:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5225:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5226:             }
 5227: 
 5228: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5229: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5230: 		&Apache::loncommon::end_data_table_row();
 5231: 
 5232: 	    $prob++;
 5233: 	}
 5234:         $curRes = $iterator->next();
 5235:     }
 5236: 
 5237:     $studentTable.=&Apache::loncommon::end_data_table();
 5238:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5239:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5240: 		  &mt('The scores were changed for [quant,_1,problem].',
 5241: 		  $changeflag));
 5242:     $request->print($grademsg.$studentTable);
 5243: 
 5244:     return '';
 5245: }
 5246: 
 5247: #-------- end of section for handling grading by page/sequence ---------
 5248: #
 5249: #-------------------------------------------------------------------
 5250: 
 5251: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5252: #
 5253: #------ start of section for handling grading by page/sequence ---------
 5254: 
 5255: =pod
 5256: 
 5257: =head1 Bubble sheet grading routines
 5258: 
 5259:   For this documentation:
 5260: 
 5261:    'scanline' refers to the full line of characters
 5262:    from the file that we are parsing that represents one entire sheet
 5263: 
 5264:    'bubble line' refers to the data
 5265:    representing the line of bubbles that are on the physical bubblesheet
 5266: 
 5267: 
 5268: The overall process is that a scanned in bubblesheet data is uploaded
 5269: into a course. When a user wants to grade, they select a
 5270: sequence/folder of resources, a file of bubblesheet info, and pick
 5271: one of the predefined configurations for what each scanline looks
 5272: like.
 5273: 
 5274: Next each scanline is checked for any errors of either 'missing
 5275: bubbles' (it's an error because it may have been mis-scanned
 5276: because too light bubbling), 'double bubble' (each bubble line should
 5277: have no more than one letter picked), invalid or duplicated CODE,
 5278: invalid student/employee ID
 5279: 
 5280: If the CODE option is used that determines the randomization of the
 5281: homework problems, either way the student/employee ID is looked up into a
 5282: username:domain.
 5283: 
 5284: During the validation phase the instructor can choose to skip scanlines. 
 5285: 
 5286: After the validation phase, there are now 3 bubblesheet files
 5287: 
 5288:   scantron_original_filename (unmodified original file)
 5289:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5290:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5291: 
 5292: Also there is a separate hash nohist_scantrondata that contains extra
 5293: correction information that isn't representable in the bubblesheet
 5294: file (see &scantron_getfile() for more information)
 5295: 
 5296: After all scanlines are either valid, marked as valid or skipped, then
 5297: foreach line foreach problem in the picked sequence, an ssi request is
 5298: made that simulates a user submitting their selected letter(s) against
 5299: the homework problem.
 5300: 
 5301: =over 4
 5302: 
 5303: 
 5304: 
 5305: =item defaultFormData
 5306: 
 5307:   Returns html hidden inputs used to hold context/default values.
 5308: 
 5309:  Arguments:
 5310:   $symb - $symb of the current resource 
 5311: 
 5312: =cut
 5313: 
 5314: sub defaultFormData {
 5315:     my ($symb)=@_;
 5316:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5317:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5318:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5319: }
 5320: 
 5321: 
 5322: =pod 
 5323: 
 5324: =item getSequenceDropDown
 5325: 
 5326:    Return html dropdown of possible sequences to grade
 5327:  
 5328:  Arguments:
 5329:    $symb - $symb of the current resource
 5330:    $map_error - ref to scalar which will container error if
 5331:                 $navmap object is unavailable in &getSymbMap().
 5332: 
 5333: =cut
 5334: 
 5335: sub getSequenceDropDown {
 5336:     my ($symb,$map_error)=@_;
 5337:     my $result='<select name="selectpage">'."\n";
 5338:     my ($titles,$symbx) = &getSymbMap($map_error);
 5339:     if (ref($map_error)) {
 5340:         return if ($$map_error);
 5341:     }
 5342:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5343:     my $ctr=0;
 5344:     foreach (@$titles) {
 5345: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5346: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5347: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5348: 	    '>'.$showtitle.'</option>'."\n";
 5349: 	$ctr++;
 5350:     }
 5351:     $result.= '</select>';
 5352:     return $result;
 5353: }
 5354: 
 5355: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5356:                                    # key is zero-based index - 0, 1, 2 ...
 5357: 
 5358: my %first_bubble_line;             # First bubble line no. for each bubble.
 5359: 
 5360: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5361:                                    # matchresponse or rankresponse, where 
 5362:                                    # an individual response can have multiple 
 5363:                                    # lines
 5364: 
 5365: my %responsetype_per_response;     # responsetype for each response
 5366: 
 5367: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5368:                                    # numbered response. Needed when randomorder
 5369:                                    # or randompick are in use. Key is ID, value 
 5370:                                    # is response number.
 5371: 
 5372: # Save and restore the bubble lines array to the form env.
 5373: 
 5374: 
 5375: sub save_bubble_lines {
 5376:     foreach my $line (keys(%bubble_lines_per_response)) {
 5377: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5378: 	$env{"form.scantron.first_bubble_line.$line"} =
 5379: 	    $first_bubble_line{$line};
 5380:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5381:             $subdivided_bubble_lines{$line};
 5382:         $env{"form.scantron.responsetype.$line"} =
 5383:             $responsetype_per_response{$line};
 5384:     }
 5385:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5386:         my $line = $masterseq_id_responsenum{$resid};
 5387:         $env{"form.scantron.residpart.$line"} = $resid;
 5388:     }
 5389: }
 5390: 
 5391: 
 5392: sub restore_bubble_lines {
 5393:     my $line = 0;
 5394:     %bubble_lines_per_response = ();
 5395:     %masterseq_id_responsenum = ();
 5396:     while ($env{"form.scantron.bubblelines.$line"}) {
 5397: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5398: 	$bubble_lines_per_response{$line} = $value;
 5399: 	$first_bubble_line{$line}  =
 5400: 	    $env{"form.scantron.first_bubble_line.$line"};
 5401:         $subdivided_bubble_lines{$line} =
 5402:             $env{"form.scantron.sub_bubblelines.$line"};
 5403:         $responsetype_per_response{$line} =
 5404:             $env{"form.scantron.responsetype.$line"};
 5405:         my $id = $env{"form.scantron.residpart.$line"};
 5406:         $masterseq_id_responsenum{$id} = $line;
 5407: 	$line++;
 5408:     }
 5409: }
 5410: 
 5411: =pod 
 5412: 
 5413: =item scantron_filenames
 5414: 
 5415:    Returns a list of the scantron files in the current course 
 5416: 
 5417: =cut
 5418: 
 5419: sub scantron_filenames {
 5420:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5421:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5422:     my $getpropath = 1;
 5423:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5424:                                                         $cname,$getpropath);
 5425:     my @possiblenames;
 5426:     if (ref($dirlist) eq 'ARRAY') {
 5427:         foreach my $filename (sort(@{$dirlist})) {
 5428: 	    ($filename)=split(/&/,$filename);
 5429: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5430: 	    $filename=~s/^scantron_orig_//;
 5431: 	    push(@possiblenames,$filename);
 5432:         }
 5433:     }
 5434:     return @possiblenames;
 5435: }
 5436: 
 5437: =pod 
 5438: 
 5439: =item scantron_uploads
 5440: 
 5441:    Returns  html drop-down list of scantron files in current course.
 5442: 
 5443:  Arguments:
 5444:    $file2grade - filename to set as selected in the dropdown
 5445: 
 5446: =cut
 5447: 
 5448: sub scantron_uploads {
 5449:     my ($file2grade) = @_;
 5450:     my $result=	'<select name="scantron_selectfile">';
 5451:     $result.="<option></option>";
 5452:     foreach my $filename (sort(&scantron_filenames())) {
 5453: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5454:     }
 5455:     $result.="</select>";
 5456:     return $result;
 5457: }
 5458: 
 5459: =pod 
 5460: 
 5461: =item scantron_scantab
 5462: 
 5463:   Returns html drop down of the scantron formats in the scantronformat.tab
 5464:   file.
 5465: 
 5466: =cut
 5467: 
 5468: sub scantron_scantab {
 5469:     my $result='<select name="scantron_format">'."\n";
 5470:     $result.='<option></option>'."\n";
 5471:     my @lines = &get_scantronformat_file();
 5472:     if (@lines > 0) {
 5473:         foreach my $line (@lines) {
 5474:             next if (($line =~ /^\#/) || ($line eq ''));
 5475: 	    my ($name,$descrip)=split(/:/,$line);
 5476: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5477:         }
 5478:     }
 5479:     $result.='</select>'."\n";
 5480:     return $result;
 5481: }
 5482: 
 5483: =pod
 5484: 
 5485: =item get_scantronformat_file
 5486: 
 5487:   Returns an array containing lines from the scantron format file for
 5488:   the domain of the course.
 5489: 
 5490:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5491:   lines are from this file.
 5492: 
 5493:   Otherwise, if a default.tab has been published in RES space by the 
 5494:   domainconfig user, lines are from this file.
 5495: 
 5496:   Otherwise, fall back to getting lines from the legacy file on the
 5497:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5498: 
 5499: =cut
 5500: 
 5501: sub get_scantronformat_file {
 5502:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5503:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5504:     my $gottab = 0;
 5505:     my @lines;
 5506:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5507:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5508:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5509:             if ($formatfile ne '-1') {
 5510:                 @lines = split("\n",$formatfile,-1);
 5511:                 $gottab = 1;
 5512:             }
 5513:         }
 5514:     }
 5515:     if (!$gottab) {
 5516:         my $confname = $cdom.'-domainconfig';
 5517:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5518:         my $formatfile =  &Apache::lonnet::getfile($default);
 5519:         if ($formatfile ne '-1') {
 5520:             @lines = split("\n",$formatfile,-1);
 5521:             $gottab = 1;
 5522:         }
 5523:     }
 5524:     if (!$gottab) {
 5525:         my @domains = &Apache::lonnet::current_machine_domains();
 5526:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5527:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5528:             @lines = <$fh>;
 5529:             close($fh);
 5530:         } else {
 5531:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5532:             @lines = <$fh>;
 5533:             close($fh);
 5534:         }
 5535:     }
 5536:     return @lines;
 5537: }
 5538: 
 5539: =pod 
 5540: 
 5541: =item scantron_CODElist
 5542: 
 5543:   Returns html drop down of the saved CODE lists from current course,
 5544:   generated from earlier printings.
 5545: 
 5546: =cut
 5547: 
 5548: sub scantron_CODElist {
 5549:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5550:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5551:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5552:     my $namechoice='<option></option>';
 5553:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5554: 	if ($name =~ /^error: 2 /) { next; }
 5555: 	if ($name =~ /^type\0/) { next; }
 5556: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5557:     }
 5558:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5559:     return $namechoice;
 5560: }
 5561: 
 5562: =pod 
 5563: 
 5564: =item scantron_CODEunique
 5565: 
 5566:   Returns the html for "Each CODE to be used once" radio.
 5567: 
 5568: =cut
 5569: 
 5570: sub scantron_CODEunique {
 5571:     my $result='<span class="LC_nobreak">
 5572:                  <label><input type="radio" name="scantron_CODEunique"
 5573:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5574:                 </span>
 5575:                 <span class="LC_nobreak">
 5576:                  <label><input type="radio" name="scantron_CODEunique"
 5577:                         value="no" />'.&mt('No').' </label>
 5578:                 </span>';
 5579:     return $result;
 5580: }
 5581: 
 5582: =pod 
 5583: 
 5584: =item scantron_selectphase
 5585: 
 5586:   Generates the initial screen to start the bubblesheet process.
 5587:   Allows for - starting a grading run.
 5588:              - downloading existing scan data (original, corrected
 5589:                                                 or skipped info)
 5590: 
 5591:              - uploading new scan data
 5592: 
 5593:  Arguments:
 5594:   $r          - The Apache request object
 5595:   $file2grade - name of the file that contain the scanned data to score
 5596: 
 5597: =cut
 5598: 
 5599: sub scantron_selectphase {
 5600:     my ($r,$file2grade) = @_;
 5601:     my ($symb)=&get_symb($r);
 5602:     if (!$symb) {return '';}
 5603:     my $map_error;
 5604:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5605:     if ($map_error) {
 5606:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5607:         return;
 5608:     }
 5609:     my $default_form_data=&defaultFormData($symb);
 5610:     my $grading_menu_button=&show_grading_menu_form($symb);
 5611:     my $file_selector=&scantron_uploads($file2grade);
 5612:     my $format_selector=&scantron_scantab();
 5613:     my $CODE_selector=&scantron_CODElist();
 5614:     my $CODE_unique=&scantron_CODEunique();
 5615:     my $result;
 5616: 
 5617:     $ssi_error = 0;
 5618: 
 5619:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5620:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5621: 
 5622:         # Chunk of form to prompt for a scantron file upload.
 5623: 
 5624:         $r->print('
 5625:     <br />
 5626:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5627:        '.&Apache::loncommon::start_data_table_header_row().'
 5628:             <th>
 5629:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5630:             </th>
 5631:        '.&Apache::loncommon::end_data_table_header_row().'
 5632:        '.&Apache::loncommon::start_data_table_row().'
 5633:             <td>
 5634: ');
 5635:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5636:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5637:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5638:     $r->print('
 5639:               <script type="text/javascript" language="javascript">
 5640:     function checkUpload(formname) {
 5641:         if (formname.upfile.value == "") {
 5642:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5643:             return false;
 5644:         }
 5645:         formname.submit();
 5646:     }
 5647:               </script>
 5648: 
 5649:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5650:                 '.$default_form_data.'
 5651:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5652:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5653:                 <input name="command" value="scantronupload_save" type="hidden" />
 5654:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5655:                 <br />
 5656:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5657:               </form>
 5658: ');
 5659: 
 5660:         $r->print('
 5661:             </td>
 5662:        '.&Apache::loncommon::end_data_table_row().'
 5663:        '.&Apache::loncommon::end_data_table().'
 5664: ');
 5665:     }
 5666: 
 5667:     # Chunk of form to prompt for a file to grade and how:
 5668: 
 5669:     $result.= '
 5670:     <br />
 5671:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5672:     <input type="hidden" name="command" value="scantron_warning" />
 5673:     '.$default_form_data.'
 5674:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5675:        '.&Apache::loncommon::start_data_table_header_row().'
 5676:             <th colspan="2">
 5677:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5678:             </th>
 5679:        '.&Apache::loncommon::end_data_table_header_row().'
 5680:        '.&Apache::loncommon::start_data_table_row().'
 5681:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5682:        '.&Apache::loncommon::end_data_table_row().'
 5683:        '.&Apache::loncommon::start_data_table_row().'
 5684:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5685:        '.&Apache::loncommon::end_data_table_row().'
 5686:        '.&Apache::loncommon::start_data_table_row().'
 5687:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5688:        '.&Apache::loncommon::end_data_table_row().'
 5689:        '.&Apache::loncommon::start_data_table_row().'
 5690:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5691:        '.&Apache::loncommon::end_data_table_row().'
 5692:        '.&Apache::loncommon::start_data_table_row().'
 5693:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5694:        '.&Apache::loncommon::end_data_table_row().'
 5695:        '.&Apache::loncommon::start_data_table_row().'
 5696: 	    <td> '.&mt('Options:').' </td>
 5697:             <td>
 5698: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5699:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5700:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5701: 	    </td>
 5702:        '.&Apache::loncommon::end_data_table_row().'
 5703:        '.&Apache::loncommon::start_data_table_row().'
 5704:             <td colspan="2">
 5705:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5706:             </td>
 5707:        '.&Apache::loncommon::end_data_table_row().'
 5708:     '.&Apache::loncommon::end_data_table().'
 5709:     </form>
 5710: ';
 5711:    
 5712:     $r->print($result);
 5713: 
 5714:     # Chunk of the form that prompts to view a scoring office file,
 5715:     # corrected file, skipped records in a file.
 5716: 
 5717:     $r->print('
 5718:    <br />
 5719:    <form action="/adm/grades" name="scantron_download">
 5720:      '.$default_form_data.'
 5721:      <input type="hidden" name="command" value="scantron_download" />
 5722:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5723:        '.&Apache::loncommon::start_data_table_header_row().'
 5724:               <th>
 5725:                 &nbsp;'.&mt('Download a scoring office file').'
 5726:               </th>
 5727:        '.&Apache::loncommon::end_data_table_header_row().'
 5728:        '.&Apache::loncommon::start_data_table_row().'
 5729:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5730:                 <br />
 5731:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5732:        '.&Apache::loncommon::end_data_table_row().'
 5733:      '.&Apache::loncommon::end_data_table().'
 5734:    </form>
 5735:    <br />
 5736: ');
 5737: 
 5738:     &Apache::lonpickcode::code_list($r,2);
 5739: 
 5740:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5741:              $default_form_data."\n".
 5742:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5743:              &Apache::loncommon::start_data_table_header_row()."\n".
 5744:              '<th colspan="2">
 5745:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5746:              '</th>'."\n".
 5747:               &Apache::loncommon::end_data_table_header_row()."\n".
 5748:               &Apache::loncommon::start_data_table_row()."\n".
 5749:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5750:               '<td> '.$sequence_selector.' </td>'.
 5751:               &Apache::loncommon::end_data_table_row()."\n".
 5752:               &Apache::loncommon::start_data_table_row()."\n".
 5753:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5754:               '<td> '.$file_selector.' </td>'."\n".
 5755:               &Apache::loncommon::end_data_table_row()."\n".
 5756:               &Apache::loncommon::start_data_table_row()."\n".
 5757:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5758:               '<td> '.$format_selector.' </td>'."\n".
 5759:               &Apache::loncommon::end_data_table_row()."\n".
 5760:               &Apache::loncommon::start_data_table_row()."\n".
 5761:               '<td> '.&mt('Options').' </td>'."\n".
 5762:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5763:               &Apache::loncommon::end_data_table_row()."\n".
 5764:               &Apache::loncommon::start_data_table_row()."\n".
 5765:               '<td colspan="2">'."\n".
 5766:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5767:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5768:               '</td>'."\n".
 5769:               &Apache::loncommon::end_data_table_row()."\n".
 5770:               &Apache::loncommon::end_data_table()."\n".
 5771:               '</form><br />');
 5772:     $r->print($grading_menu_button);
 5773:     return;
 5774: }
 5775: 
 5776: =pod
 5777: 
 5778: =item get_scantron_config
 5779: 
 5780:    Parse and return the scantron configuration line selected as a
 5781:    hash of configuration file fields.
 5782: 
 5783:  Arguments:
 5784:     which - the name of the configuration to parse from the file.
 5785: 
 5786: 
 5787:  Returns:
 5788:             If the named configuration is not in the file, an empty
 5789:             hash is returned.
 5790:     a hash with the fields
 5791:       name         - internal name for the this configuration setup
 5792:       description  - text to display to operator that describes this config
 5793:       CODElocation - if 0 or the string 'none'
 5794:                           - no CODE exists for this config
 5795:                      if -1 || the string 'letter'
 5796:                           - a CODE exists for this config and is
 5797:                             a string of letters
 5798:                      Unsupported value (but planned for future support)
 5799:                           if a positive integer
 5800:                                - The CODE exists as the first n items from
 5801:                                  the question section of the form
 5802:                           if the string 'number'
 5803:                                - The CODE exists for this config and is
 5804:                                  a string of numbers
 5805:       CODEstart   - (only matter if a CODE exists) column in the line where
 5806:                      the CODE starts
 5807:       CODElength  - length of the CODE
 5808:       IDstart     - column where the student/employee ID starts
 5809:       IDlength    - length of the student/employee ID info
 5810:       Qstart      - column where the information from the bubbled
 5811:                     'questions' start
 5812:       Qlength     - number of columns comprising a single bubble line from
 5813:                     the sheet. (usually either 1 or 10)
 5814:       Qon         - either a single character representing the character used
 5815:                     to signal a bubble was chosen in the positional setup, or
 5816:                     the string 'letter' if the letter of the chosen bubble is
 5817:                     in the final, or 'number' if a number representing the
 5818:                     chosen bubble is in the file (1->A 0->J)
 5819:       Qoff        - the character used to represent that a bubble was
 5820:                     left blank
 5821:       PaperID     - if the scanning process generates a unique number for each
 5822:                     sheet scanned the column that this ID number starts in
 5823:       PaperIDlength - number of columns that comprise the unique ID number
 5824:                       for the sheet of paper
 5825:       FirstName   - column that the first name starts in
 5826:       FirstNameLength - number of columns that the first name spans
 5827:  
 5828:       LastName    - column that the last name starts in
 5829:       LastNameLength - number of columns that the last name spans
 5830:       BubblesPerRow - number of bubbles available in each row used to
 5831:                       bubble an answer. (If not specified, 10 assumed).
 5832: 
 5833: =cut
 5834: 
 5835: sub get_scantron_config {
 5836:     my ($which) = @_;
 5837:     my @lines = &get_scantronformat_file();
 5838:     my %config;
 5839:     #FIXME probably should move to XML it has already gotten a bit much now
 5840:     foreach my $line (@lines) {
 5841: 	my ($name,$descrip)=split(/:/,$line);
 5842: 	if ($name ne $which ) { next; }
 5843: 	chomp($line);
 5844: 	my @config=split(/:/,$line);
 5845: 	$config{'name'}=$config[0];
 5846: 	$config{'description'}=$config[1];
 5847: 	$config{'CODElocation'}=$config[2];
 5848: 	$config{'CODEstart'}=$config[3];
 5849: 	$config{'CODElength'}=$config[4];
 5850: 	$config{'IDstart'}=$config[5];
 5851: 	$config{'IDlength'}=$config[6];
 5852: 	$config{'Qstart'}=$config[7];
 5853:  	$config{'Qlength'}=$config[8];
 5854: 	$config{'Qoff'}=$config[9];
 5855: 	$config{'Qon'}=$config[10];
 5856: 	$config{'PaperID'}=$config[11];
 5857: 	$config{'PaperIDlength'}=$config[12];
 5858: 	$config{'FirstName'}=$config[13];
 5859: 	$config{'FirstNamelength'}=$config[14];
 5860: 	$config{'LastName'}=$config[15];
 5861: 	$config{'LastNamelength'}=$config[16];
 5862:         $config{'BubblesPerRow'}=$config[17];
 5863: 	last;
 5864:     }
 5865:     return %config;
 5866: }
 5867: 
 5868: =pod 
 5869: 
 5870: =item username_to_idmap
 5871: 
 5872:     creates a hash keyed by student/employee ID with values of the corresponding
 5873:     student username:domain.
 5874: 
 5875:   Arguments:
 5876: 
 5877:     $classlist - reference to the class list hash. This is a hash
 5878:                  keyed by student name:domain  whose elements are references
 5879:                  to arrays containing various chunks of information
 5880:                  about the student. (See loncoursedata for more info).
 5881: 
 5882:   Returns
 5883:     %idmap - the constructed hash
 5884: 
 5885: =cut
 5886: 
 5887: sub username_to_idmap {
 5888:     my ($classlist)= @_;
 5889:     my %idmap;
 5890:     foreach my $student (keys(%$classlist)) {
 5891: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5892: 	    $student;
 5893:     }
 5894:     return %idmap;
 5895: }
 5896: 
 5897: =pod
 5898: 
 5899: =item scantron_fixup_scanline
 5900: 
 5901:    Process a requested correction to a scanline.
 5902: 
 5903:   Arguments:
 5904:     $scantron_config   - hash from &get_scantron_config()
 5905:     $scan_data         - hash of correction information 
 5906:                           (see &scantron_getfile())
 5907:     $line              - existing scanline
 5908:     $whichline         - line number of the passed in scanline
 5909:     $field             - type of change to process 
 5910:                          (either 
 5911:                           'ID'     -> correct the student/employee ID
 5912:                           'CODE'   -> correct the CODE
 5913:                           'answer' -> fixup the submitted answers)
 5914:     
 5915:    $args               - hash of additional info,
 5916:                           - 'ID' 
 5917:                                'newid' -> studentID to use in replacement
 5918:                                           of existing one
 5919:                           - 'CODE' 
 5920:                                'CODE_ignore_dup' - set to true if duplicates
 5921:                                                    should be ignored.
 5922: 	                       'CODE' - is new code or 'use_unfound'
 5923:                                         if the existing unfound code should
 5924:                                         be used as is
 5925:                           - 'answer'
 5926:                                'response' - new answer or 'none' if blank
 5927:                                'question' - the bubble line to change
 5928:                                'questionnum' - the question identifier,
 5929:                                                may include subquestion. 
 5930: 
 5931:   Returns:
 5932:     $line - the modified scanline
 5933: 
 5934:   Side effects: 
 5935:     $scan_data - may be updated
 5936: 
 5937: =cut
 5938: 
 5939: 
 5940: sub scantron_fixup_scanline {
 5941:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5942:     if ($field eq 'ID') {
 5943: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5944: 	    return ($line,1,'New value too large');
 5945: 	}
 5946: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5947: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5948: 				     $args->{'newid'});
 5949: 	}
 5950: 	substr($line,$$scantron_config{'IDstart'}-1,
 5951: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5952: 	if ($args->{'newid'}=~/^\s*$/) {
 5953: 	    &scan_data($scan_data,"$whichline.user",
 5954: 		       $args->{'username'}.':'.$args->{'domain'});
 5955: 	}
 5956:     } elsif ($field eq 'CODE') {
 5957: 	if ($args->{'CODE_ignore_dup'}) {
 5958: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5959: 	}
 5960: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5961: 	if ($args->{'CODE'} ne 'use_unfound') {
 5962: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5963: 		return ($line,1,'New CODE value too large');
 5964: 	    }
 5965: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5966: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5967: 	    }
 5968: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5969: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5970: 	}
 5971:     } elsif ($field eq 'answer') {
 5972: 	my $length=$scantron_config->{'Qlength'};
 5973: 	my $off=$scantron_config->{'Qoff'};
 5974: 	my $on=$scantron_config->{'Qon'};
 5975: 	my $answer=${off}x$length;
 5976: 	if ($args->{'response'} eq 'none') {
 5977: 	    &scan_data($scan_data,
 5978: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5979: 	} else {
 5980: 	    if ($on eq 'letter') {
 5981: 		my @alphabet=('A'..'Z');
 5982: 		$answer=$alphabet[$args->{'response'}];
 5983: 	    } elsif ($on eq 'number') {
 5984: 		$answer=$args->{'response'}+1;
 5985: 		if ($answer == 10) { $answer = '0'; }
 5986: 	    } else {
 5987: 		substr($answer,$args->{'response'},1)=$on;
 5988: 	    }
 5989: 	    &scan_data($scan_data,
 5990: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5991: 	}
 5992: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5993: 	substr($line,$where-1,$length)=$answer;
 5994:     }
 5995:     return $line;
 5996: }
 5997: 
 5998: =pod
 5999: 
 6000: =item scan_data
 6001: 
 6002:     Edit or look up  an item in the scan_data hash.
 6003: 
 6004:   Arguments:
 6005:     $scan_data  - The hash (see scantron_getfile)
 6006:     $key        - shorthand of the key to edit (actual key is
 6007:                   scantronfilename_key).
 6008:     $data        - New value of the hash entry.
 6009:     $delete      - If true, the entry is removed from the hash.
 6010: 
 6011:   Returns:
 6012:     The new value of the hash table field (undefined if deleted).
 6013: 
 6014: =cut
 6015: 
 6016: 
 6017: sub scan_data {
 6018:     my ($scan_data,$key,$value,$delete)=@_;
 6019:     my $filename=$env{'form.scantron_selectfile'};
 6020:     if (defined($value)) {
 6021: 	$scan_data->{$filename.'_'.$key} = $value;
 6022:     }
 6023:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6024:     return $scan_data->{$filename.'_'.$key};
 6025: }
 6026: 
 6027: # ----- These first few routines are general use routines.----
 6028: 
 6029: # Return the number of occurences of a pattern in a string.
 6030: 
 6031: sub occurence_count {
 6032:     my ($string, $pattern) = @_;
 6033: 
 6034:     my @matches = ($string =~ /$pattern/g);
 6035: 
 6036:     return scalar(@matches);
 6037: }
 6038: 
 6039: 
 6040: # Take a string known to have digits and convert all the
 6041: # digits into letters in the range J,A..I.
 6042: 
 6043: sub digits_to_letters {
 6044:     my ($input) = @_;
 6045: 
 6046:     my @alphabet = ('J', 'A'..'I');
 6047: 
 6048:     my @input    = split(//, $input);
 6049:     my $output ='';
 6050:     for (my $i = 0; $i < scalar(@input); $i++) {
 6051: 	if ($input[$i] =~ /\d/) {
 6052: 	    $output .= $alphabet[$input[$i]];
 6053: 	} else {
 6054: 	    $output .= $input[$i];
 6055: 	}
 6056:     }
 6057:     return $output;
 6058: }
 6059: 
 6060: =pod 
 6061: 
 6062: =item scantron_parse_scanline
 6063: 
 6064:   Decodes a scanline from the selected scantron file
 6065: 
 6066:  Arguments:
 6067:     line             - The text of the scantron file line to process
 6068:     whichline        - Line number
 6069:     scantron_config  - Hash describing the format of the scantron lines.
 6070:     scan_data        - Hash of extra information about the scanline
 6071:                        (see scantron_getfile for more information)
 6072:     just_header      - True if should not process question answers but only
 6073:                        the stuff to the left of the answers.
 6074:     randomorder      - True if randomorder in use
 6075:     randompick       - True if randompick in use
 6076:     sequence         - Exam folder URL
 6077:     master_seq       - Ref to array containing symbs in exam folder
 6078:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6079:                        (corresponding values are resource objects)
 6080:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6081:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6082:                        are refs to an array of resource objects, ordered
 6083:                        according to order used for CODE, when randomorder
 6084:                        and or randompick are in use.
 6085:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6086:                        for current line to question number used for same question
 6087:                         in "Master Sequence" (as seen by Course Coordinator).
 6088:     startline        - Ref to hash where key is question number (0 is first)
 6089:                        and value is number of first bubble line for current 
 6090:                        student or code-based randompick and/or randomorder.
 6091:     totalref         - Ref of scalar used to score total number of bubble
 6092:                        lines needed for responses in a scan line (used when
 6093:                        randompick in use. 
 6094: 
 6095:  Returns:
 6096:    Hash containing the result of parsing the scanline
 6097: 
 6098:    Keys are all proceeded by the string 'scantron.'
 6099: 
 6100:        CODE    - the CODE in use for this scanline
 6101:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6102:                  by the operator
 6103:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6104:                             CODEs were selected, but the usage has been
 6105:                             forced by the operator
 6106:        ID  - student/employee ID
 6107:        PaperID - if used, the ID number printed on the sheet when the 
 6108:                  paper was scanned
 6109:        FirstName - first name from the sheet
 6110:        LastName  - last name from the sheet
 6111: 
 6112:      if just_header was not true these key may also exist
 6113: 
 6114:        missingerror - a list of bubble ranges that are considered to be answers
 6115:                       to a single question that don't have any bubbles filled in.
 6116:                       Of the form questionnumber:firstbubblenumber:count.
 6117:        doubleerror  - a list of bubble ranges that are considered to be answers
 6118:                       to a single question that have more than one bubble filled in.
 6119:                       Of the form questionnumber::firstbubblenumber:count
 6120:    
 6121:                 In the above, count is the number of bubble responses in the
 6122:                 input line needed to represent the possible answers to the question.
 6123:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6124:                 per line would have count = 2.
 6125: 
 6126:        maxquest     - the number of the last bubble line that was parsed
 6127: 
 6128:        (<number> starts at 1)
 6129:        <number>.answer - zero or more letters representing the selected
 6130:                          letters from the scanline for the bubble line 
 6131:                          <number>.
 6132:                          if blank there was either no bubble or there where
 6133:                          multiple bubbles, (consult the keys missingerror and
 6134:                          doubleerror if this is an error condition)
 6135: 
 6136: =cut
 6137: 
 6138: sub scantron_parse_scanline {
 6139:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6140:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6141:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6142: 
 6143:     my %record;
 6144:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6145:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6146: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6147: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6148: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6149: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6150: 	    $record{'scantron.CODE'}=substr($data,
 6151: 					    $$scantron_config{'CODEstart'}-1,
 6152: 					    $$scantron_config{'CODElength'});
 6153: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6154: 		$record{'scantron.useCODE'}=1;
 6155: 	    }
 6156: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6157: 		$record{'scantron.CODE_ignore_dup'}=1;
 6158: 	    }
 6159: 	} else {
 6160: 	    #FIXME interpret first N questions
 6161: 	}
 6162:     }
 6163:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6164: 				  $$scantron_config{'IDlength'});
 6165:     $record{'scantron.PaperID'}=
 6166: 	substr($data,$$scantron_config{'PaperID'}-1,
 6167: 	       $$scantron_config{'PaperIDlength'});
 6168:     $record{'scantron.FirstName'}=
 6169: 	substr($data,$$scantron_config{'FirstName'}-1,
 6170: 	       $$scantron_config{'FirstNamelength'});
 6171:     $record{'scantron.LastName'}=
 6172: 	substr($data,$$scantron_config{'LastName'}-1,
 6173: 	       $$scantron_config{'LastNamelength'});
 6174:     if ($just_header) { return \%record; }
 6175: 
 6176:     my @alphabet=('A'..'Z');
 6177:     my $questnum=0;
 6178:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6179: 
 6180:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6181:     if ($randompick || $randomorder) {
 6182:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6183:                                          $master_seq,$symb_to_resource,
 6184:                                          $partids_by_symb,$orderedforcode,
 6185:                                          $respnumlookup,$startline);
 6186:         if ($total) {
 6187:             $lastpos = $total*$$scantron_config{'Qlength'};
 6188:         }
 6189:         if (ref($totalref)) {
 6190:             $$totalref = $total;
 6191:         }
 6192:     }
 6193:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6194:     chomp($questions);		# Get rid of any trailing \n.
 6195:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6196:     while (length($questions)) {
 6197:         my $answers_needed;
 6198:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6199:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6200:         } else {
 6201:             $answers_needed = $bubble_lines_per_response{$questnum};
 6202:         }
 6203:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6204:                              || 1;
 6205:         $questnum++;
 6206:         my $quest_id = $questnum;
 6207:         my $currentquest = substr($questions,0,$answer_length);
 6208:         $questions       = substr($questions,$answer_length);
 6209:         if (length($currentquest) < $answer_length) { next; }
 6210: 
 6211:         my $subdivided;
 6212:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6213:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6214:         } else {
 6215:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6216:         }
 6217:         if ($subdivided =~ /,/) {
 6218:             my $subquestnum = 1;
 6219:             my $subquestions = $currentquest;
 6220:             my @subanswers_needed = split(/,/,$subdivided);
 6221:             foreach my $subans (@subanswers_needed) {
 6222:                 my $subans_length =
 6223:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6224:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6225:                 $subquestions   = substr($subquestions,$subans_length);
 6226:                 $quest_id = "$questnum.$subquestnum";
 6227:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6228:                     ($$scantron_config{'Qon'} eq 'number')) {
 6229:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6230:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6231:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6232:                         $randomorder,$randompick,$respnumlookup);
 6233:                 } else {
 6234:                     $ansnum = &scantron_validator_positional($ansnum,
 6235:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6236:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6237:                         $randomorder,$randompick,$respnumlookup);
 6238:                 }
 6239:                 $subquestnum ++;
 6240:             }
 6241:         } else {
 6242:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6243:                 ($$scantron_config{'Qon'} eq 'number')) {
 6244:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6245:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6246:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6247:                     $randomorder,$randompick,$respnumlookup);
 6248:             } else {
 6249:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6250:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6251:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6252:                     $randomorder,$randompick,$respnumlookup);
 6253:             }
 6254:         }
 6255:     }
 6256:     $record{'scantron.maxquest'}=$questnum;
 6257:     return \%record;
 6258: }
 6259: 
 6260: sub get_master_seq {
 6261:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6262:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6263:                    (ref($symb_to_resource) eq 'HASH'));
 6264:     my $resource_error;
 6265:     foreach my $resource (@{$resources}) {
 6266:         my $ressymb;
 6267:         if (ref($resource)) {
 6268:             $ressymb = $resource->symb();
 6269:             push(@{$master_seq},$ressymb);
 6270:             $symb_to_resource->{$ressymb} = $resource;
 6271:         } else {
 6272:             $resource_error = 1;
 6273:             last;
 6274:         }
 6275:     }
 6276:     return $resource_error;
 6277: }
 6278: 
 6279: sub get_respnum_lookups {
 6280:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6281:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6282:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6283:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6284:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6285:                    (ref($startline) eq 'HASH'));
 6286:     my ($user,$scancode);
 6287:     if ((exists($record->{'scantron.CODE'})) &&
 6288:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6289:         $scancode = $record->{'scantron.CODE'};
 6290:     } else {
 6291:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6292:     }
 6293:     my @mapresources =
 6294:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6295:                      $orderedforcode);
 6296:     my $total = 0;
 6297:     my $count = 0;
 6298:     foreach my $resource (@mapresources) {
 6299:         my $id = $resource->id();
 6300:         my $symb = $resource->symb();
 6301:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6302:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6303:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6304:                 if ($respnum ne '') {
 6305:                     $respnumlookup->{$count} = $respnum;
 6306:                     $startline->{$count} = $total;
 6307:                     $total += $bubble_lines_per_response{$respnum};
 6308:                     $count ++;
 6309:                 }
 6310:             }
 6311:         }
 6312:     }
 6313:     return $total;
 6314: }
 6315: 
 6316: sub scantron_validator_lettnum {
 6317:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6318:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6319:         $randompick,$respnumlookup) = @_;
 6320: 
 6321:     # Qon 'letter' implies for each slot in currquest we have:
 6322:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6323:     #    about anything else (esp. a value of Qoff) for missing
 6324:     #    bubbles.
 6325:     #
 6326:     # Qon 'number' implies each slot gives a digit that indexes the
 6327:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6328:     #    and * or ? for double bubbles on a single line.
 6329:     #
 6330: 
 6331:     my $matchon;
 6332:     if ($$scantron_config{'Qon'} eq 'letter') {
 6333:         $matchon = '[A-Z]';
 6334:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6335:         $matchon = '\d';
 6336:     }
 6337:     my $occurrences = 0;
 6338:     my $responsenum = $questnum-1;
 6339:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6340:        $responsenum = $respnumlookup->{$questnum-1}
 6341:     }
 6342:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6343:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6344:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6345:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6346:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6347:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6348:         my @singlelines = split('',$currquest);
 6349:         foreach my $entry (@singlelines) {
 6350:             $occurrences = &occurence_count($entry,$matchon);
 6351:             if ($occurrences > 1) {
 6352:                 last;
 6353:             }
 6354:         }
 6355:     } else {
 6356:         $occurrences = &occurence_count($currquest,$matchon); 
 6357:     }
 6358:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6359:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6360:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6361:             my $bubble = substr($currquest,$ans,1);
 6362:             if ($bubble =~ /$matchon/ ) {
 6363:                 if ($$scantron_config{'Qon'} eq 'number') {
 6364:                     if ($bubble == 0) {
 6365:                         $bubble = 10; 
 6366:                     }
 6367:                     $record->{"scantron.$ansnum.answer"} = 
 6368:                         $alphabet->[$bubble-1];
 6369:                 } else {
 6370:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6371:                 }
 6372:             } else {
 6373:                 $record->{"scantron.$ansnum.answer"}='';
 6374:             }
 6375:             $ansnum++;
 6376:         }
 6377:     } elsif (!defined($currquest)
 6378:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6379:             || (&occurence_count($currquest,$matchon) == 0)) {
 6380:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6381:             $record->{"scantron.$ansnum.answer"}='';
 6382:             $ansnum++;
 6383:         }
 6384:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6385:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6386:         }
 6387:     } else {
 6388:         if ($$scantron_config{'Qon'} eq 'number') {
 6389:             $currquest = &digits_to_letters($currquest);            
 6390:         }
 6391:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6392:             my $bubble = substr($currquest,$ans,1);
 6393:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6394:             $ansnum++;
 6395:         }
 6396:     }
 6397:     return $ansnum;
 6398: }
 6399: 
 6400: sub scantron_validator_positional {
 6401:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6402:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6403:         $randomorder,$randompick,$respnumlookup) = @_;
 6404: 
 6405:     # Otherwise there's a positional notation;
 6406:     # each bubble line requires Qlength items, and there are filled in
 6407:     # bubbles for each case where there 'Qon' characters.
 6408:     #
 6409: 
 6410:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6411: 
 6412:     # If the split only gives us one element.. the full length of the
 6413:     # answer string, no bubbles are filled in:
 6414: 
 6415:     if ($answers_needed eq '') {
 6416:         return;
 6417:     }
 6418: 
 6419:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6420:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6421:             $record->{"scantron.$ansnum.answer"}='';
 6422:             $ansnum++;
 6423:         }
 6424:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6425:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6426:         }
 6427:     } elsif (scalar(@array) == 2) {
 6428:         my $location = length($array[0]);
 6429:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6430:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6431:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6432:             if ($ans eq $line_num) {
 6433:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6434:             } else {
 6435:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6436:             }
 6437:             $ansnum++;
 6438:          }
 6439:     } else {
 6440:         #  If there's more than one instance of a bubble character
 6441:         #  That's a double bubble; with positional notation we can
 6442:         #  record all the bubbles filled in as well as the
 6443:         #  fact this response consists of multiple bubbles.
 6444:         #
 6445:         my $responsenum = $questnum-1;
 6446:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6447:             $responsenum = $respnumlookup->{$questnum-1}
 6448:         }
 6449:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6450:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6451:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6452:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6453:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6454:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6455:             my $doubleerror = 0;
 6456:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6457:                    (!$doubleerror)) {
 6458:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6459:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6460:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6461:                if (length(@currarray) > 2) {
 6462:                    $doubleerror = 1;
 6463:                } 
 6464:             }
 6465:             if ($doubleerror) {
 6466:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6467:             }
 6468:         } else {
 6469:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6470:         }
 6471:         my $item = $ansnum;
 6472:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6473:             $record->{"scantron.$item.answer"} = '';
 6474:             $item ++;
 6475:         }
 6476: 
 6477:         my @ans=@array;
 6478:         my $i=0;
 6479:         my $increment = 0;
 6480:         while ($#ans) {
 6481:             $i+=length($ans[0]) + $increment;
 6482:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6483:             my $bubble = $i%$$scantron_config{'Qlength'};
 6484:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6485:             shift(@ans);
 6486:             $increment = 1;
 6487:         }
 6488:         $ansnum += $answers_needed;
 6489:     }
 6490:     return $ansnum;
 6491: }
 6492: 
 6493: =pod
 6494: 
 6495: =item scantron_add_delay
 6496: 
 6497:    Adds an error message that occurred during the grading phase to a
 6498:    queue of messages to be shown after grading pass is complete
 6499: 
 6500:  Arguments:
 6501:    $delayqueue  - arrary ref of hash ref of error messages
 6502:    $scanline    - the scanline that caused the error
 6503:    $errormesage - the error message
 6504:    $errorcode   - a numeric code for the error
 6505: 
 6506:  Side Effects:
 6507:    updates the $delayqueue to have a new hash ref of the error
 6508: 
 6509: =cut
 6510: 
 6511: sub scantron_add_delay {
 6512:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6513:     push(@$delayqueue,
 6514: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6515: 	  'ecode' => $errorcode }
 6516: 	 );
 6517: }
 6518: 
 6519: =pod
 6520: 
 6521: =item scantron_find_student
 6522: 
 6523:    Finds the username for the current scanline
 6524: 
 6525:   Arguments:
 6526:    $scantron_record - hash result from scantron_parse_scanline
 6527:    $scan_data       - hash of correction information 
 6528:                       (see &scantron_getfile() form more information)
 6529:    $idmap           - hash from &username_to_idmap()
 6530:    $line            - number of current scanline
 6531:  
 6532:   Returns:
 6533:    Either 'username:domain' or undef if unknown
 6534: 
 6535: =cut
 6536: 
 6537: sub scantron_find_student {
 6538:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6539:     my $scanID=$$scantron_record{'scantron.ID'};
 6540:     if ($scanID =~ /^\s*$/) {
 6541:  	return &scan_data($scan_data,"$line.user");
 6542:     }
 6543:     foreach my $id (keys(%$idmap)) {
 6544:  	if (lc($id) eq lc($scanID)) {
 6545:  	    return $$idmap{$id};
 6546:  	}
 6547:     }
 6548:     return undef;
 6549: }
 6550: 
 6551: =pod
 6552: 
 6553: =item scantron_filter
 6554: 
 6555:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6556:    hidden resources was selected
 6557: 
 6558: =cut
 6559: 
 6560: sub scantron_filter {
 6561:     my ($curres)=@_;
 6562: 
 6563:     if (ref($curres) && $curres->is_problem()) {
 6564: 	# if the user has asked to not have either hidden
 6565: 	# or 'randomout' controlled resources to be graded
 6566: 	# don't include them
 6567: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6568: 	    && $curres->randomout) {
 6569: 	    return 0;
 6570: 	}
 6571: 	return 1;
 6572:     }
 6573:     return 0;
 6574: }
 6575: 
 6576: =pod
 6577: 
 6578: =item scantron_process_corrections
 6579: 
 6580:    Gets correction information out of submitted form data and corrects
 6581:    the scanline
 6582: 
 6583: =cut
 6584: 
 6585: sub scantron_process_corrections {
 6586:     my ($r) = @_;
 6587:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6588:     my ($scanlines,$scan_data)=&scantron_getfile();
 6589:     my $classlist=&Apache::loncoursedata::get_classlist();
 6590:     my $which=$env{'form.scantron_line'};
 6591:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6592:     my ($skip,$err,$errmsg);
 6593:     if ($env{'form.scantron_skip_record'}) {
 6594: 	$skip=1;
 6595:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6596: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6597: 	    $env{'form.scantron_domain'};
 6598: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6599: 	($line,$err,$errmsg)=
 6600: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6601: 				     'ID',{'newid'=>$newid,
 6602: 				    'username'=>$env{'form.scantron_username'},
 6603: 				    'domain'=>$env{'form.scantron_domain'}});
 6604:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6605: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6606: 	my $newCODE;
 6607: 	my %args;
 6608: 	if      ($resolution eq 'use_unfound') {
 6609: 	    $newCODE='use_unfound';
 6610: 	} elsif ($resolution eq 'use_found') {
 6611: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6612: 	} elsif ($resolution eq 'use_typed') {
 6613: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6614: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6615: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6616: 	}
 6617: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6618: 	    $args{'CODE_ignore_dup'}=1;
 6619: 	}
 6620: 	$args{'CODE'}=$newCODE;
 6621: 	($line,$err,$errmsg)=
 6622: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6623: 				     'CODE',\%args);
 6624:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6625: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6626: 	    ($line,$err,$errmsg)=
 6627: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6628: 					 $which,'answer',
 6629: 					 { 'question'=>$question,
 6630: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6631:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6632: 	    if ($err) { last; }
 6633: 	}
 6634:     }
 6635:     if ($err) {
 6636: 	$r->print(
 6637:             '<p class="LC_error">'
 6638:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6639:                 $errmsg)
 6640:            .'</p>');
 6641:     } else {
 6642: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6643: 	&scantron_putfile($scanlines,$scan_data);
 6644:     }
 6645: }
 6646: 
 6647: =pod
 6648: 
 6649: =item reset_skipping_status
 6650: 
 6651:    Forgets the current set of remember skipped scanlines (and thus
 6652:    reverts back to considering all lines in the
 6653:    scantron_skipped_<filename> file)
 6654: 
 6655: =cut
 6656: 
 6657: sub reset_skipping_status {
 6658:     my ($scanlines,$scan_data)=&scantron_getfile();
 6659:     &scan_data($scan_data,'remember_skipping',undef,1);
 6660:     &scantron_putfile(undef,$scan_data);
 6661: }
 6662: 
 6663: =pod
 6664: 
 6665: =item start_skipping
 6666: 
 6667:    Marks a scanline to be skipped. 
 6668: 
 6669: =cut
 6670: 
 6671: sub start_skipping {
 6672:     my ($scan_data,$i)=@_;
 6673:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6674:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6675: 	$remembered{$i}=2;
 6676:     } else {
 6677: 	$remembered{$i}=1;
 6678:     }
 6679:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6680: }
 6681: 
 6682: =pod
 6683: 
 6684: =item should_be_skipped
 6685: 
 6686:    Checks whether a scanline should be skipped.
 6687: 
 6688: =cut
 6689: 
 6690: sub should_be_skipped {
 6691:     my ($scanlines,$scan_data,$i)=@_;
 6692:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6693: 	# not redoing old skips
 6694: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6695: 	return 0;
 6696:     }
 6697:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6698: 
 6699:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6700: 	return 0;
 6701:     }
 6702:     return 1;
 6703: }
 6704: 
 6705: =pod
 6706: 
 6707: =item remember_current_skipped
 6708: 
 6709:    Discovers what scanlines are in the scantron_skipped_<filename>
 6710:    file and remembers them into scan_data for later use.
 6711: 
 6712: =cut
 6713: 
 6714: sub remember_current_skipped {
 6715:     my ($scanlines,$scan_data)=&scantron_getfile();
 6716:     my %to_remember;
 6717:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6718: 	if ($scanlines->{'skipped'}[$i]) {
 6719: 	    $to_remember{$i}=1;
 6720: 	}
 6721:     }
 6722: 
 6723:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6724:     &scantron_putfile(undef,$scan_data);
 6725: }
 6726: 
 6727: =pod
 6728: 
 6729: =item check_for_error
 6730: 
 6731:     Checks if there was an error when attempting to remove a specific
 6732:     scantron_.. bubblesheet data file. Prints out an error if
 6733:     something went wrong.
 6734: 
 6735: =cut
 6736: 
 6737: sub check_for_error {
 6738:     my ($r,$result)=@_;
 6739:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6740: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6741:     }
 6742: }
 6743: 
 6744: =pod
 6745: 
 6746: =item scantron_warning_screen
 6747: 
 6748:    Interstitial screen to make sure the operator has selected the
 6749:    correct options before we start the validation phase.
 6750: 
 6751: =cut
 6752: 
 6753: sub scantron_warning_screen {
 6754:     my ($button_text)=@_;
 6755:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6756:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6757:     my $CODElist;
 6758:     if ($scantron_config{'CODElocation'} &&
 6759: 	$scantron_config{'CODEstart'} &&
 6760: 	$scantron_config{'CODElength'}) {
 6761: 	$CODElist=$env{'form.scantron_CODElist'};
 6762: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6763: 	$CODElist=
 6764: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6765: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6766:     }
 6767:     my $lastbubblepoints;
 6768:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6769:         $lastbubblepoints =
 6770:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6771:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6772:     }
 6773:     return ('
 6774: <p>
 6775: <span class="LC_warning">
 6776: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6777: </p>
 6778: <table>
 6779: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6780: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6781: '.$CODElist.$lastbubblepoints.'
 6782: </table>
 6783: <br />
 6784: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 6785: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 6786: 
 6787: <br />
 6788: ');
 6789: }
 6790: 
 6791: =pod
 6792: 
 6793: =item scantron_do_warning
 6794: 
 6795:    Check if the operator has picked something for all required
 6796:    fields. Error out if something is missing.
 6797: 
 6798: =cut
 6799: 
 6800: sub scantron_do_warning {
 6801:     my ($r)=@_;
 6802:     my ($symb)=&get_symb($r);
 6803:     if (!$symb) {return '';}
 6804:     my $default_form_data=&defaultFormData($symb);
 6805:     $r->print(&scantron_form_start().$default_form_data);
 6806:     if ( $env{'form.selectpage'} eq '' ||
 6807: 	 $env{'form.scantron_selectfile'} eq '' ||
 6808: 	 $env{'form.scantron_format'} eq '' ) {
 6809: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6810: 	if ( $env{'form.selectpage'} eq '') {
 6811: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6812: 	} 
 6813: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6814: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6815: 	} 
 6816: 	if ( $env{'form.scantron_format'} eq '') {
 6817: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6818: 	} 
 6819:     } else {
 6820: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6821:         my $bubbledbyhand=&hand_bubble_option();
 6822: 	$r->print('
 6823: '.$warning.$bubbledbyhand.'
 6824: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6825: <input type="hidden" name="command" value="scantron_validate" />
 6826: ');
 6827:     }
 6828:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6829:     return '';
 6830: }
 6831: 
 6832: =pod
 6833: 
 6834: =item scantron_form_start
 6835: 
 6836:     html hidden input for remembering all selected grading options
 6837: 
 6838: =cut
 6839: 
 6840: sub scantron_form_start {
 6841:     my ($max_bubble)=@_;
 6842:     my $result= <<SCANTRONFORM;
 6843: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6844:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6845:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6846:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6847:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6848:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6849:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6850:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6851:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6852:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6853: SCANTRONFORM
 6854: 
 6855:   my $line = 0;
 6856:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6857:        my $chunk =
 6858: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6859:        $chunk .=
 6860: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6861:        $chunk .= 
 6862:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6863:        $chunk .=
 6864:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6865:        $chunk .=
 6866:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6867:        $result .= $chunk;
 6868:        $line++;
 6869:     }
 6870:     return $result;
 6871: }
 6872: 
 6873: =pod
 6874: 
 6875: =item scantron_validate_file
 6876: 
 6877:     Dispatch routine for doing validation of a bubblesheet data file.
 6878: 
 6879:     Also processes any necessary information resets that need to
 6880:     occur before validation begins (ignore previous corrections,
 6881:     restarting the skipped records processing)
 6882: 
 6883: =cut
 6884: 
 6885: sub scantron_validate_file {
 6886:     my ($r) = @_;
 6887:     my ($symb)=&get_symb($r);
 6888:     if (!$symb) {return '';}
 6889:     my $default_form_data=&defaultFormData($symb);
 6890:     
 6891:     # do the detection of only doing skipped records first before we delete
 6892:     # them when doing the corrections reset
 6893:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6894: 	&reset_skipping_status();
 6895:     }
 6896:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6897: 	&remember_current_skipped();
 6898: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6899:     }
 6900: 
 6901:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6902: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6903: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6904: 	&check_for_error($r,&scantron_remove_scan_data());
 6905: 	$env{'form.scantron_options_ignore'}='done';
 6906:     }
 6907: 
 6908:     if ($env{'form.scantron_corrections'}) {
 6909: 	&scantron_process_corrections($r);
 6910:     }
 6911:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6912:     #get the student pick code ready
 6913:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6914:     my $nav_error;
 6915:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6916:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6917:     if ($nav_error) {
 6918:         $r->print(&navmap_errormsg());
 6919:         return '';
 6920:     }
 6921:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6922:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6923:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6924:     }
 6925:     $r->print($result);
 6926:     
 6927:     my @validate_phases=( 'sequence',
 6928: 			  'ID',
 6929: 			  'CODE',
 6930: 			  'doublebubble',
 6931: 			  'missingbubbles');
 6932:     if (!$env{'form.validatepass'}) {
 6933: 	$env{'form.validatepass'} = 0;
 6934:     }
 6935:     my $currentphase=$env{'form.validatepass'};
 6936: 
 6937: 
 6938:     my $stop=0;
 6939:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6940: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6941: 	$r->rflush();
 6942: 
 6943: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6944: 	{
 6945: 	    no strict 'refs';
 6946: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6947: 	}
 6948:     }
 6949:     if (!$stop) {
 6950: 	my $warning=&scantron_warning_screen('Start Grading');
 6951: 	$r->print(&mt('Validation process complete.').'<br />'.
 6952:                   $warning.
 6953:                   &mt('Perform verification for each student after storage of submissions?').
 6954:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6955:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6956:                   ('&nbsp;'x3).'<label>'.
 6957:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6958:                   '</label></span><br />'.
 6959:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6960:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6961:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6962:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6963:     } else {
 6964: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6965: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6966:     }
 6967:     if ($stop) {
 6968: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6969: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6970: 	    $r->print(' '.&mt('this error').' <br />');
 6971: 
 6972: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6973: 	} else {
 6974:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6975: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6976:             } else {
 6977:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6978:             }
 6979: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6980: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6981: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6982: 	}
 6983:     }
 6984:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6985:     return '';
 6986: }
 6987: 
 6988: 
 6989: =pod
 6990: 
 6991: =item scantron_remove_file
 6992: 
 6993:    Removes the requested bubblesheet data file, makes sure that
 6994:    scantron_original_<filename> is never removed
 6995: 
 6996: 
 6997: =cut
 6998: 
 6999: sub scantron_remove_file {
 7000:     my ($which)=@_;
 7001:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7002:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7003:     my $file='scantron_';
 7004:     if ($which eq 'corrected' || $which eq 'skipped') {
 7005: 	$file.=$which.'_';
 7006:     } else {
 7007: 	return 'refused';
 7008:     }
 7009:     $file.=$env{'form.scantron_selectfile'};
 7010:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7011: }
 7012: 
 7013: 
 7014: =pod
 7015: 
 7016: =item scantron_remove_scan_data
 7017: 
 7018:    Removes all scan_data correction for the requested bubblesheet
 7019:    data file.  (In the case that both the are doing skipped records we need
 7020:    to remember the old skipped lines for the time being so that element
 7021:    persists for a while.)
 7022: 
 7023: =cut
 7024: 
 7025: sub scantron_remove_scan_data {
 7026:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7027:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7028:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7029:     my @todelete;
 7030:     my $filename=$env{'form.scantron_selectfile'};
 7031:     foreach my $key (@keys) {
 7032: 	if ($key=~/^\Q$filename\E_/) {
 7033: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7034: 		$key=~/remember_skipping/) {
 7035: 		next;
 7036: 	    }
 7037: 	    push(@todelete,$key);
 7038: 	}
 7039:     }
 7040:     my $result;
 7041:     if (@todelete) {
 7042: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7043: 				       \@todelete,$cdom,$cname);
 7044:     } else {
 7045: 	$result = 'ok';
 7046:     }
 7047:     return $result;
 7048: }
 7049: 
 7050: 
 7051: =pod
 7052: 
 7053: =item scantron_getfile
 7054: 
 7055:     Fetches the requested bubblesheet data file (all 3 versions), and
 7056:     the scan_data hash
 7057:   
 7058:   Arguments:
 7059:     None
 7060: 
 7061:   Returns:
 7062:     2 hash references
 7063: 
 7064:      - first one has 
 7065:          orig      -
 7066:          corrected -
 7067:          skipped   -  each of which points to an array ref of the specified
 7068:                       file broken up into individual lines
 7069:          count     - number of scanlines
 7070:  
 7071:      - second is the scan_data hash possible keys are
 7072:        ($number refers to scanline numbered $number and thus the key affects
 7073:         only that scanline
 7074:         $bubline refers to the specific bubble line element and the aspects
 7075:         refers to that specific bubble line element)
 7076: 
 7077:        $number.user - username:domain to use
 7078:        $number.CODE_ignore_dup 
 7079:                     - ignore the duplicate CODE error 
 7080:        $number.useCODE
 7081:                     - use the CODE in the scanline as is
 7082:        $number.no_bubble.$bubline
 7083:                     - it is valid that there is no bubbled in bubble
 7084:                       at $number $bubline
 7085:        remember_skipping
 7086:                     - a frozen hash containing keys of $number and values
 7087:                       of either 
 7088:                         1 - we are on a 'do skipped records pass' and plan
 7089:                             on processing this line
 7090:                         2 - we are on a 'do skipped records pass' and this
 7091:                             scanline has been marked to skip yet again
 7092: 
 7093: =cut
 7094: 
 7095: sub scantron_getfile {
 7096:     #FIXME really would prefer a scantron directory
 7097:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7098:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7099:     my $lines;
 7100:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7101: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7102:     my %scanlines;
 7103:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7104:     my $temp=$scanlines{'orig'};
 7105:     $scanlines{'count'}=$#$temp;
 7106: 
 7107:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7108: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7109:     if ($lines eq '-1') {
 7110: 	$scanlines{'corrected'}=[];
 7111:     } else {
 7112: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7113:     }
 7114:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7115: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7116:     if ($lines eq '-1') {
 7117: 	$scanlines{'skipped'}=[];
 7118:     } else {
 7119: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7120:     }
 7121:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7122:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7123:     my %scan_data = @tmp;
 7124:     return (\%scanlines,\%scan_data);
 7125: }
 7126: 
 7127: =pod
 7128: 
 7129: =item lonnet_putfile
 7130: 
 7131:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7132: 
 7133:  Arguments:
 7134:    $contents - data to store
 7135:    $filename - filename to store $contents into
 7136: 
 7137:  Returns:
 7138:    result value from &Apache::lonnet::finishuserfileupload
 7139: 
 7140: =cut
 7141: 
 7142: sub lonnet_putfile {
 7143:     my ($contents,$filename)=@_;
 7144:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7145:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7146:     $env{'form.sillywaytopassafilearound'}=$contents;
 7147:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7148: 
 7149: }
 7150: 
 7151: =pod
 7152: 
 7153: =item scantron_putfile
 7154: 
 7155:     Stores the current version of the bubblesheet data files, and the
 7156:     scan_data hash. (Does not modify the original version only the
 7157:     corrected and skipped versions.
 7158: 
 7159:  Arguments:
 7160:     $scanlines - hash ref that looks like the first return value from
 7161:                  &scantron_getfile()
 7162:     $scan_data - hash ref that looks like the second return value from
 7163:                  &scantron_getfile()
 7164: 
 7165: =cut
 7166: 
 7167: sub scantron_putfile {
 7168:     my ($scanlines,$scan_data) = @_;
 7169:     #FIXME really would prefer a scantron directory
 7170:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7171:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7172:     if ($scanlines) {
 7173: 	my $prefix='scantron_';
 7174: # no need to update orig, shouldn't change
 7175: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7176: #		    $env{'form.scantron_selectfile'});
 7177: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7178: 			$prefix.'corrected_'.
 7179: 			$env{'form.scantron_selectfile'});
 7180: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7181: 			$prefix.'skipped_'.
 7182: 			$env{'form.scantron_selectfile'});
 7183:     }
 7184:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7185: }
 7186: 
 7187: =pod
 7188: 
 7189: =item scantron_get_line
 7190: 
 7191:    Returns the correct version of the scanline
 7192: 
 7193:  Arguments:
 7194:     $scanlines - hash ref that looks like the first return value from
 7195:                  &scantron_getfile()
 7196:     $scan_data - hash ref that looks like the second return value from
 7197:                  &scantron_getfile()
 7198:     $i         - number of the requested line (starts at 0)
 7199: 
 7200:  Returns:
 7201:    A scanline, (either the original or the corrected one if it
 7202:    exists), or undef if the requested scanline should be
 7203:    skipped. (Either because it's an skipped scanline, or it's an
 7204:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7205:    pass.
 7206: 
 7207: =cut
 7208: 
 7209: sub scantron_get_line {
 7210:     my ($scanlines,$scan_data,$i)=@_;
 7211:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7212:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7213:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7214:     return $scanlines->{'orig'}[$i]; 
 7215: }
 7216: 
 7217: =pod
 7218: 
 7219: =item scantron_todo_count
 7220: 
 7221:     Counts the number of scanlines that need processing.
 7222: 
 7223:  Arguments:
 7224:     $scanlines - hash ref that looks like the first return value from
 7225:                  &scantron_getfile()
 7226:     $scan_data - hash ref that looks like the second return value from
 7227:                  &scantron_getfile()
 7228: 
 7229:  Returns:
 7230:     $count - number of scanlines to process
 7231: 
 7232: =cut
 7233: 
 7234: sub get_todo_count {
 7235:     my ($scanlines,$scan_data)=@_;
 7236:     my $count=0;
 7237:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7238: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7239: 	if ($line=~/^[\s\cz]*$/) { next; }
 7240: 	$count++;
 7241:     }
 7242:     return $count;
 7243: }
 7244: 
 7245: =pod
 7246: 
 7247: =item scantron_put_line
 7248: 
 7249:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7250:     data file.
 7251: 
 7252:  Arguments:
 7253:     $scanlines - hash ref that looks like the first return value from
 7254:                  &scantron_getfile()
 7255:     $scan_data - hash ref that looks like the second return value from
 7256:                  &scantron_getfile()
 7257:     $i         - line number to update
 7258:     $newline   - contents of the updated scanline
 7259:     $skip      - if true make the line for skipping and update the
 7260:                  'skipped' file
 7261: 
 7262: =cut
 7263: 
 7264: sub scantron_put_line {
 7265:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7266:     if ($skip) {
 7267: 	$scanlines->{'skipped'}[$i]=$newline;
 7268: 	&start_skipping($scan_data,$i);
 7269: 	return;
 7270:     }
 7271:     $scanlines->{'corrected'}[$i]=$newline;
 7272: }
 7273: 
 7274: =pod
 7275: 
 7276: =item scantron_clear_skip
 7277: 
 7278:    Remove a line from the 'skipped' file
 7279: 
 7280:  Arguments:
 7281:     $scanlines - hash ref that looks like the first return value from
 7282:                  &scantron_getfile()
 7283:     $scan_data - hash ref that looks like the second return value from
 7284:                  &scantron_getfile()
 7285:     $i         - line number to update
 7286: 
 7287: =cut
 7288: 
 7289: sub scantron_clear_skip {
 7290:     my ($scanlines,$scan_data,$i)=@_;
 7291:     if (exists($scanlines->{'skipped'}[$i])) {
 7292: 	undef($scanlines->{'skipped'}[$i]);
 7293: 	return 1;
 7294:     }
 7295:     return 0;
 7296: }
 7297: 
 7298: =pod
 7299: 
 7300: =item scantron_filter_not_exam
 7301: 
 7302:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7303:    filter out resources that are not marked as 'exam' mode
 7304: 
 7305: =cut
 7306: 
 7307: sub scantron_filter_not_exam {
 7308:     my ($curres)=@_;
 7309:     
 7310:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7311: 	# if the user has asked to not have either hidden
 7312: 	# or 'randomout' controlled resources to be graded
 7313: 	# don't include them
 7314: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7315: 	    && $curres->randomout) {
 7316: 	    return 0;
 7317: 	}
 7318: 	return 1;
 7319:     }
 7320:     return 0;
 7321: }
 7322: 
 7323: =pod
 7324: 
 7325: =item scantron_validate_sequence
 7326: 
 7327:     Validates the selected sequence, checking for resource that are
 7328:     not set to exam mode.
 7329: 
 7330: =cut
 7331: 
 7332: sub scantron_validate_sequence {
 7333:     my ($r,$currentphase) = @_;
 7334: 
 7335:     my $navmap=Apache::lonnavmaps::navmap->new();
 7336:     unless (ref($navmap)) {
 7337:         $r->print(&navmap_errormsg());
 7338:         return (1,$currentphase);
 7339:     }
 7340:     my (undef,undef,$sequence)=
 7341: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7342: 
 7343:     my $map=$navmap->getResourceByUrl($sequence);
 7344: 
 7345:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7346:                                     value="ignore" />');
 7347:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7348: 	my @resources=
 7349: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7350: 	if (@resources) {
 7351: 	    $r->print('<p class="LC_warning">'
 7352:                .&mt('Some resources in the sequence currently are not set to'
 7353:                    .' exam mode. Grading these resources currently may not'
 7354:                    .' work correctly.')
 7355:                .'</p>'
 7356:             );
 7357: 	    return (1,$currentphase);
 7358: 	}
 7359:     }
 7360: 
 7361:     return (0,$currentphase+1);
 7362: }
 7363: 
 7364: 
 7365: 
 7366: sub scantron_validate_ID {
 7367:     my ($r,$currentphase) = @_;
 7368:     
 7369:     #get student info
 7370:     my $classlist=&Apache::loncoursedata::get_classlist();
 7371:     my %idmap=&username_to_idmap($classlist);
 7372: 
 7373:     #get scantron line setup
 7374:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7375:     my ($scanlines,$scan_data)=&scantron_getfile();
 7376: 
 7377:     my $nav_error;
 7378:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7379:     if ($nav_error) {
 7380:         $r->print(&navmap_errormsg());
 7381:         return(1,$currentphase);
 7382:     }
 7383: 
 7384:     my %found=('ids'=>{},'usernames'=>{});
 7385:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7386: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7387: 	if ($line=~/^[\s\cz]*$/) { next; }
 7388: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7389: 						 $scan_data);
 7390: 	my $id=$$scan_record{'scantron.ID'};
 7391: 	my $found;
 7392: 	foreach my $checkid (keys(%idmap)) {
 7393: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7394: 	}
 7395: 	if ($found) {
 7396: 	    my $username=$idmap{$found};
 7397: 	    if ($found{'ids'}{$found}) {
 7398: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7399: 					 $line,'duplicateID',$found);
 7400: 		return(1,$currentphase);
 7401: 	    } elsif ($found{'usernames'}{$username}) {
 7402: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7403: 					 $line,'duplicateID',$username);
 7404: 		return(1,$currentphase);
 7405: 	    }
 7406: 	    #FIXME store away line we previously saw the ID on to use above
 7407: 	    $found{'ids'}{$found}++;
 7408: 	    $found{'usernames'}{$username}++;
 7409: 	} else {
 7410: 	    if ($id =~ /^\s*$/) {
 7411: 		my $username=&scan_data($scan_data,"$i.user");
 7412: 		if (defined($username) && $found{'usernames'}{$username}) {
 7413: 		    &scantron_get_correction($r,$i,$scan_record,
 7414: 					     \%scantron_config,
 7415: 					     $line,'duplicateID',$username);
 7416: 		    return(1,$currentphase);
 7417: 		} elsif (!defined($username)) {
 7418: 		    &scantron_get_correction($r,$i,$scan_record,
 7419: 					     \%scantron_config,
 7420: 					     $line,'incorrectID');
 7421: 		    return(1,$currentphase);
 7422: 		}
 7423: 		$found{'usernames'}{$username}++;
 7424: 	    } else {
 7425: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7426: 					 $line,'incorrectID');
 7427: 		return(1,$currentphase);
 7428: 	    }
 7429: 	}
 7430:     }
 7431: 
 7432:     return (0,$currentphase+1);
 7433: }
 7434: 
 7435: 
 7436: sub scantron_get_correction {
 7437:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7438:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7439: #FIXME in the case of a duplicated ID the previous line, probably need
 7440: #to show both the current line and the previous one and allow skipping
 7441: #the previous one or the current one
 7442: 
 7443:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7444:         $r->print(
 7445:             '<p class="LC_warning">'
 7446:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7447:                 "<b>$error</b>",
 7448:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7449:            ."</p> \n");
 7450:     } else {
 7451:         $r->print(
 7452:             '<p class="LC_warning">'
 7453:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7454:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7455:            ."</p> \n");
 7456:     }
 7457:     my $message =
 7458:         '<p>'
 7459:        .&mt('The ID on the form is [_1]',
 7460:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7461:        .'<br />'
 7462:        .&mt('The name on the paper is [_1], [_2]',
 7463:             $$scan_record{'scantron.LastName'},
 7464:             $$scan_record{'scantron.FirstName'})
 7465:        .'</p>';
 7466: 
 7467:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7468:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7469:                            # Array populated for doublebubble or
 7470:     my @lines_to_correct;  # missingbubble errors to build javascript
 7471:                            # to validate radio button checking   
 7472: 
 7473:     if ($error =~ /ID$/) {
 7474: 	if ($error eq 'incorrectID') {
 7475: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7476: 		      "</p>\n");
 7477: 	} elsif ($error eq 'duplicateID') {
 7478: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7479: 	}
 7480: 	$r->print($message);
 7481: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7482: 	$r->print("\n<ul><li> ");
 7483: 	#FIXME it would be nice if this sent back the user ID and
 7484: 	#could do partial userID matches
 7485: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7486: 				       'scantron_username','scantron_domain'));
 7487: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7488: 	$r->print("\n:\n".
 7489: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7490: 
 7491: 	$r->print('</li>');
 7492:     } elsif ($error =~ /CODE$/) {
 7493: 	if ($error eq 'incorrectCODE') {
 7494: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7495: 	} elsif ($error eq 'duplicateCODE') {
 7496: 	    $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");
 7497: 	}
 7498:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7499:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7500:                  ."</p>\n");
 7501: 	$r->print($message);
 7502: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7503: 	$r->print("\n<br /> ");
 7504: 	my $i=0;
 7505: 	if ($error eq 'incorrectCODE' 
 7506: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7507: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7508: 	    if ($closest > 0) {
 7509: 		foreach my $testcode (@{$closest}) {
 7510: 		    my $checked='';
 7511: 		    if (!$i) { $checked=' checked="checked"'; }
 7512: 		    $r->print("
 7513:    <label>
 7514:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7515:        ".&mt("Use the similar CODE [_1] instead.",
 7516: 	    "<b><tt>".$testcode."</tt></b>")."
 7517:     </label>
 7518:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7519: 		    $r->print("\n<br />");
 7520: 		    $i++;
 7521: 		}
 7522: 	    }
 7523: 	}
 7524: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7525: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7526: 	    $r->print("
 7527:     <label>
 7528:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7529:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7530: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7531:     </label>");
 7532: 	    $r->print("\n<br />");
 7533: 	}
 7534: 
 7535: 	$r->print(<<ENDSCRIPT);
 7536: <script type="text/javascript">
 7537: function change_radio(field) {
 7538:     var slct=document.scantronupload.scantron_CODE_resolution;
 7539:     var i;
 7540:     for (i=0;i<slct.length;i++) {
 7541:         if (slct[i].value==field) { slct[i].checked=true; }
 7542:     }
 7543: }
 7544: </script>
 7545: ENDSCRIPT
 7546: 	my $href="/adm/pickcode?".
 7547: 	   "form=".&escape("scantronupload").
 7548: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7549: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7550: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7551: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7552: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7553: 	    $r->print("
 7554:     <label>
 7555:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7556:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7557: 	     "<a target='_blank' href='$href'>","</a>")."
 7558:     </label> 
 7559:     ".&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\')" />'));
 7560: 	    $r->print("\n<br />");
 7561: 	}
 7562: 	$r->print("
 7563:     <label>
 7564:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7565:        ".&mt("Use [_1] as the CODE.",
 7566: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7567: 	$r->print("\n<br /><br />");
 7568:     } elsif ($error eq 'doublebubble') {
 7569: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7570: 
 7571: 	# The form field scantron_questions is acutally a list of line numbers.
 7572: 	# represented by this form so:
 7573: 
 7574: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7575:                                                 $respnumlookup,$startline);
 7576: 
 7577: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7578: 		  $line_list.'" />');
 7579: 	$r->print($message);
 7580: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7581: 	foreach my $question (@{$arg}) {
 7582: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7583:                                                    $scan_record, $error,
 7584:                                                    $randomorder,$randompick,
 7585:                                                    $respnumlookup,$startline);
 7586:             push(@lines_to_correct,@linenums);
 7587: 	}
 7588:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7589:     } elsif ($error eq 'missingbubble') {
 7590: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7591: 	$r->print($message);
 7592: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7593: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7594: 
 7595: 	# The form field scantron_questions is actually a list of line numbers not
 7596: 	# a list of question numbers. Therefore:
 7597: 	#
 7598: 	
 7599: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7600:                                                 $respnumlookup,$startline);
 7601: 
 7602: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7603: 		  $line_list.'" />');
 7604: 	foreach my $question (@{$arg}) {
 7605: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7606:                                                    $scan_record, $error,
 7607:                                                    $randomorder,$randompick,
 7608:                                                    $respnumlookup,$startline);
 7609:             push(@lines_to_correct,@linenums);
 7610: 	}
 7611:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7612:     } else {
 7613: 	$r->print("\n<ul>");
 7614:     }
 7615:     $r->print("\n</li></ul>");
 7616: }
 7617: 
 7618: sub verify_bubbles_checked {
 7619:     my (@ansnums) = @_;
 7620:     my $ansnumstr = join('","',@ansnums);
 7621:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7622:     my $output = (<<ENDSCRIPT);
 7623: <script type="text/javascript">
 7624: function verify_bubble_radio(form) {
 7625:     var ansnumArray = new Array ("$ansnumstr");
 7626:     var need_bubble_count = 0;
 7627:     for (var i=0; i<ansnumArray.length; i++) {
 7628:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7629:             var bubble_picked = 0; 
 7630:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7631:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7632:                     bubble_picked = 1;
 7633:                 }
 7634:             }
 7635:             if (bubble_picked == 0) {
 7636:                 need_bubble_count ++;
 7637:             }
 7638:         }
 7639:     }
 7640:     if (need_bubble_count) {
 7641:         alert("$warning");
 7642:         return;
 7643:     }
 7644:     form.submit(); 
 7645: }
 7646: </script>
 7647: ENDSCRIPT
 7648:     return $output;
 7649: }
 7650: 
 7651: =pod
 7652: 
 7653: =item  questions_to_line_list
 7654: 
 7655: Converts a list of questions into a string of comma separated
 7656: line numbers in the answer sheet used by the questions.  This is
 7657: used to fill in the scantron_questions form field.
 7658: 
 7659:   Arguments:
 7660:      questions    - Reference to an array of questions.
 7661:      randomorder  - True if randomorder in use.
 7662:      randompick   - True if randompick in use.
 7663:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7664:                      for current line to question number used for same question
 7665:                      in "Master Seqence" (as seen by Course Coordinator).
 7666:      startline    - Reference to hash where key is question number (0 is first)
 7667:                     and key is number of first bubble line for current student
 7668:                     or code-based randompick and/or randomorder.
 7669: 
 7670: =cut
 7671: 
 7672: 
 7673: sub questions_to_line_list {
 7674:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7675:     my @lines;
 7676: 
 7677:     foreach my $item (@{$questions}) {
 7678:         my $question = $item;
 7679:         my ($first,$count,$last);
 7680:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7681:             $question = $1;
 7682:             my $subquestion = $2;
 7683:             my $responsenum = $question-1;
 7684:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7685:                 $responsenum = $respnumlookup->{$question-1};
 7686:                 if (ref($startline) eq 'HASH') {
 7687:                     $first = $startline->{$question-1} + 1;
 7688:                 }
 7689:             } else {
 7690:                 $first = $first_bubble_line{$responsenum} + 1;
 7691:             }
 7692:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7693:             my $subcount = 1;
 7694:             while ($subcount<$subquestion) {
 7695:                 $first += $subans[$subcount-1];
 7696:                 $subcount ++;
 7697:             }
 7698:             $count = $subans[$subquestion-1];
 7699:         } else {
 7700:             my $responsenum = $question-1;
 7701:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7702:                 $responsenum = $respnumlookup->{$question-1};
 7703:                 if (ref($startline) eq 'HASH') {
 7704:                     $first = $startline->{$question-1} + 1;
 7705:                 }
 7706:             } else {
 7707:                 $first = $first_bubble_line{$responsenum} + 1;
 7708:             }
 7709:             $count   = $bubble_lines_per_response{$responsenum};
 7710:         }
 7711:         $last = $first+$count-1;
 7712:         push(@lines, ($first..$last));
 7713:     }
 7714:     return join(',', @lines);
 7715: }
 7716: 
 7717: =pod 
 7718: 
 7719: =item prompt_for_corrections
 7720: 
 7721: Prompts for a potentially multiline correction to the
 7722: user's bubbling (factors out common code from scantron_get_correction
 7723: for multi and missing bubble cases).
 7724: 
 7725:  Arguments:
 7726:    $r           - Apache request object.
 7727:    $question    - The question number to prompt for.
 7728:    $scan_config - The scantron file configuration hash.
 7729:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7730:    $error       - Type of error
 7731:    $randomorder - True if randomorder in use.
 7732:    $randompick  - True if randompick in use.
 7733:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7734:                     for current line to question number used for same question
 7735:                     in "Master Seqence" (as seen by Course Coordinator).
 7736:    $startline   - Reference to hash where key is question number (0 is first)
 7737:                   and value is number of first bubble line for current student
 7738:                   or code-based randompick and/or randomorder.
 7739: 
 7740:  Implicit inputs:
 7741:    %bubble_lines_per_response   - Starting line numbers for each question.
 7742:                                   Numbered from 0 (but question numbers are from
 7743:                                   1.
 7744:    %first_bubble_line           - Starting bubble line for each question.
 7745:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7746:                                   type problems render as separate sub-questions, 
 7747:                                   in exam mode. This hash contains a 
 7748:                                   comma-separated list of the lines per 
 7749:                                   sub-question.
 7750:    %responsetype_per_response   - essayresponse, formularesponse,
 7751:                                   stringresponse, imageresponse, reactionresponse,
 7752:                                   and organicresponse type problem parts can have
 7753:                                   multiple lines per response if the weight
 7754:                                   assigned exceeds 10.  In this case, only
 7755:                                   one bubble per line is permitted, but more 
 7756:                                   than one line might contain bubbles, e.g.
 7757:                                   bubbling of: line 1 - J, line 2 - J, 
 7758:                                   line 3 - B would assign 22 points.  
 7759: 
 7760: =cut
 7761: 
 7762: sub prompt_for_corrections {
 7763:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7764:         $randompick, $respnumlookup, $startline) = @_;
 7765:     my ($current_line,$lines);
 7766:     my @linenums;
 7767:     my $questionnum = $question;
 7768:     my ($first,$responsenum);
 7769:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7770:         $question = $1;
 7771:         my $subquestion = $2;
 7772:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7773:             $responsenum = $respnumlookup->{$question-1};
 7774:             if (ref($startline) eq 'HASH') {
 7775:                 $first = $startline->{$question-1};
 7776:             }
 7777:         } else {
 7778:             $responsenum = $question-1;
 7779:             $first = $first_bubble_line{$responsenum};
 7780:         }
 7781:         $current_line = $first + 1 ;
 7782:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7783:         my $subcount = 1;
 7784:         while ($subcount<$subquestion) {
 7785:             $current_line += $subans[$subcount-1];
 7786:             $subcount ++;
 7787:         }
 7788:         $lines = $subans[$subquestion-1];
 7789:     } else {
 7790:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7791:             $responsenum = $respnumlookup->{$question-1};
 7792:             if (ref($startline) eq 'HASH') {
 7793:                 $first = $startline->{$question-1};
 7794:             }
 7795:         } else {
 7796:             $responsenum = $question-1;
 7797:             $first = $first_bubble_line{$responsenum};
 7798:         }
 7799:         $current_line = $first + 1;
 7800:         $lines        = $bubble_lines_per_response{$responsenum};
 7801:     }
 7802:     if ($lines > 1) {
 7803:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7804:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7805:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7806:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7807:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7808:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7809:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7810:             $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 />');
 7811:         } else {
 7812:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7813:         }
 7814:     }
 7815:     for (my $i =0; $i < $lines; $i++) {
 7816:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7817: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7818: 	        		  $questionnum,$error,split('', $selected));
 7819:         push(@linenums,$current_line);
 7820: 	$current_line++;
 7821:     }
 7822:     if ($lines > 1) {
 7823: 	$r->print("<hr /><br />");
 7824:     }
 7825:     return @linenums;
 7826: }
 7827: 
 7828: =pod
 7829: 
 7830: =item scantron_bubble_selector
 7831:   
 7832:    Generates the html radiobuttons to correct a single bubble line
 7833:    possibly showing the existing the selected bubbles if known
 7834: 
 7835:  Arguments:
 7836:     $r           - Apache request object
 7837:     $scan_config - hash from &get_scantron_config()
 7838:     $line        - Number of the line being displayed.
 7839:     $questionnum - Question number (may include subquestion)
 7840:     $error       - Type of error.
 7841:     @selected    - Array of bubbles picked on this line.
 7842: 
 7843: =cut
 7844: 
 7845: sub scantron_bubble_selector {
 7846:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7847:     my $max=$$scan_config{'Qlength'};
 7848: 
 7849:     my $scmode=$$scan_config{'Qon'};
 7850:     if ($scmode eq 'number' || $scmode eq 'letter') {
 7851:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7852:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7853:             $max=$$scan_config{'BubblesPerRow'};
 7854:             if (($scmode eq 'number') && ($max > 10)) {
 7855:                 $max = 10;
 7856:             } elsif (($scmode eq 'letter') && $max > 26) {
 7857:                 $max = 26;
 7858:             }
 7859:         } else {
 7860:             $max = 10;
 7861:         }
 7862:     }
 7863: 
 7864:     my @alphabet=('A'..'Z');
 7865:     $r->print(&Apache::loncommon::start_data_table().
 7866:               &Apache::loncommon::start_data_table_row());
 7867:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7868:     for (my $i=0;$i<$max+1;$i++) {
 7869: 	$r->print("\n".'<td align="center">');
 7870: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7871: 	else { $r->print('&nbsp;'); }
 7872: 	$r->print('</td>');
 7873:     }
 7874:     $r->print(&Apache::loncommon::end_data_table_row().
 7875:               &Apache::loncommon::start_data_table_row());
 7876:     for (my $i=0;$i<$max;$i++) {
 7877: 	$r->print("\n".
 7878: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7879: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7880:     }
 7881:     my $nobub_checked = ' ';
 7882:     if ($error eq 'missingbubble') {
 7883:         $nobub_checked = ' checked = "checked" ';
 7884:     }
 7885:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7886: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7887:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7888:               $line.'" value="'.$questionnum.'" /></td>');
 7889:     $r->print(&Apache::loncommon::end_data_table_row().
 7890:               &Apache::loncommon::end_data_table());
 7891: }
 7892: 
 7893: =pod
 7894: 
 7895: =item num_matches
 7896: 
 7897:    Counts the number of characters that are the same between the two arguments.
 7898: 
 7899:  Arguments:
 7900:    $orig - CODE from the scanline
 7901:    $code - CODE to match against
 7902: 
 7903:  Returns:
 7904:    $count - integer count of the number of same characters between the
 7905:             two arguments
 7906: 
 7907: =cut
 7908: 
 7909: sub num_matches {
 7910:     my ($orig,$code) = @_;
 7911:     my @code=split(//,$code);
 7912:     my @orig=split(//,$orig);
 7913:     my $same=0;
 7914:     for (my $i=0;$i<scalar(@code);$i++) {
 7915: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7916:     }
 7917:     return $same;
 7918: }
 7919: 
 7920: =pod
 7921: 
 7922: =item scantron_get_closely_matching_CODEs
 7923: 
 7924:    Cycles through all CODEs and finds the set that has the greatest
 7925:    number of same characters as the provided CODE
 7926: 
 7927:  Arguments:
 7928:    $allcodes - hash ref returned by &get_codes()
 7929:    $CODE     - CODE from the current scanline
 7930: 
 7931:  Returns:
 7932:    2 element list
 7933:     - first elements is number of how closely matching the best fit is 
 7934:       (5 means best set has 5 matching characters)
 7935:     - second element is an arrary ref containing the set of valid CODEs
 7936:       that best fit the passed in CODE
 7937: 
 7938: =cut
 7939: 
 7940: sub scantron_get_closely_matching_CODEs {
 7941:     my ($allcodes,$CODE)=@_;
 7942:     my @CODEs;
 7943:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7944: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7945:     }
 7946: 
 7947:     return ($#CODEs,$CODEs[-1]);
 7948: }
 7949: 
 7950: =pod
 7951: 
 7952: =item get_codes
 7953: 
 7954:    Builds a hash which has keys of all of the valid CODEs from the selected
 7955:    set of remembered CODEs.
 7956: 
 7957:  Arguments:
 7958:   $old_name - name of the set of remembered CODEs
 7959:   $cdom     - domain of the course
 7960:   $cnum     - internal course name
 7961: 
 7962:  Returns:
 7963:   %allcodes - keys are the valid CODEs, values are all 1
 7964: 
 7965: =cut
 7966: 
 7967: sub get_codes {
 7968:     my ($old_name, $cdom, $cnum) = @_;
 7969:     if (!$old_name) {
 7970: 	$old_name=$env{'form.scantron_CODElist'};
 7971:     }
 7972:     if (!$cdom) {
 7973: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7974:     }
 7975:     if (!$cnum) {
 7976: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7977:     }
 7978:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7979: 				    $cdom,$cnum);
 7980:     my %allcodes;
 7981:     if ($result{"type\0$old_name"} eq 'number') {
 7982: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7983:     } else {
 7984: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7985:     }
 7986:     return %allcodes;
 7987: }
 7988: 
 7989: =pod
 7990: 
 7991: =item scantron_validate_CODE
 7992: 
 7993:    Validates all scanlines in the selected file to not have any
 7994:    invalid or underspecified CODEs and that none of the codes are
 7995:    duplicated if this was requested.
 7996: 
 7997: =cut
 7998: 
 7999: sub scantron_validate_CODE {
 8000:     my ($r,$currentphase) = @_;
 8001:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8002:     if ($scantron_config{'CODElocation'} &&
 8003: 	$scantron_config{'CODEstart'} &&
 8004: 	$scantron_config{'CODElength'}) {
 8005: 	if (!defined($env{'form.scantron_CODElist'})) {
 8006: 	    &FIXME_blow_up()
 8007: 	}
 8008:     } else {
 8009: 	return (0,$currentphase+1);
 8010:     }
 8011:     
 8012:     my %usedCODEs;
 8013: 
 8014:     my %allcodes=&get_codes();
 8015: 
 8016:     my $nav_error;
 8017:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8018:     if ($nav_error) {
 8019:         $r->print(&navmap_errormsg());
 8020:         return(1,$currentphase);
 8021:     }
 8022: 
 8023:     my ($scanlines,$scan_data)=&scantron_getfile();
 8024:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8025: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8026: 	if ($line=~/^[\s\cz]*$/) { next; }
 8027: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8028: 						 $scan_data);
 8029: 	my $CODE=$$scan_record{'scantron.CODE'};
 8030: 	my $error=0;
 8031: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8032: 	    &scantron_get_correction($r,$i,$scan_record,
 8033: 				     \%scantron_config,
 8034: 				     $line,'incorrectCODE',\%allcodes);
 8035: 	    return(1,$currentphase);
 8036: 	}
 8037: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8038: 	    && !$$scan_record{'scantron.useCODE'}) {
 8039: 	    &scantron_get_correction($r,$i,$scan_record,
 8040: 				     \%scantron_config,
 8041: 				     $line,'incorrectCODE',\%allcodes);
 8042: 	    return(1,$currentphase);
 8043: 	}
 8044: 	if (exists($usedCODEs{$CODE}) 
 8045: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8046: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8047: 	    &scantron_get_correction($r,$i,$scan_record,
 8048: 				     \%scantron_config,
 8049: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8050: 	    return(1,$currentphase);
 8051: 	}
 8052: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8053:     }
 8054:     return (0,$currentphase+1);
 8055: }
 8056: 
 8057: =pod
 8058: 
 8059: =item scantron_validate_doublebubble
 8060: 
 8061:    Validates all scanlines in the selected file to not have any
 8062:    bubble lines with multiple bubbles marked.
 8063: 
 8064: =cut
 8065: 
 8066: sub scantron_validate_doublebubble {
 8067:     my ($r,$currentphase) = @_;
 8068:     #get student info
 8069:     my $classlist=&Apache::loncoursedata::get_classlist();
 8070:     my %idmap=&username_to_idmap($classlist);
 8071:     my (undef,undef,$sequence)=
 8072:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8073: 
 8074:     #get scantron line setup
 8075:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8076:     my ($scanlines,$scan_data)=&scantron_getfile();
 8077: 
 8078:     my $navmap = Apache::lonnavmaps::navmap->new();
 8079:     unless (ref($navmap)) {
 8080:         $r->print(&navmap_errormsg());
 8081:         return(1,$currentphase);
 8082:     }
 8083:     my $map=$navmap->getResourceByUrl($sequence);
 8084:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8085:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8086:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8087:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8088: 
 8089:     my $nav_error;
 8090:     if (ref($map)) {
 8091:         $randomorder = $map->randomorder();
 8092:         $randompick = $map->randompick();
 8093:         if ($randomorder || $randompick) {
 8094:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8095:             if ($nav_error) {
 8096:                 $r->print(&navmap_errormsg());
 8097:                 return(1,$currentphase);
 8098:             }
 8099:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8100:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8101:         }
 8102:     } else {
 8103:         $r->print(&navmap_errormsg());
 8104:         return(1,$currentphase);
 8105:     }
 8106: 
 8107:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8108:     if ($nav_error) {
 8109:         $r->print(&navmap_errormsg());
 8110:         return(1,$currentphase);
 8111:     }
 8112: 
 8113:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8114: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8115: 	if ($line=~/^[\s\cz]*$/) { next; }
 8116: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8117: 						 $scan_data,undef,\%idmap,$randomorder,
 8118:                                                  $randompick,$sequence,\@master_seq,
 8119:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8120:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8121: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8122: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8123: 				 'doublebubble',
 8124: 				 $$scan_record{'scantron.doubleerror'},
 8125:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8126:     	return (1,$currentphase);
 8127:     }
 8128:     return (0,$currentphase+1);
 8129: }
 8130: 
 8131: 
 8132: sub scantron_get_maxbubble {
 8133:     my ($nav_error,$scantron_config) = @_;
 8134:     if (defined($env{'form.scantron_maxbubble'}) &&
 8135: 	$env{'form.scantron_maxbubble'}) {
 8136: 	&restore_bubble_lines();
 8137: 	return $env{'form.scantron_maxbubble'};
 8138:     }
 8139: 
 8140:     my (undef, undef, $sequence) =
 8141: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8142: 
 8143:     my $navmap=Apache::lonnavmaps::navmap->new();
 8144:     unless (ref($navmap)) {
 8145:         if (ref($nav_error)) {
 8146:             $$nav_error = 1;
 8147:         }
 8148:         return;
 8149:     }
 8150:     my $map=$navmap->getResourceByUrl($sequence);
 8151:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8152:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8153: 
 8154:     &Apache::lonxml::clear_problem_counter();
 8155: 
 8156:     my $uname       = $env{'user.name'};
 8157:     my $udom        = $env{'user.domain'};
 8158:     my $cid         = $env{'request.course.id'};
 8159:     my $total_lines = 0;
 8160:     %bubble_lines_per_response = ();
 8161:     %first_bubble_line         = ();
 8162:     %subdivided_bubble_lines   = ();
 8163:     %responsetype_per_response = ();
 8164:     %masterseq_id_responsenum  = ();
 8165: 
 8166:     my $response_number = 0;
 8167:     my $bubble_line     = 0;
 8168:     foreach my $resource (@resources) {
 8169:         my $resid = $resource->id();
 8170:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8171:                                                           $udom,undef,$bubbles_per_row);
 8172:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8173: 	    foreach my $part_id (@{$parts}) {
 8174:                 my $lines;
 8175: 
 8176: 	        # TODO - make this a persistent hash not an array.
 8177: 
 8178:                 # optionresponse, matchresponse and rankresponse type items 
 8179:                 # render as separate sub-questions in exam mode.
 8180:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8181:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8182:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8183:                     my ($numbub,$numshown);
 8184:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8185:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8186:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8187:                         }
 8188:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8189:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8190:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8191:                         }
 8192:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8193:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8194:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8195:                         }
 8196:                     }
 8197:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8198:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8199:                     }
 8200:                     my $bubbles_per_row =
 8201:                         &bubblesheet_bubbles_per_row($scantron_config);
 8202:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8203:                     if (($numbub % $bubbles_per_row) != 0) {
 8204:                         $inner_bubble_lines++;
 8205:                     }
 8206:                     for (my $i=0; $i<$numshown; $i++) {
 8207:                         $subdivided_bubble_lines{$response_number} .= 
 8208:                             $inner_bubble_lines.',';
 8209:                     }
 8210:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8211:                     $lines = $numshown * $inner_bubble_lines;
 8212:                 } else {
 8213:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8214:                 }
 8215: 
 8216:                 $first_bubble_line{$response_number} = $bubble_line;
 8217: 	        $bubble_lines_per_response{$response_number} = $lines;
 8218:                 $responsetype_per_response{$response_number} = 
 8219:                     $analysis->{$part_id.'.type'};
 8220:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8221: 	        $response_number++;
 8222: 
 8223: 	        $bubble_line +=  $lines;
 8224: 	        $total_lines +=  $lines;
 8225: 	    }
 8226:         }
 8227:     }
 8228:     &Apache::lonnet::delenv('scantron.');
 8229: 
 8230:     &save_bubble_lines();
 8231:     $env{'form.scantron_maxbubble'} =
 8232: 	$total_lines;
 8233:     return $env{'form.scantron_maxbubble'};
 8234: }
 8235: 
 8236: sub bubblesheet_bubbles_per_row {
 8237:     my ($scantron_config) = @_;
 8238:     my $bubbles_per_row;
 8239:     if (ref($scantron_config) eq 'HASH') {
 8240:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8241:     }
 8242:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8243:         $bubbles_per_row = 10;
 8244:     }
 8245:     return $bubbles_per_row;
 8246: }
 8247: 
 8248: sub scantron_validate_missingbubbles {
 8249:     my ($r,$currentphase) = @_;
 8250:     #get student info
 8251:     my $classlist=&Apache::loncoursedata::get_classlist();
 8252:     my %idmap=&username_to_idmap($classlist);
 8253:     my (undef,undef,$sequence)=
 8254:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8255: 
 8256:     #get scantron line setup
 8257:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8258:     my ($scanlines,$scan_data)=&scantron_getfile();
 8259: 
 8260:     my $navmap = Apache::lonnavmaps::navmap->new();
 8261:     unless (ref($navmap)) {
 8262:         $r->print(&navmap_errormsg());
 8263:         return(1,$currentphase);
 8264:     }
 8265: 
 8266:     my $map=$navmap->getResourceByUrl($sequence);
 8267:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8268:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8269:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8270:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8271: 
 8272:     my $nav_error;
 8273:     if (ref($map)) {
 8274:         $randomorder = $map->randomorder();
 8275:         $randompick = $map->randompick();
 8276:         if ($randomorder || $randompick) {
 8277:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8278:             if ($nav_error) {
 8279:                 $r->print(&navmap_errormsg());
 8280:                 return(1,$currentphase);
 8281:             }
 8282:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8283:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8284:         }
 8285:     } else {
 8286:         $r->print(&navmap_errormsg());
 8287:         return(1,$currentphase);
 8288:     }
 8289: 
 8290: 
 8291:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8292:     if ($nav_error) {
 8293:         $r->print(&navmap_errormsg());
 8294:         return(1,$currentphase);
 8295:     }
 8296: 
 8297:     if (!$max_bubble) { $max_bubble=2**31; }
 8298:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8299: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8300: 	if ($line=~/^[\s\cz]*$/) { next; }
 8301:         my $scan_record =
 8302:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8303:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8304:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8305:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8306: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8307: 	my @to_correct;
 8308: 	
 8309: 	# Probably here's where the error is...
 8310: 
 8311: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8312:             my $lastbubble;
 8313:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8314:                 my $question = $1;
 8315:                 my $subquestion = $2;
 8316:                 my ($first,$responsenum);
 8317:                 if ($randomorder || $randompick) {
 8318:                     $responsenum = $respnumlookup{$question-1};
 8319:                     $first = $startline{$question-1};
 8320:                 } else {
 8321:                     $responsenum = $question-1;
 8322:                     $first = $first_bubble_line{$responsenum};
 8323:                 }
 8324:                 if (!defined($first)) { next; }
 8325:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8326:                 my $subcount = 1;
 8327:                 while ($subcount<$subquestion) {
 8328:                     $first += $subans[$subcount-1];
 8329:                     $subcount ++;
 8330:                 }
 8331:                 my $count = $subans[$subquestion-1];
 8332:                 $lastbubble = $first + $count;
 8333:             } else {
 8334:                 my ($first,$responsenum);
 8335:                 if ($randomorder || $randompick) {
 8336:                     $responsenum = $respnumlookup{$missing-1};
 8337:                     $first = $startline{$missing-1};
 8338:                 } else {
 8339:                     $responsenum = $missing-1;
 8340:                     $first = $first_bubble_line{$responsenum};
 8341:                 }
 8342:                 if (!defined($first)) { next; }
 8343:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8344:             }
 8345:             if ($lastbubble > $max_bubble) { next; }
 8346: 	    push(@to_correct,$missing);
 8347: 	}
 8348: 	if (@to_correct) {
 8349: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8350: 				     $line,'missingbubble',\@to_correct,
 8351:                                      $randomorder,$randompick,\%respnumlookup,
 8352:                                      \%startline);
 8353: 	    return (1,$currentphase);
 8354: 	}
 8355: 
 8356:     }
 8357:     return (0,$currentphase+1);
 8358: }
 8359: 
 8360: sub hand_bubble_option {
 8361:     my (undef, undef, $sequence) =
 8362:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8363:     return if ($sequence eq '');
 8364:     my $navmap = Apache::lonnavmaps::navmap->new();
 8365:     unless (ref($navmap)) {
 8366:         return;
 8367:     }
 8368:     my $needs_hand_bubbles;
 8369:     my $map=$navmap->getResourceByUrl($sequence);
 8370:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8371:     foreach my $res (@resources) {
 8372:         if (ref($res)) {
 8373:             if ($res->is_problem()) {
 8374:                 my $partlist = $res->parts();
 8375:                 foreach my $part (@{ $partlist }) {
 8376:                     my @types = $res->responseType($part);
 8377:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8378:                         $needs_hand_bubbles = 1;
 8379:                         last;
 8380:                     }
 8381:                 }
 8382:             }
 8383:         }
 8384:     }
 8385:     if ($needs_hand_bubbles) {
 8386:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8387:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8388:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8389:                &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 />').
 8390:                '<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;'.
 8391:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8392:     }
 8393:     return;
 8394: }
 8395: 
 8396: sub scantron_process_students {
 8397:     my ($r) = @_;
 8398: 
 8399:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8400:     my ($symb)=&get_symb($r);
 8401:     if (!$symb) {
 8402: 	return '';
 8403:     }
 8404:     my $default_form_data=&defaultFormData($symb);
 8405: 
 8406:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8407:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8408:     my ($scanlines,$scan_data)=&scantron_getfile();
 8409:     my $classlist=&Apache::loncoursedata::get_classlist();
 8410:     my %idmap=&username_to_idmap($classlist);
 8411:     my $navmap=Apache::lonnavmaps::navmap->new();
 8412:     unless (ref($navmap)) {
 8413:         $r->print(&navmap_errormsg());
 8414:         return '';
 8415:     }
 8416:     my $map=$navmap->getResourceByUrl($sequence);
 8417:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8418:         %grader_randomlists_by_symb);
 8419:     if (ref($map)) {
 8420:         $randomorder = $map->randomorder();
 8421:         $randompick = $map->randompick();
 8422:     } else {
 8423:         $r->print(&navmap_errormsg());
 8424:         return '';
 8425:     }
 8426:     my $nav_error;
 8427:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8428:     if ($randomorder || $randompick) {
 8429:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8430:         if ($nav_error) {
 8431:             $r->print(&navmap_errormsg());
 8432:             return '';
 8433:         }
 8434:     }
 8435:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8436:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8437: 
 8438:     my ($uname,$udom);
 8439:     my $result= <<SCANTRONFORM;
 8440: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8441:   <input type="hidden" name="command" value="scantron_configphase" />
 8442:   $default_form_data
 8443: SCANTRONFORM
 8444:     $r->print($result);
 8445: 
 8446:     my @delayqueue;
 8447:     my (%completedstudents,%scandata);
 8448:     
 8449:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8450:     my $count=&get_todo_count($scanlines,$scan_data);
 8451:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8452:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8453: 					  'Processing first student');
 8454:     $r->print('<br />');
 8455:     my $start=&Time::HiRes::time();
 8456:     my $i=-1;
 8457:     my $started;
 8458: 
 8459:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8460:     if ($nav_error) {
 8461:         $r->print(&navmap_errormsg());
 8462:         return '';
 8463:     }
 8464: 
 8465:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8466:     # the user and return.
 8467: 
 8468:     if ($ssi_error) {
 8469: 	$r->print("</form>");
 8470: 	&ssi_print_error($r);
 8471: 	$r->print(&show_grading_menu_form($symb));
 8472:         &Apache::lonnet::remove_lock($lock);
 8473: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8474:     }
 8475: 
 8476:     my %lettdig = &letter_to_digits();
 8477:     my $numletts = scalar(keys(%lettdig));
 8478:     my %orderedforcode;
 8479: 
 8480:     while ($i<$scanlines->{'count'}) {
 8481:  	($uname,$udom)=('','');
 8482:  	$i++;
 8483:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8484:  	if ($line=~/^[\s\cz]*$/) { next; }
 8485: 	if ($started) {
 8486: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8487: 						     'last student');
 8488: 	}
 8489: 	$started=1;
 8490:         my %respnumlookup = ();
 8491:         my %startline = ();
 8492:         my $total;
 8493:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8494:  						 $scan_data,undef,\%idmap,$randomorder,
 8495:                                                  $randompick,$sequence,\@master_seq,
 8496:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8497:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8498:                                                  \$total);
 8499:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8500:  					      \%idmap,$i)) {
 8501:   	    &scantron_add_delay(\@delayqueue,$line,
 8502:  				'Unable to find a student that matches',1);
 8503:  	    next;
 8504:   	}
 8505:  	if (exists $completedstudents{$uname}) {
 8506:  	    &scantron_add_delay(\@delayqueue,$line,
 8507:  				'Student '.$uname.' has multiple sheets',2);
 8508:  	    next;
 8509:  	}
 8510:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8511:         my $user = $uname.':'.$usec;
 8512:   	($uname,$udom)=split(/:/,$uname);
 8513: 
 8514:         my $scancode;
 8515:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8516:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8517:             $scancode = $scan_record->{'scantron.CODE'};
 8518:         } else {
 8519:             $scancode = '';
 8520:         }
 8521: 
 8522:         my @mapresources = @resources;
 8523:         if ($randomorder || $randompick) {
 8524:             @mapresources =
 8525:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8526:                              \%orderedforcode);
 8527:         }
 8528:         my (%partids_by_symb,$res_error);
 8529:         foreach my $resource (@mapresources) {
 8530:             my $ressymb;
 8531:             if (ref($resource)) {
 8532:                 $ressymb = $resource->symb();
 8533:             } else {
 8534:                 $res_error = 1;
 8535:                 last;
 8536:             }
 8537:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8538:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8539:                 my ($analysis,$parts) =
 8540:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8541:                                               $uname,$udom,undef,$bubbles_per_row);
 8542:                 $partids_by_symb{$ressymb} = $parts;
 8543:             } else {
 8544:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8545:             }
 8546:         }
 8547: 
 8548:         if ($res_error) {
 8549:             &scantron_add_delay(\@delayqueue,$line,
 8550:                                 'An error occurred while grading student '.$uname,2);
 8551:             next;
 8552:         }
 8553: 
 8554: 	&Apache::lonxml::clear_problem_counter();
 8555:   	&Apache::lonnet::appenv($scan_record);
 8556: 
 8557: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8558: 	    &scantron_putfile($scanlines,$scan_data);
 8559: 	}
 8560: 	
 8561:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8562:                                    \@mapresources,\%partids_by_symb,
 8563:                                    $bubbles_per_row,$randomorder,$randompick,
 8564:                                    \%respnumlookup,\%startline) 
 8565:             eq 'ssi_error') {
 8566:             $ssi_error = 0; # So end of handler error message does not trigger.
 8567:             $r->print("</form>");
 8568:             &ssi_print_error($r);
 8569:             $r->print(&show_grading_menu_form($symb));
 8570:             &Apache::lonnet::remove_lock($lock);
 8571:             return '';      # Why return ''?  Beats me.
 8572:         }
 8573: 
 8574:         if (($scancode) && ($randomorder || $randompick)) {
 8575:             my $parmresult =
 8576:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8577:                                                        '0_examcode',2,$scancode,
 8578:                                                        'string_examcode',$uname,
 8579:                                                        $udom);
 8580:         }
 8581: 	$completedstudents{$uname}={'line'=>$line};
 8582:         if ($env{'form.verifyrecord'}) {
 8583:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8584:             if ($randompick) {
 8585:                 if ($total) {
 8586:                     $lastpos = $total*$scantron_config{'Qlength'};
 8587:                 }
 8588:             }
 8589: 
 8590:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8591:             chomp($studentdata);
 8592:             $studentdata =~ s/\r$//;
 8593:             my $studentrecord = '';
 8594:             my $counter = -1;
 8595:             foreach my $resource (@mapresources) {
 8596:                 my $ressymb = $resource->symb();
 8597:                 ($counter,my $recording) =
 8598:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8599:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8600:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8601:                                              $randompick,\%respnumlookup,\%startline);
 8602:                 $studentrecord .= $recording;
 8603:             }
 8604:             if ($studentrecord ne $studentdata) {
 8605:                 &Apache::lonxml::clear_problem_counter();
 8606:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8607:                                            \@mapresources,\%partids_by_symb,
 8608:                                            $bubbles_per_row,$randomorder,$randompick,
 8609:                                            \%respnumlookup,\%startline)
 8610:                     eq 'ssi_error') {
 8611:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8612:                     $r->print("</form>");
 8613:                     &ssi_print_error($r);
 8614:                     $r->print(&show_grading_menu_form($symb));
 8615:                     &Apache::lonnet::remove_lock($lock);
 8616:                     delete($completedstudents{$uname});
 8617:                     return '';
 8618:                 }
 8619:                 $counter = -1;
 8620:                 $studentrecord = '';
 8621:                 foreach my $resource (@mapresources) {
 8622:                     my $ressymb = $resource->symb();
 8623:                     ($counter,my $recording) =
 8624:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8625:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8626:                                                  \%scantron_config,\%lettdig,$numletts,
 8627:                                                  $randomorder,$randompick,\%respnumlookup,
 8628:                                                  \%startline);
 8629:                     $studentrecord .= $recording;
 8630:                 }
 8631:                 if ($studentrecord ne $studentdata) {
 8632:                     $r->print('<p><span class="LC_warning">');
 8633:                     if ($scancode eq '') {
 8634:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8635:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8636:                     } else {
 8637:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8638:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8639:                     }
 8640:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8641:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8642:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8643:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8644:                               &Apache::loncommon::start_data_table_row().
 8645:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8646:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8647:                               &Apache::loncommon::end_data_table_row().
 8648:                               &Apache::loncommon::start_data_table_row().
 8649:                               '<td>'.&mt('Stored submissions').'</td>'.
 8650:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8651:                               &Apache::loncommon::end_data_table_row().
 8652:                               &Apache::loncommon::end_data_table().'</p>');
 8653:                 } else {
 8654:                     $r->print('<br /><span class="LC_warning">'.
 8655:                              &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 />'.
 8656:                              &mt("As a consequence, this user's submission history records two tries.").
 8657:                                  '</span><br />');
 8658:                 }
 8659:             }
 8660:         }
 8661:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8662:     } continue {
 8663: 	&Apache::lonxml::clear_problem_counter();
 8664: 	&Apache::lonnet::delenv('scantron.');
 8665:     }
 8666:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8667:     &Apache::lonnet::remove_lock($lock);
 8668: #    my $lasttime = &Time::HiRes::time()-$start;
 8669: #    $r->print("<p>took $lasttime</p>");
 8670: 
 8671:     $r->print("</form>");
 8672:     $r->print(&show_grading_menu_form($symb));
 8673:     return '';
 8674: }
 8675: 
 8676: sub graders_resources_pass {
 8677:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8678:         $bubbles_per_row) = @_;
 8679:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8680:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8681:         foreach my $resource (@{$resources}) {
 8682:             my $ressymb = $resource->symb();
 8683:             my ($analysis,$parts) =
 8684:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8685:                                           $env{'user.name'},$env{'user.domain'},
 8686:                                           1,$bubbles_per_row);
 8687:             $grader_partids_by_symb->{$ressymb} = $parts;
 8688:             if (ref($analysis) eq 'HASH') {
 8689:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8690:                     $grader_randomlists_by_symb->{$ressymb} =
 8691:                         $analysis->{'parts_withrandomlist'};
 8692:                 }
 8693:             }
 8694:         }
 8695:     }
 8696:     return;
 8697: }
 8698: 
 8699: =pod
 8700: 
 8701: =item users_order
 8702: 
 8703:   Returns array of resources in current map, ordered based on either CODE,
 8704:   if this is a CODEd exam, or based on student's identity if this is a
 8705:   "NAMEd" exam.
 8706: 
 8707:   Should be used when randomorder and/or randompick applied when the 
 8708:   corresponding exam was printed, prior to students completing bubblesheets 
 8709:   for the version of the exam the student received.
 8710: 
 8711: =cut
 8712: 
 8713: sub users_order  {
 8714:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8715:     my @mapresources;
 8716:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8717:         return @mapresources;
 8718:     }
 8719:     if ($scancode) {
 8720:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8721:             @mapresources = @{$orderedforcode->{$scancode}};
 8722:         } else {
 8723:             $env{'form.CODE'} = $scancode;
 8724:             my $actual_seq =
 8725:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8726:                                                                $master_seq,
 8727:                                                                $user,$scancode,1);
 8728:             if (ref($actual_seq) eq 'ARRAY') {
 8729:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8730:                 if (ref($orderedforcode) eq 'HASH') {
 8731:                     if (@mapresources > 0) {
 8732:                         $orderedforcode->{$scancode} = \@mapresources;
 8733:                     }
 8734:                 }
 8735:             }
 8736:             delete($env{'form.CODE'});
 8737:         }
 8738:     } else {
 8739:         my $actual_seq =
 8740:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8741:                                                            $master_seq,
 8742:                                                            $user,undef,1);
 8743:         if (ref($actual_seq) eq 'ARRAY') {
 8744:             @mapresources =
 8745:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8746:         }
 8747:     }
 8748:     return @mapresources;
 8749: }
 8750: 
 8751: sub grade_student_bubbles {
 8752:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8753:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8754:     my $uselookup = 0;
 8755:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8756:         (ref($startline) eq 'HASH')) {
 8757:         $uselookup = 1;
 8758:     }
 8759: 
 8760:     if (ref($resources) eq 'ARRAY') {
 8761:         my $count = 0;
 8762:         foreach my $resource (@{$resources}) {
 8763:             my $ressymb = $resource->symb();
 8764:             my %form = ('submitted'      => 'scantron',
 8765:                         'grade_target'   => 'grade',
 8766:                         'grade_username' => $uname,
 8767:                         'grade_domain'   => $udom,
 8768:                         'grade_courseid' => $env{'request.course.id'},
 8769:                         'grade_symb'     => $ressymb,
 8770:                         'CODE'           => $scancode
 8771:                        );
 8772:             if ($bubbles_per_row ne '') {
 8773:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8774:             }
 8775:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8776:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8777:             }
 8778:             if (ref($parts) eq 'HASH') {
 8779:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8780:                     foreach my $part (@{$parts->{$ressymb}}) {
 8781:                         if ($uselookup) {
 8782:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8783:                         } else {
 8784:                             $form{'scantron_questnum_start.'.$part} =
 8785:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8786:                         }
 8787:                         $count++;
 8788:                     }
 8789:                 }
 8790:             }
 8791:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8792:             return 'ssi_error' if ($ssi_error);
 8793:             last if (&Apache::loncommon::connection_aborted($r));
 8794:         }
 8795:     }
 8796:     return;
 8797: }
 8798: 
 8799: sub scantron_upload_scantron_data {
 8800:     my ($r)=@_;
 8801:     my $dom = $env{'request.role.domain'};
 8802:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8803:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8804:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8805: 							  'domainid',
 8806: 							  'coursename',$dom);
 8807:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8808:                        ('&nbsp'x2).&mt('(shows course personnel)');
 8809:     my ($symb) = &get_symb($r,1);
 8810:     my $default_form_data=&defaultFormData($symb);
 8811:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8812:     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.");
 8813:     $r->print('
 8814: <script type="text/javascript" language="javascript">
 8815:     function checkUpload(formname) {
 8816: 	if (formname.upfile.value == "") {
 8817: 	    alert("'.$nofile_alert.'");
 8818: 	    return false;
 8819: 	}
 8820:         if (formname.courseid.value == "") {
 8821:             alert("'.$nocourseid_alert.'");
 8822:             return false;
 8823:         }
 8824: 	formname.submit();
 8825:     }
 8826: 
 8827:     function ToSyllabus() {
 8828:         var cdom = '."'$dom'".';
 8829:         var cnum = document.rules.courseid.value;
 8830:         if (cdom == "" || cdom == null) {
 8831:             return;
 8832:         }
 8833:         if (cnum == "" || cnum == null) {
 8834:            return;
 8835:         }
 8836:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8837:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8838:         return;
 8839:     }
 8840: 
 8841: </script>
 8842: 
 8843: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8844: 
 8845: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8846: '.$default_form_data.
 8847:   &Apache::lonhtmlcommon::start_pick_box().
 8848:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8849:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8850:   &Apache::lonhtmlcommon::row_closure().
 8851:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8852:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8853:   &Apache::lonhtmlcommon::row_closure().
 8854:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8855:   '<input name="domainid" type="hidden" />'.$domdesc.
 8856:   &Apache::lonhtmlcommon::row_closure().
 8857:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8858:   '<input type="file" name="upfile" size="50" />'.
 8859:   &Apache::lonhtmlcommon::row_closure(1).
 8860:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8861: 
 8862: <input name="command" value="scantronupload_save" type="hidden" />
 8863: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8864: </form>
 8865: ');
 8866:     return '';
 8867: }
 8868: 
 8869: 
 8870: sub scantron_upload_scantron_data_save {
 8871:     my($r)=@_;
 8872:     my ($symb)=&get_symb($r,1);
 8873:     my $doanotherupload=
 8874: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8875: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8876: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8877: 	'</form>'."\n";
 8878:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8879: 	!&Apache::lonnet::allowed('usc',
 8880: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8881: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8882: 	if ($symb) {
 8883: 	    $r->print(&show_grading_menu_form($symb));
 8884: 	} else {
 8885: 	    $r->print($doanotherupload);
 8886: 	}
 8887: 	return '';
 8888:     }
 8889:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8890:     my $uploadedfile;
 8891:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 8892:     if (length($env{'form.upfile'}) < 2) {
 8893:         $r->print(
 8894:             &Apache::lonhtmlcommon::confirm_success(
 8895:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8896:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8897:     } else {
 8898:         my $result = 
 8899:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8900:                                             $env{'form.courseid'},$env{'form.domainid'});
 8901: 	if ($result =~ m{^/uploaded/}) {
 8902:             $r->print(
 8903:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8904:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8905:                         (length($env{'form.upfile'})-1),
 8906:                         '<span class="LC_filename">'.$result.'</span>'));
 8907:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8908:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8909:                                                        $env{'form.courseid'},$uploadedfile));
 8910: 	} else {
 8911:             $r->print(
 8912:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8913:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8914:                           $result,
 8915: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8916: 	}
 8917:     }
 8918:     if ($symb) {
 8919: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8920:     } else {
 8921: 	$r->print($doanotherupload);
 8922:     }
 8923:     return '';
 8924: }
 8925: 
 8926: sub validate_uploaded_scantron_file {
 8927:     my ($cdom,$cname,$fname) = @_;
 8928:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8929:     my @lines;
 8930:     if ($scanlines ne '-1') {
 8931:         @lines=split("\n",$scanlines,-1);
 8932:     }
 8933:     my $output;
 8934:     if (@lines) {
 8935:         my (%counts,$max_match_format);
 8936:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8937:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8938:         my %idmap = &username_to_idmap($classlist);
 8939:         foreach my $key (keys(%idmap)) {
 8940:             my $lckey = lc($key);
 8941:             $idmap{$lckey} = $idmap{$key};
 8942:         }
 8943:         my %unique_formats;
 8944:         my @formatlines = &get_scantronformat_file();
 8945:         foreach my $line (@formatlines) {
 8946:             chomp($line);
 8947:             my @config = split(/:/,$line);
 8948:             my $idstart = $config[5];
 8949:             my $idlength = $config[6];
 8950:             if (($idstart ne '') && ($idlength > 0)) {
 8951:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8952:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8953:                 } else {
 8954:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8955:                 }
 8956:             }
 8957:         }
 8958:         foreach my $key (keys(%unique_formats)) {
 8959:             my ($idstart,$idlength) = split(':',$key);
 8960:             %{$counts{$key}} = (
 8961:                                'found'   => 0,
 8962:                                'total'   => 0,
 8963:                               );
 8964:             foreach my $line (@lines) {
 8965:                 next if ($line =~ /^#/);
 8966:                 next if ($line =~ /^[\s\cz]*$/);
 8967:                 my $id = substr($line,$idstart-1,$idlength);
 8968:                 $id = lc($id);
 8969:                 if (exists($idmap{$id})) {
 8970:                     $counts{$key}{'found'} ++;
 8971:                 }
 8972:                 $counts{$key}{'total'} ++;
 8973:             }
 8974:             if ($counts{$key}{'total'}) {
 8975:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8976:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8977:                     $max_match_pct = $percent_match;
 8978:                     $max_match_format = $key;
 8979:                     $found_match_count = $counts{$key}{'found'};
 8980:                     $max_match_count = $counts{$key}{'total'};
 8981:                 }
 8982:             }
 8983:         }
 8984:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8985:             my $format_descs;
 8986:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8987:             for (my $i=0; $i<$numwithformat; $i++) {
 8988:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8989:                 if ($i<$numwithformat-2) {
 8990:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8991:                 } elsif ($i==$numwithformat-2) {
 8992:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8993:                 } elsif ($i==$numwithformat-1) {
 8994:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8995:                 }
 8996:             }
 8997:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8998:             $output .= '<br />';
 8999:             if ($found_match_count == $max_match_count) {
 9000:                 # 100% matching entries
 9001:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9002:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9003:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9004:                 &mt('Comparison of student IDs in the uploaded file with'.
 9005:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9006:                     ' in the file (for the format defined for [_3]).',
 9007:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9008:             } else {
 9009:                 # Not all entries matching? -> Show warning and additional info
 9010:                 $output .=
 9011:                     &Apache::lonhtmlcommon::confirm_success(
 9012:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9013:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9014:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9015:                     &mt('Comparison of student IDs in the uploaded file with'.
 9016:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9017:                         ' in the file (for the format defined for [_3]).',
 9018:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9019:                     '<p class="LC_info">'.
 9020:                     &mt('A low percentage of matches results from one of the following:').
 9021:                     '</p><ul>'.
 9022:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9023:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9024:                                '<i>'.$cdom.'</i>').'</li>'.
 9025:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9026:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9027:                     '</ul>';
 9028:             }
 9029:         }
 9030:     } else {
 9031:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9032:     }
 9033:     return $output;
 9034: }
 9035: 
 9036: sub valid_file {
 9037:     my ($requested_file)=@_;
 9038:     foreach my $filename (sort(&scantron_filenames())) {
 9039: 	if ($requested_file eq $filename) { return 1; }
 9040:     }
 9041:     return 0;
 9042: }
 9043: 
 9044: sub scantron_download_scantron_data {
 9045:     my ($r)=@_;
 9046:     my ($symb) = &get_symb($r,1);
 9047:     my $default_form_data=&defaultFormData($symb);
 9048:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9049:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9050:     my $file=$env{'form.scantron_selectfile'};
 9051:     if (! &valid_file($file)) {
 9052: 	$r->print('
 9053: 	<p>
 9054: 	    '.&mt('The requested filename was invalid.').'
 9055:         </p>
 9056: ');
 9057: 	$r->print(&show_grading_menu_form($symb));
 9058: 	return;
 9059:     }
 9060:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9061:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9062:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9063:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9064:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9065:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9066:     $r->print('
 9067:     <p>
 9068: 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
 9069: 	      '<a href="'.$orig.'">','</a>').'
 9070:     </p>
 9071:     <p>
 9072: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9073: 	      '<a href="'.$corrected.'">','</a>').'
 9074:     </p>
 9075:     <p>
 9076: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9077: 	      '<a href="'.$skipped.'">','</a>').'
 9078:     </p>
 9079: ');
 9080:     $r->print(&show_grading_menu_form($symb));
 9081:     return '';
 9082: }
 9083: 
 9084: sub checkscantron_results {
 9085:     my ($r) = @_;
 9086:     my ($symb)=&get_symb($r);
 9087:     if (!$symb) {return '';}
 9088:     my $grading_menu_button=&show_grading_menu_form($symb);
 9089:     my $cid = $env{'request.course.id'};
 9090:     my %lettdig = &letter_to_digits();
 9091:     my $numletts = scalar(keys(%lettdig));
 9092:     my $cnum = $env{'course.'.$cid.'.num'};
 9093:     my $cdom = $env{'course.'.$cid.'.domain'};
 9094:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9095:     my %record;
 9096:     my %scantron_config =
 9097:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9098:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9099:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9100:     my $classlist=&Apache::loncoursedata::get_classlist();
 9101:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9102:     my $navmap=Apache::lonnavmaps::navmap->new();
 9103:     unless (ref($navmap)) {
 9104:         $r->print(&navmap_errormsg());
 9105:         return '';
 9106:     }
 9107:     my $map=$navmap->getResourceByUrl($sequence);
 9108:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9109:         %grader_randomlists_by_symb,%orderedforcode);
 9110:     if (ref($map)) {
 9111:         $randomorder=$map->randomorder();
 9112:         $randompick=$map->randompick();
 9113:     }
 9114:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9115:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9116:     if ($nav_error) {
 9117:         $r->print(&navmap_errormsg());
 9118:         return '';
 9119:     }
 9120:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9121:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9122:     my ($uname,$udom);
 9123:     my (%scandata,%lastname,%bylast);
 9124:     $r->print('
 9125: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9126: 
 9127:     my @delayqueue;
 9128:     my %completedstudents;
 9129: 
 9130:     my $count=&get_todo_count($scanlines,$scan_data);
 9131:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9132:     my ($username,$domain,$started);
 9133:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9134:     if ($nav_error) {
 9135:         $r->print(&navmap_errormsg());
 9136:         return '';
 9137:     }
 9138: 
 9139:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9140:                                           'Processing first student');
 9141:     my $start=&Time::HiRes::time();
 9142:     my $i=-1;
 9143: 
 9144:     while ($i<$scanlines->{'count'}) {
 9145:         ($username,$domain,$uname)=('','','');
 9146:         $i++;
 9147:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9148:         if ($line=~/^[\s\cz]*$/) { next; }
 9149:         if ($started) {
 9150:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9151:                                                      'last student');
 9152:         }
 9153:         $started=1;
 9154:         my $scan_record=
 9155:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9156:                                                      $scan_data);
 9157:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9158:                                               \%idmap,$i)) {
 9159:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9160:                                 'Unable to find a student that matches',1);
 9161:             next;
 9162:         }
 9163:         if (exists $completedstudents{$uname}) {
 9164:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9165:                                 'Student '.$uname.' has multiple sheets',2);
 9166:             next;
 9167:         }
 9168:         my $pid = $scan_record->{'scantron.ID'};
 9169:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9170:         push(@{$bylast{$lastname{$pid}}},$pid);
 9171:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9172:         my $user = $uname.':'.$usec;
 9173:         ($username,$domain)=split(/:/,$uname);
 9174: 
 9175:         my $scancode;
 9176:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9177:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9178:             $scancode = $scan_record->{'scantron.CODE'};
 9179:         } else {
 9180:             $scancode = '';
 9181:         }
 9182: 
 9183:         my @mapresources = @resources;
 9184:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9185:         my %respnumlookup=();
 9186:         my %startline=();
 9187:         if ($randomorder || $randompick) {
 9188:             @mapresources =
 9189:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9190:                              \%orderedforcode);
 9191:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9192:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9193:                                              \%grader_partids_by_symb,\%orderedforcode,
 9194:                                              \%respnumlookup,\%startline);
 9195:             if ($randompick && $total) {
 9196:                 $lastpos = $total*$scantron_config{'Qlength'};
 9197:             }
 9198:         }
 9199:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9200:         chomp($scandata{$pid});
 9201:         $scandata{$pid} =~ s/\r$//;
 9202: 
 9203:         my $counter = -1;
 9204:         foreach my $resource (@mapresources) {
 9205:             my $parts;
 9206:             my $ressymb = $resource->symb();
 9207:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9208:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9209:                 (my $analysis,$parts) =
 9210:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9211:                                               $username,$domain,undef,
 9212:                                               $bubbles_per_row);
 9213:             } else {
 9214:                 $parts = $grader_partids_by_symb{$ressymb};
 9215:             }
 9216:             ($counter,my $recording) =
 9217:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9218:                                          $scandata{$pid},$parts,
 9219:                                          \%scantron_config,\%lettdig,$numletts,
 9220:                                          $randomorder,$randompick,
 9221:                                          \%respnumlookup,\%startline);
 9222:             $record{$pid} .= $recording;
 9223:         }
 9224:     }
 9225:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9226:     $r->print('<br />');
 9227:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9228:     $passed = 0;
 9229:     $failed = 0;
 9230:     $numstudents = 0;
 9231:     foreach my $last (sort(keys(%bylast))) {
 9232:         if (ref($bylast{$last}) eq 'ARRAY') {
 9233:             foreach my $pid (sort(@{$bylast{$last}})) {
 9234:                 my $showscandata = $scandata{$pid};
 9235:                 my $showrecord = $record{$pid};
 9236:                 $showscandata =~ s/\s/&nbsp;/g;
 9237:                 $showrecord =~ s/\s/&nbsp;/g;
 9238:                 if ($scandata{$pid} eq $record{$pid}) {
 9239:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9240:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9241: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9242: '</tr>'."\n".
 9243: '<tr class="'.$css_class.'">'."\n".
 9244: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9245:                     $passed ++;
 9246:                 } else {
 9247:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9248:                     $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".
 9249: '</tr>'."\n".
 9250: '<tr class="'.$css_class.'">'."\n".
 9251: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9252: '</tr>'."\n";
 9253:                     $failed ++;
 9254:                 }
 9255:                 $numstudents ++;
 9256:             }
 9257:         }
 9258:     }
 9259:     $r->print('<p>'.
 9260:               &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).',
 9261:                   '<b>',
 9262:                   $numstudents,
 9263:                   '</b>',
 9264:                   $env{'form.scantron_maxbubble'}).
 9265:               '</p>'
 9266:     );
 9267:     $r->print('<p>'
 9268:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9269:              .'<br />'
 9270:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9271:              .'</p>');
 9272:     if ($passed) {
 9273:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9274:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9275:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9276:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9277:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9278:                  $okstudents."\n".
 9279:                  &Apache::loncommon::end_data_table().'<br />');
 9280:     }
 9281:     if ($failed) {
 9282:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9283:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9284:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9285:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9286:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9287:                  $badstudents."\n".
 9288:                  &Apache::loncommon::end_data_table()).'<br />'.
 9289:                  &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.');  
 9290:     }
 9291:     $r->print('</form><br />'.$grading_menu_button);
 9292:     return;
 9293: }
 9294: 
 9295: sub verify_scantron_grading {
 9296:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9297:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9298:         $respnumlookup,$startline) = @_;
 9299:     my ($record,%expected,%startpos);
 9300:     return ($counter,$record) if (!ref($resource));
 9301:     return ($counter,$record) if (!$resource->is_problem());
 9302:     my $symb = $resource->symb();
 9303:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9304:     foreach my $part_id (@{$partids}) {
 9305:         $counter ++;
 9306:         $expected{$part_id} = 0;
 9307:         my $respnum = $counter;
 9308:         if ($randomorder || $randompick) {
 9309:             $respnum = $respnumlookup->{$counter};
 9310:             $startpos{$part_id} = $startline->{$counter} + 1;
 9311:         } else {
 9312:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9313:         }
 9314:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9315:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9316:             foreach my $item (@sub_lines) {
 9317:                 $expected{$part_id} += $item;
 9318:             }
 9319:         } else {
 9320:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9321:         }
 9322:     }
 9323:     if ($symb) {
 9324:         my %recorded;
 9325:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9326:         if ($returnhash{'version'}) {
 9327:             my %lasthash=();
 9328:             my $version;
 9329:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9330:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9331:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9332:                 }
 9333:             }
 9334:             foreach my $key (keys(%lasthash)) {
 9335:                 if ($key =~ /\.scantron$/) {
 9336:                     my $value = &unescape($lasthash{$key});
 9337:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9338:                     if ($value eq '') {
 9339:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9340:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9341:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9342:                             }
 9343:                         }
 9344:                     } else {
 9345:                         my @tocheck;
 9346:                         my @items = split(//,$value);
 9347:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9348:                             ($scantron_config->{'Qon'} eq 'number')) {
 9349:                             if (@items < $expected{$part_id}) {
 9350:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9351:                                 my @singles = split(//,$fragment);
 9352:                                 foreach my $pos (@singles) {
 9353:                                     if ($pos eq ' ') {
 9354:                                         push(@tocheck,$pos);
 9355:                                     } else {
 9356:                                         my $next = shift(@items);
 9357:                                         push(@tocheck,$next);
 9358:                                     }
 9359:                                 }
 9360:                             } else {
 9361:                                 @tocheck = @items;
 9362:                             }
 9363:                             foreach my $letter (@tocheck) {
 9364:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9365:                                     if ($letter !~ /^[A-J]$/) {
 9366:                                         $letter = $scantron_config->{'Qoff'};
 9367:                                     }
 9368:                                     $recorded{$part_id} .= $letter;
 9369:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9370:                                     my $digit;
 9371:                                     if ($letter !~ /^[A-J]$/) {
 9372:                                         $digit = $scantron_config->{'Qoff'};
 9373:                                     } else {
 9374:                                         $digit = $lettdig->{$letter};
 9375:                                     }
 9376:                                     $recorded{$part_id} .= $digit;
 9377:                                 }
 9378:                             }
 9379:                         } else {
 9380:                             @tocheck = @items;
 9381:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9382:                                 my $curr_sub = shift(@tocheck);
 9383:                                 my $digit;
 9384:                                 if ($curr_sub =~ /^[A-J]$/) {
 9385:                                     $digit = $lettdig->{$curr_sub}-1;
 9386:                                 }
 9387:                                 if ($curr_sub eq 'J') {
 9388:                                     $digit += scalar($numletts);
 9389:                                 }
 9390:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9391:                                     if ($j == $digit) {
 9392:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9393:                                     } else {
 9394:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9395:                                     }
 9396:                                 }
 9397:                             }
 9398:                         }
 9399:                     }
 9400:                 }
 9401:             }
 9402:         }
 9403:         foreach my $part_id (@{$partids}) {
 9404:             if ($recorded{$part_id} eq '') {
 9405:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9406:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9407:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9408:                     }
 9409:                 }
 9410:             }
 9411:             $record .= $recorded{$part_id};
 9412:         }
 9413:     }
 9414:     return ($counter,$record);
 9415: }
 9416: 
 9417: sub letter_to_digits {
 9418:     my %lettdig = (
 9419:                     A => 1,
 9420:                     B => 2,
 9421:                     C => 3,
 9422:                     D => 4,
 9423:                     E => 5,
 9424:                     F => 6,
 9425:                     G => 7,
 9426:                     H => 8,
 9427:                     I => 9,
 9428:                     J => 0,
 9429:                   );
 9430:     return %lettdig;
 9431: }
 9432: 
 9433: 
 9434: #-------- end of section for handling grading scantron forms -------
 9435: #
 9436: #-------------------------------------------------------------------
 9437: 
 9438: #-------------------------- Menu interface -------------------------
 9439: #
 9440: #--- Show a Grading Menu button - Calls the next routine ---
 9441: sub show_grading_menu_form {
 9442:     my ($symb)=@_;
 9443:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9444: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9445: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9446: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9447: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9448: 	'</form>'."\n";
 9449:     return $result;
 9450: }
 9451: 
 9452: # -- Retrieve choices for grading form
 9453: sub savedState {
 9454:     my %savedState = ();
 9455:     if ($env{'form.saveState'}) {
 9456: 	foreach (split(/:/,$env{'form.saveState'})) {
 9457: 	    my ($key,$value) = split(/=/,$_,2);
 9458: 	    $savedState{$key} = $value;
 9459: 	}
 9460:     }
 9461:     return \%savedState;
 9462: }
 9463: 
 9464: #--- Href with symb and command ---
 9465: 
 9466: sub href_symb_cmd {
 9467:     my ($symb,$cmd)=@_;
 9468:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9469: }
 9470: 
 9471: sub grading_menu {
 9472:     my ($request) = @_;
 9473:     my ($symb)=&get_symb($request);
 9474:     if (!$symb) {return '';}
 9475:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9476:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9477: 
 9478:     $request->print($table);
 9479:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9480:                   'handgrade'=>$hdgrade,
 9481:                   'probTitle'=>$probTitle,
 9482:                   'command'=>'submit_options',
 9483:                   'saveState'=>"",
 9484:                   'gradingMenu'=>1,
 9485:                   'showgrading'=>"yes");
 9486:     
 9487:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9488:     
 9489:     $fields{'command'} = 'csvform';
 9490:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9491:     
 9492:     $fields{'command'} = 'processclicker';
 9493:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9494:     
 9495:     $fields{'command'} = 'scantron_selectphase';
 9496:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9497:     
 9498:     my @menu = ({	categorytitle=>'Course Grading',
 9499:             items =>[
 9500:                         {	linktext => 'Manual Grading/View Submissions',
 9501:                     		url => $url1,
 9502:                     		permission => 'F',
 9503:                     		icon => 'edit-find-replace.png',
 9504:                     		linktitle => 'Start the process of hand grading submissions.'
 9505:                         },
 9506:                 	    {	linktext => 'Upload Scores',
 9507:                     		url => $url2,
 9508:                     		permission => 'F',
 9509:                     		icon => 'uploadscores.png',
 9510:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9511:                 	    },
 9512:                 	    {	linktext => 'Process Clicker',
 9513:                     		url => $url3,
 9514:                     		permission => 'F',
 9515:                     		icon => 'addClickerInfoFile.png',
 9516:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9517:                 	    },
 9518:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9519:                     		url => $url4,
 9520:                     		permission => 'F',
 9521:                     		icon => 'stat.png',
 9522:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9523:                 	    }
 9524:                     ]
 9525:             });
 9526: 
 9527:     #$fields{'command'} = 'verify';
 9528:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9529:     #
 9530:     # Create the menu
 9531:     my $Str;
 9532:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9533:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9534:     $Str .= '<input type="hidden" name="command" value="" />'.
 9535:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9536: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9537: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9538: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9539: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9540: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9541: 
 9542:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9543:     #$menudata->{'jscript'}
 9544:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9545:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9546:         ' /> '.
 9547:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9548:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9549: 
 9550:     $Str .="</form>\n";
 9551:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9552:     $request->print(<<GRADINGMENUJS);
 9553: <script type="text/javascript" language="javascript">
 9554:     function checkChoice(formname,val,cmdx) {
 9555: 	if (val <= 2) {
 9556: 	    var cmd = radioSelection(formname.radioChoice);
 9557: 	    var cmdsave = cmd;
 9558: 	} else {
 9559: 	    cmd = cmdx;
 9560: 	    cmdsave = 'submission';
 9561: 	}
 9562: 	formname.command.value = cmd;
 9563: 	if (val < 5) formname.submit();
 9564: 	if (val == 5) {
 9565: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9566: 	        return false;
 9567: 	    } else {
 9568: 	        formname.submit();
 9569: 	    }
 9570: 	}
 9571:     }
 9572: 
 9573:     function checkReceiptNo(formname,nospace) {
 9574: 	var receiptNo = formname.receipt.value;
 9575: 	var checkOpt = false;
 9576: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9577: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9578: 	if (checkOpt) {
 9579: 	    alert("$receiptalert");
 9580: 	    formname.receipt.value = "";
 9581: 	    formname.receipt.focus();
 9582: 	    return false;
 9583: 	}
 9584: 	return true;
 9585:     }
 9586: </script>
 9587: GRADINGMENUJS
 9588:     &commonJSfunctions($request);
 9589:     return $Str;    
 9590: }
 9591: 
 9592: 
 9593: #--- Displays the submissions first page -------
 9594: sub submit_options {
 9595:     my ($request) = @_;
 9596:     my ($symb)=&get_symb($request);
 9597:     if (!$symb) {return '';}
 9598:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9599: 
 9600:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9601:     $request->print(<<GRADINGMENUJS);
 9602: <script type="text/javascript" language="javascript">
 9603:     function checkChoice(formname,val,cmdx) {
 9604: 	if (val <= 2) {
 9605: 	    var cmd = radioSelection(formname.radioChoice);
 9606: 	    var cmdsave = cmd;
 9607: 	} else {
 9608: 	    cmd = cmdx;
 9609: 	    cmdsave = 'submission';
 9610: 	}
 9611: 	formname.command.value = cmd;
 9612: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9613: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9614: 	if (val < 5) formname.submit();
 9615: 	if (val == 5) {
 9616: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9617: 	    formname.submit();
 9618: 	}
 9619: 	if (val < 7) formname.submit();
 9620:     }
 9621: 
 9622:     function checkReceiptNo(formname,nospace) {
 9623: 	var receiptNo = formname.receipt.value;
 9624: 	var checkOpt = false;
 9625: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9626: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9627: 	if (checkOpt) {
 9628: 	    alert("$receiptalert");
 9629: 	    formname.receipt.value = "";
 9630: 	    formname.receipt.focus();
 9631: 	    return false;
 9632: 	}
 9633: 	return true;
 9634:     }
 9635: </script>
 9636: GRADINGMENUJS
 9637:     &commonJSfunctions($request);
 9638:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9639:     my $result;
 9640:     my (undef,$sections) = &getclasslist('all','0');
 9641:     my $savedState = &savedState();
 9642:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9643:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9644:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9645:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9646: 
 9647:     # Preselect sections
 9648:     my $selsec="";
 9649:     if (ref($sections)) {
 9650:         foreach my $section (sort(@$sections)) {
 9651:             $selsec.='<option value="'.$section.'" '.
 9652:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9653:         }
 9654:     }
 9655: 
 9656:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9657: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9658: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9659: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9660: 	'<input type="hidden" name="command"     value="" />'."\n".
 9661: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9662: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9663: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9664: 
 9665:     $result.='
 9666: <h2>
 9667:   '.&mt('Grade Current Resource').'
 9668: </h2>
 9669: <div>
 9670:   '.$table.'
 9671: </div>
 9672: 
 9673: <div class="LC_columnSection">
 9674:   
 9675:     <fieldset>
 9676:       <legend>
 9677:        '.&mt('Sections').'
 9678:       </legend>
 9679:       <select name="section" multiple="multiple" size="5">'."\n";
 9680:     $result.= $selsec;
 9681:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9682:     $result.='
 9683:     </fieldset>
 9684:   
 9685:     <fieldset>
 9686:       <legend>
 9687:         '.&mt('Groups').'
 9688:       </legend>
 9689:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9690:     </fieldset>
 9691:   
 9692:     <fieldset>
 9693:       <legend>
 9694:         '.&mt('Access Status').'
 9695:       </legend>
 9696:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9697:     </fieldset>
 9698:   
 9699:     <fieldset>
 9700:       <legend>
 9701:         '.&mt('Submission Status').'
 9702:       </legend>
 9703:       <select name="submitonly" size="5">
 9704: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9705: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9706: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9707: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9708:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9709:       </select>
 9710:     </fieldset>
 9711:   
 9712: </div>
 9713: 
 9714: <br />
 9715:           <div>
 9716:             <div>
 9717:               <label>
 9718:                 <input type="radio" name="radioChoice" value="submission" '.
 9719:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9720:              &mt('Select individual students to grade and view submissions.').'
 9721: 	      </label> 
 9722:             </div>
 9723:             <div>
 9724: 	      <label>
 9725:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9726:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 9727:                     &mt('Grade all selected students in a grading table.').'
 9728:               </label>
 9729:             </div>
 9730:             <div>
 9731: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9732:             </div>
 9733:           </div>
 9734: 
 9735: 
 9736:         <h2>
 9737:          '.&mt('Grade Complete Folder for One Student').'
 9738:         </h2>
 9739:         <div>
 9740:             <div>
 9741:               <label>
 9742:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 9743: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 9744:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 9745:               </label>
 9746:             </div>
 9747:             <div>
 9748: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9749:             </div>
 9750:         </div>
 9751:   </form>';
 9752:     $result .= &show_grading_menu_form($symb);
 9753:     return $result;
 9754: }
 9755: 
 9756: sub reset_perm {
 9757:     undef(%perm);
 9758: }
 9759: 
 9760: sub init_perm {
 9761:     &reset_perm();
 9762:     foreach my $test_perm ('vgr','mgr','opa') {
 9763: 
 9764: 	my $scope = $env{'request.course.id'};
 9765: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9766: 
 9767: 	    $scope .= '/'.$env{'request.course.sec'};
 9768: 	    if ( $perm{$test_perm}=
 9769: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9770: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9771: 	    } else {
 9772: 		delete($perm{$test_perm});
 9773: 	    }
 9774: 	}
 9775:     }
 9776: }
 9777: 
 9778: sub init_old_essays {
 9779:     my ($symb,$apath,$adom,$aname) = @_;
 9780:     if ($symb ne '') {
 9781:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9782:         if (keys(%essays) > 0) {
 9783:             $old_essays{$symb} = \%essays;
 9784:         }
 9785:     }
 9786:     return;
 9787: }
 9788: 
 9789: sub reset_old_essays {
 9790:     undef(%old_essays);
 9791: }
 9792: 
 9793: sub gather_clicker_ids {
 9794:     my %clicker_ids;
 9795: 
 9796:     my $classlist = &Apache::loncoursedata::get_classlist();
 9797: 
 9798:     # Set up a couple variables.
 9799:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9800:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9801:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9802: 
 9803:     foreach my $student (keys(%$classlist)) {
 9804:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9805:         my $username = $classlist->{$student}->[$username_idx];
 9806:         my $domain   = $classlist->{$student}->[$domain_idx];
 9807:         my $clickers =
 9808: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9809:         foreach my $id (split(/\,/,$clickers)) {
 9810:             $id=~s/^[\#0]+//;
 9811:             $id=~s/[\-\:]//g;
 9812:             if (exists($clicker_ids{$id})) {
 9813: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9814:             } else {
 9815: 		$clicker_ids{$id}=$username.':'.$domain;
 9816:             }
 9817:         }
 9818:     }
 9819:     return %clicker_ids;
 9820: }
 9821: 
 9822: sub gather_adv_clicker_ids {
 9823:     my %clicker_ids;
 9824:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9825:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9826:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9827:     foreach my $element (sort(keys(%coursepersonnel))) {
 9828:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9829:             my ($puname,$pudom)=split(/\:/,$person);
 9830:             my $clickers =
 9831: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9832:             foreach my $id (split(/\,/,$clickers)) {
 9833: 		$id=~s/^[\#0]+//;
 9834:                 $id=~s/[\-\:]//g;
 9835: 		if (exists($clicker_ids{$id})) {
 9836: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9837: 		} else {
 9838: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9839: 		}
 9840:             }
 9841:         }
 9842:     }
 9843:     return %clicker_ids;
 9844: }
 9845: 
 9846: sub clicker_grading_parameters {
 9847:     return ('gradingmechanism' => 'scalar',
 9848:             'upfiletype' => 'scalar',
 9849:             'specificid' => 'scalar',
 9850:             'pcorrect' => 'scalar',
 9851:             'pincorrect' => 'scalar');
 9852: }
 9853: 
 9854: sub process_clicker {
 9855:     my ($r)=@_;
 9856:     my ($symb)=&get_symb($r);
 9857:     if (!$symb) {return '';}
 9858:     my $result=&checkforfile_js();
 9859:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 9860:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 9861:     $result.=$table;
 9862:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 9863:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 9864:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 9865:         '</b></td></tr>'."\n";
 9866:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 9867: # Attempt to restore parameters from last session, set defaults if not present
 9868:     my %Saveable_Parameters=&clicker_grading_parameters();
 9869:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9870:                                                  \%Saveable_Parameters);
 9871:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9872:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9873:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9874:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9875: 
 9876:     my %checked;
 9877:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9878:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9879:           $checked{$gradingmechanism}=' checked="checked"';
 9880:        }
 9881:     }
 9882: 
 9883:     my $upload=&mt("Upload File");
 9884:     my $type=&mt("Type");
 9885:     my $attendance=&mt("Award points just for participation");
 9886:     my $personnel=&mt("Correctness determined from response by course personnel");
 9887:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9888:     my $given=&mt("Correctness determined from given list of answers").' '.
 9889:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9890:     my $pcorrect=&mt("Percentage points for correct solution");
 9891:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9892:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9893:                                                    {'iclicker' => 'i>clicker',
 9894:                                                     'interwrite' => 'interwrite PRS',
 9895:                                                     'turning' => 'Turning Technologies'});
 9896:     $symb = &Apache::lonenc::check_encrypt($symb);
 9897:     $result.=<<ENDUPFORM;
 9898: <script type="text/javascript">
 9899: function sanitycheck() {
 9900: // Accept only integer percentages
 9901:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9902:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9903: // Find out grading choice
 9904:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9905:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9906:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9907:       }
 9908:    }
 9909: // By default, new choice equals user selection
 9910:    newgradingchoice=gradingchoice;
 9911: // Not good to give more points for false answers than correct ones
 9912:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9913:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9914:    }
 9915: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9916:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9917:       document.forms.gradesupload.pcorrect.value=100;
 9918:       document.forms.gradesupload.pincorrect.value=100;
 9919:    }
 9920: // If the values are different, cannot be attendance only
 9921:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9922:        (gradingchoice=='attendance')) {
 9923:        newgradingchoice='personnel';
 9924:    }
 9925: // Change grading choice to new one
 9926:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9927:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9928:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9929:       } else {
 9930:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9931:       }
 9932:    }
 9933: // Remember the old state
 9934:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9935: }
 9936: </script>
 9937: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9938: <input type="hidden" name="symb" value="$symb" />
 9939: <input type="hidden" name="command" value="processclickerfile" />
 9940: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9941: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9942: <input type="file" name="upfile" size="50" />
 9943: <br /><label>$type: $selectform</label>
 9944: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9945: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9946: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9947: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9948: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9949: <br />&nbsp;&nbsp;&nbsp;
 9950: <input type="text" name="givenanswer" size="50" />
 9951: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9952: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9953: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9954: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9955: </form>
 9956: ENDUPFORM
 9957:     $result.='</td></tr></table>'."\n".
 9958:              '</td></tr></table><br /><br />'."\n";
 9959:     $result.=&show_grading_menu_form($symb);
 9960:     return $result;
 9961: }
 9962: 
 9963: sub process_clicker_file {
 9964:     my ($r)=@_;
 9965:     my ($symb)=&get_symb($r);
 9966:     if (!$symb) {return '';}
 9967: 
 9968:     my %Saveable_Parameters=&clicker_grading_parameters();
 9969:     &Apache::loncommon::store_course_settings('grades_clicker',
 9970:                                               \%Saveable_Parameters);
 9971: 
 9972:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9973:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9974: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9975: 	return $result.&show_grading_menu_form($symb);
 9976:     }
 9977:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9978:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9979:         return $result.&show_grading_menu_form($symb);
 9980:     }
 9981:     my $foundgiven=0;
 9982:     if ($env{'form.gradingmechanism'} eq 'given') {
 9983:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9984:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9985:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9986:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9987:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9988:         $foundgiven=$#answers+1;
 9989:     }
 9990:     my %clicker_ids=&gather_clicker_ids();
 9991:     my %correct_ids;
 9992:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9993: 	%correct_ids=&gather_adv_clicker_ids();
 9994:     }
 9995:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9996: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9997: 	   $correct_id=~tr/a-z/A-Z/;
 9998: 	   $correct_id=~s/\s//gs;
 9999: 	   $correct_id=~s/^[\#0]+//;
10000:            $correct_id=~s/[\-\:]//g;
10001:            if ($correct_id) {
10002: 	      $correct_ids{$correct_id}='specified';
10003:            }
10004:         }
10005:     }
10006:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10007: 	$result.=&mt('Score based on attendance only');
10008:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10009:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10010:     } else {
10011: 	my $number=0;
10012: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10013: 	foreach my $id (sort(keys(%correct_ids))) {
10014: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10015: 	    if ($correct_ids{$id} eq 'specified') {
10016: 		$result.=&mt('specified');
10017: 	    } else {
10018: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10019: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10020: 	    }
10021: 	    $number++;
10022: 	}
10023:         $result.="</p>\n";
10024:         if ($number==0) {
10025:             $result .=
10026:                  &Apache::lonhtmlcommon::confirm_success(
10027:                      &mt('No IDs found to determine correct answer'),1);
10028:             return $result,.&show_grading_menu_form($symb);
10029:         }
10030:     }
10031:     if (length($env{'form.upfile'}) < 2) {
10032:         $result .=
10033:             &Apache::lonhtmlcommon::confirm_success(
10034:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10035:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10036:         return $result.&show_grading_menu_form($symb);
10037:     }
10038: 
10039: # Were able to get all the info needed, now analyze the file
10040: 
10041:     $result.=&Apache::loncommon::studentbrowser_javascript();
10042:     $symb = &Apache::lonenc::check_encrypt($symb);
10043:     my $heading=&mt('Scanning clicker file');
10044:     $result.=(<<ENDHEADER);
10045: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
10046: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
10047: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
10048: <form method="post" action="/adm/grades" name="clickeranalysis">
10049: <input type="hidden" name="symb" value="$symb" />
10050: <input type="hidden" name="command" value="assignclickergrades" />
10051: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10052: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10053: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10054: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10055: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10056: ENDHEADER
10057:     if ($env{'form.gradingmechanism'} eq 'given') {
10058:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10059:     } 
10060:     my %responses;
10061:     my @questiontitles;
10062:     my $errormsg='';
10063:     my $number=0;
10064:     if ($env{'form.upfiletype'} eq 'iclicker') {
10065: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10066:     }
10067:     if ($env{'form.upfiletype'} eq 'interwrite') {
10068:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10069:     }
10070:     if ($env{'form.upfiletype'} eq 'turning') {
10071:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10072:     }
10073:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10074:              '<input type="hidden" name="number" value="'.$number.'" />'.
10075:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10076:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10077:              '<br />';
10078:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10079:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10080:        return $result.&show_grading_menu_form($symb);
10081:     } 
10082: # Remember Question Titles
10083: # FIXME: Possibly need delimiter other than ":"
10084:     for (my $i=0;$i<$number;$i++) {
10085:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10086:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10087:     }
10088:     my $correct_count=0;
10089:     my $student_count=0;
10090:     my $unknown_count=0;
10091: # Match answers with usernames
10092: # FIXME: Possibly need delimiter other than ":"
10093:     foreach my $id (keys(%responses)) {
10094:        if ($correct_ids{$id}) {
10095:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10096:           $correct_count++;
10097:        } elsif ($clicker_ids{$id}) {
10098:           if ($clicker_ids{$id}=~/\,/) {
10099: # More than one user with the same clicker!
10100:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10101:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10102:                            "<select name='multi".$id."'>";
10103:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10104:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10105:              }
10106:              $result.='</select>';
10107:              $unknown_count++;
10108:           } else {
10109: # Good: found one and only one user with the right clicker
10110:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10111:              $student_count++;
10112:           }
10113:        } else {
10114:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10115:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10116:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10117:                    "\n".&mt("Domain").": ".
10118:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10119:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10120:           $unknown_count++;
10121:        }
10122:     }
10123:     $result.='<hr />'.
10124:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10125:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10126:        if ($correct_count==0) {
10127:           $errormsg.="Found no correct answers for grading!";
10128:        } elsif ($correct_count>1) {
10129:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10130:        }
10131:     }
10132:     if ($number<1) {
10133:        $errormsg.="Found no questions.";
10134:     }
10135:     if ($errormsg) {
10136:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10137:     } else {
10138:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10139:     }
10140:     $result.='</form></td></tr></table>'."\n".
10141:              '</td></tr></table><br /><br />'."\n";
10142:     return $result.&show_grading_menu_form($symb);
10143: }
10144: 
10145: sub iclicker_eval {
10146:     my ($questiontitles,$responses)=@_;
10147:     my $number=0;
10148:     my $errormsg='';
10149:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10150:         my %components=&Apache::loncommon::record_sep($line);
10151:         my @entries=map {$components{$_}} (sort(keys(%components)));
10152: 	if ($entries[0] eq 'Question') {
10153: 	    for (my $i=3;$i<$#entries;$i+=6) {
10154: 		$$questiontitles[$number]=$entries[$i];
10155: 		$number++;
10156: 	    }
10157: 	}
10158: 	if ($entries[0]=~/^\#/) {
10159: 	    my $id=$entries[0];
10160: 	    my @idresponses;
10161: 	    $id=~s/^[\#0]+//;
10162: 	    for (my $i=0;$i<$number;$i++) {
10163: 		my $idx=3+$i*6;
10164:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10165: 		push(@idresponses,$entries[$idx]);
10166: 	    }
10167: 	    $$responses{$id}=join(',',@idresponses);
10168: 	}
10169:     }
10170:     return ($errormsg,$number);
10171: }
10172: 
10173: sub interwrite_eval {
10174:     my ($questiontitles,$responses)=@_;
10175:     my $number=0;
10176:     my $errormsg='';
10177:     my $skipline=1;
10178:     my $questionnumber=0;
10179:     my %idresponses=();
10180:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10181:         my %components=&Apache::loncommon::record_sep($line);
10182:         my @entries=map {$components{$_}} (sort(keys(%components)));
10183:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10184:         if ($entries[1] eq 'Response') { $skipline=1; }
10185:         next if $skipline;
10186:         if ($entries[0]!=$questionnumber) {
10187:            $questionnumber=$entries[0];
10188:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10189:            $number++;
10190:         }
10191:         my $id=$entries[4];
10192:         $id=~s/^[\#0]+//;
10193:         $id=~s/^v\d*\://i;
10194:         $id=~s/[\-\:]//g;
10195:         $idresponses{$id}[$number]=$entries[6];
10196:     }
10197:     foreach my $id (keys(%idresponses)) {
10198:        $$responses{$id}=join(',',@{$idresponses{$id}});
10199:        $$responses{$id}=~s/^\s*\,//;
10200:     }
10201:     return ($errormsg,$number);
10202: }
10203: 
10204: sub turning_eval {
10205:     my ($questiontitles,$responses)=@_;
10206:     my $number=0;
10207:     my $errormsg='';
10208:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10209:         my %components=&Apache::loncommon::record_sep($line);
10210:         my @entries=map {$components{$_}} (sort(keys(%components)));
10211:         if ($#entries>$number) { $number=$#entries; }
10212:         my $id=$entries[0];
10213:         my @idresponses;
10214:         $id=~s/^[\#0]+//;
10215:         unless ($id) { next; }
10216:         for (my $idx=1;$idx<=$#entries;$idx++) {
10217:             $entries[$idx]=~s/\,/\;/g;
10218:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10219:             push(@idresponses,$entries[$idx]);
10220:         }
10221:         $$responses{$id}=join(',',@idresponses);
10222:     }
10223:     for (my $i=1; $i<=$number; $i++) {
10224:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10225:     }
10226:     return ($errormsg,$number);
10227: }
10228: 
10229: sub assign_clicker_grades {
10230:     my ($r)=@_;
10231:     my ($symb)=&get_symb($r);
10232:     if (!$symb) {return '';}
10233: # See which part we are saving to
10234:     my $res_error;
10235:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10236:     if ($res_error) {
10237:         return &navmap_errormsg();
10238:     }
10239: # FIXME: This should probably look for the first handgradeable part
10240:     my $part=$$partlist[0];
10241: # Start screen output
10242:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10243: 
10244:     $result .= '<br />'.
10245:                &Apache::loncommon::start_data_table().
10246:                &Apache::loncommon::start_data_table_header_row().
10247:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10248:                &Apache::loncommon::end_data_table_header_row().
10249:                &Apache::loncommon::start_data_table_row().'<td>';
10250: 
10251: # Get correct result
10252: # FIXME: Possibly need delimiter other than ":"
10253:     my @correct=();
10254:     my $gradingmechanism=$env{'form.gradingmechanism'};
10255:     my $number=$env{'form.number'};
10256:     if ($gradingmechanism ne 'attendance') {
10257:        foreach my $key (keys(%env)) {
10258:           if ($key=~/^form\.correct\:/) {
10259:              my @input=split(/\,/,$env{$key});
10260:              for (my $i=0;$i<=$#input;$i++) {
10261:                  if (($correct[$i]) && ($input[$i]) &&
10262:                      ($correct[$i] ne $input[$i])) {
10263:                     $result.='<br /><span class="LC_warning">'.
10264:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10265:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10266:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10267:                     $correct[$i]=$input[$i];
10268:                  }
10269:              }
10270:           }
10271:        }
10272:        for (my $i=0;$i<$number;$i++) {
10273:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10274:              $result.='<br /><span class="LC_error">'.
10275:                       &mt('No correct result given for question "[_1]"!',
10276:                           $env{'form.question:'.$i}).'</span>';
10277:           }
10278:        }
10279:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10280:     }
10281: # Start grading
10282:     my $pcorrect=$env{'form.pcorrect'};
10283:     my $pincorrect=$env{'form.pincorrect'};
10284:     my $storecount=0;
10285:     my %users=();
10286:     foreach my $key (keys(%env)) {
10287:        my $user='';
10288:        if ($key=~/^form\.student\:(.*)$/) {
10289:           $user=$1;
10290:        }
10291:        if ($key=~/^form\.unknown\:(.*)$/) {
10292:           my $id=$1;
10293:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10294:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10295:           } elsif ($env{'form.multi'.$id}) {
10296:              $user=$env{'form.multi'.$id};
10297:           }
10298:        }
10299:        if ($user) {
10300:           if ($users{$user}) {
10301:              $result.='<br /><span class="LC_warning">'.
10302:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10303:                       '</span><br />';
10304:           }
10305:           $users{$user}=1;
10306:           my @answer=split(/\,/,$env{$key});
10307:           my $sum=0;
10308:           my $realnumber=$number;
10309:           for (my $i=0;$i<$number;$i++) {
10310:              if  ($correct[$i] eq '-') {
10311:                 $realnumber--;
10312:              } elsif ($answer[$i]) {
10313:                 if ($gradingmechanism eq 'attendance') {
10314:                    $sum+=$pcorrect;
10315:                 } elsif ($correct[$i] eq '*') {
10316:                    $sum+=$pcorrect;
10317:                 } else {
10318: # We actually grade if correct or not
10319:                    my $increment=$pincorrect;
10320: # Special case: numerical answer "0"
10321:                    if ($correct[$i] eq '0') {
10322:                       if ($answer[$i]=~/^[0\.]+$/) {
10323:                          $increment=$pcorrect;
10324:                       }
10325: # General numerical answer, both evaluate to something non-zero
10326:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10327:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10328:                          $increment=$pcorrect;
10329:                       }
10330: # Must be just alphanumeric
10331:                    } elsif ($answer[$i] eq $correct[$i]) {
10332:                       $increment=$pcorrect;
10333:                    }
10334:                    $sum+=$increment;
10335:                 }
10336:              }
10337:           }
10338:           my $ave=$sum/(100*$realnumber);
10339: # Store
10340:           my ($username,$domain)=split(/\:/,$user);
10341:           my %grades=();
10342:           $grades{"resource.$part.solved"}='correct_by_override';
10343:           $grades{"resource.$part.awarded"}=$ave;
10344:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10345:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10346:                                                  $env{'request.course.id'},
10347:                                                  $domain,$username);
10348:           if ($returncode ne 'ok') {
10349:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10350:           } else {
10351:              $storecount++;
10352:           }
10353:        }
10354:     }
10355: # We are done
10356:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10357:              '</td>'.
10358:              &Apache::loncommon::end_data_table_row().
10359:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10360:     return $result.&show_grading_menu_form($symb);
10361: }
10362: 
10363: sub navmap_errormsg {
10364:     return '<div class="LC_error">'.
10365:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10366:            &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>').
10367:            '</div>';
10368: }
10369: 
10370: sub startpage {
10371:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10372:     if ($nomenu) {
10373:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10374:     } else {
10375:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10376:                                                  {'bread_crumbs' => $crumbs}));
10377:     }
10378:     unless ($nodisplayflag) {
10379:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10380:     }
10381: }
10382: 
10383: sub handler {
10384:     my $request=$_[0];
10385:     &reset_caches();
10386:     if ($request->header_only) {
10387:         &Apache::loncommon::content_type($request,'text/html');
10388:         $request->send_http_header;
10389:         return OK;
10390:     }
10391:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10392: 
10393:     my $symb=&get_symb($request,1);
10394:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10395:     my $command=$commands[0];
10396: 
10397:     if ($#commands > 0) {
10398: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10399:     }
10400: 
10401:     $ssi_error = 0;
10402:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10403:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10404:                                                     {'bread_crumbs' => $brcrum});
10405:     if ($symb eq '' && $command eq '') {
10406: 	if ($env{'user.adv'}) {
10407:             &Apache::loncommon::content_type($request,'text/html');
10408:             $request->send_http_header;
10409:             $request->print($start_page);
10410: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10411: 		($env{'form.codethree'})) {
10412: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10413: 		    $env{'form.codethree'};
10414: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10415: 		    &Apache::lonnet::checkin($token);
10416: 		if ($tsymb) {
10417: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10418: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10419: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10420: 					  ('grade_username' => $tuname,
10421: 					   'grade_domain' => $tudom,
10422: 					   'grade_courseid' => $tcrsid,
10423: 					   'grade_symb' => $tsymb)));
10424: 		    } else {
10425: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10426: 		    }
10427: 		} else {
10428: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10429: 		}
10430: 	    } else {
10431: 		$request->print(&Apache::lonxml::tokeninputfield());
10432: 	    }
10433:         } elsif ($env{'request.course.id'}) {
10434:             &init_perm(); 
10435:             if (!%perm) {
10436:                 $request->internal_redirect('/adm/quickgrades');
10437:                 return OK;
10438:             } else {
10439:                 &Apache::loncommon::content_type($request,'text/html');
10440:                 $request->send_http_header;
10441:                 $request->print($start_page);
10442:             }
10443:         }
10444:     } else {
10445:         &init_perm();
10446:         if (!$env{'request.course.id'}) {
10447:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10448:                     ($command =~ /^scantronupload/)) {
10449:                 # Not in a course.
10450:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10451:                 return HTTP_NOT_ACCEPTABLE;
10452:             }
10453:         } elsif (!%perm) {
10454:             $request->internal_redirect('/adm/quickgrades');
10455:         }
10456:         &Apache::loncommon::content_type($request,'text/html');
10457:         $request->send_http_header;
10458:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10459:             $request->print($start_page); 
10460:         }
10461: 	if ($command eq 'submission' && $perm{'vgr'}) {
10462:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10463:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10464:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10465:                     &choose_task_version_form($symb,$env{'form.student'},
10466:                                               $env{'form.userdom'});
10467:             }
10468:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10469:             if ($versionform) {
10470:                 $request->print($versionform);
10471:             }
10472:             $request->print('<br clear="all" />');
10473: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10474:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10475:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10476:                 &choose_task_version_form($symb,$env{'form.student'},
10477:                                           $env{'form.userdom'},
10478:                                           $env{'form.inhibitmenu'});
10479:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10480:             if ($versionform) {
10481:                 $request->print($versionform);
10482:             }
10483:             $request->print('<br clear="all" />');
10484:             $request->print(&show_previous_task_version($request,$symb));
10485: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10486: 	    &pickStudentPage($request);
10487: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10488: 	    &displayPage($request);
10489: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10490: 	    &updateGradeByPage($request);
10491: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10492: 	    &processGroup($request);
10493: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10494: 	    $request->print(&grading_menu($request));
10495: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10496: 	    $request->print(&submit_options($request));
10497: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10498: 	    $request->print(&viewgrades($request));
10499: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10500: 	    $request->print(&processHandGrade($request));
10501: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10502: 	    $request->print(&editgrades($request));
10503: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10504: 	    $request->print(&verifyreceipt($request));
10505:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10506:             $request->print(&process_clicker($request));
10507:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10508:             $request->print(&process_clicker_file($request));
10509:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10510:             $request->print(&assign_clicker_grades($request));
10511: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10512: 	    $request->print(&upcsvScores_form($request));
10513: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10514: 	    $request->print(&csvupload($request));
10515: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10516: 	    $request->print(&csvuploadmap($request));
10517: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10518: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10519: 		$request->print(&csvuploadoptions($request));
10520: 	    } else {
10521: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10522: 		    $env{'form.upfile_associate'} = 'reverse';
10523: 		} else {
10524: 		    $env{'form.upfile_associate'} = 'forward';
10525: 		}
10526: 		$request->print(&csvuploadmap($request));
10527: 	    }
10528: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10529: 	    $request->print(&csvuploadassign($request));
10530: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10531: 	    $request->print(&scantron_selectphase($request));
10532:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10533:  	    $request->print(&scantron_do_warning($request));
10534: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10535: 	    $request->print(&scantron_validate_file($request));
10536: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10537: 	    $request->print(&scantron_process_students($request));
10538:  	} elsif ($command eq 'scantronupload' && 
10539:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10540: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10541:  	    $request->print(&scantron_upload_scantron_data($request)); 
10542:  	} elsif ($command eq 'scantronupload_save' &&
10543:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10544: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10545:  	    $request->print(&scantron_upload_scantron_data_save($request));
10546:  	} elsif ($command eq 'scantron_download' &&
10547: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10548:  	    $request->print(&scantron_download_scantron_data($request));
10549:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10550:             $request->print(&checkscantron_results($request));     
10551: 	} elsif ($command) {
10552: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10553: 	}
10554:     }
10555:     if ($ssi_error) {
10556: 	&ssi_print_error($request);
10557:     }
10558:     $request->print(&Apache::loncommon::end_page());
10559:     &reset_caches();
10560:     return OK;
10561: }
10562: 
10563: 1;
10564: 
10565: __END__;
10566: 
10567: 
10568: =head1 NAME
10569: 
10570: Apache::grades
10571: 
10572: =head1 SYNOPSIS
10573: 
10574: Handles the viewing of grades.
10575: 
10576: This is part of the LearningOnline Network with CAPA project
10577: described at http://www.lon-capa.org.
10578: 
10579: =head1 OVERVIEW
10580: 
10581: Do an ssi with retries:
10582: While I'd love to factor out this with the vesrion in lonprintout,
10583: 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
10584: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10585: 
10586: At least the logic that drives this has been pulled out into loncommon.
10587: 
10588: 
10589: 
10590: ssi_with_retries - Does the server side include of a resource.
10591:                      if the ssi call returns an error we'll retry it up to
10592:                      the number of times requested by the caller.
10593:                      If we still have a problem, no text is appended to the
10594:                      output and we set some global variables.
10595:                      to indicate to the caller an SSI error occurred.  
10596:                      All of this is supposed to deal with the issues described
10597:                      in LON-CAPA BZ 5631 see:
10598:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10599:                      by informing the user that this happened.
10600: 
10601: Parameters:
10602:   resource   - The resource to include.  This is passed directly, without
10603:                interpretation to lonnet::ssi.
10604:   form       - The form hash parameters that guide the interpretation of the resource
10605:                
10606:   retries    - Number of retries allowed before giving up completely.
10607: Returns:
10608:   On success, returns the rendered resource identified by the resource parameter.
10609: Side Effects:
10610:   The following global variables can be set:
10611:    ssi_error                - If an unrecoverable error occurred this becomes true.
10612:                               It is up to the caller to initialize this to false
10613:                               if desired.
10614:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10615:                               of the resource that could not be rendered by the ssi
10616:                               call.
10617:    ssi_error_message   - The error string fetched from the ssi response
10618:                               in the event of an error.
10619: 
10620: 
10621: =head1 HANDLER SUBROUTINE
10622: 
10623: ssi_with_retries()
10624: 
10625: =head1 SUBROUTINES
10626: 
10627: =over
10628: 
10629: =item scantron_get_correction() : 
10630: 
10631:    Builds the interface screen to interact with the operator to fix a
10632:    specific error condition in a specific scanline
10633: 
10634:  Arguments:
10635:     $r           - Apache request object
10636:     $i           - number of the current scanline
10637:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10638:     $scan_config - hash ref as returned from &get_scantron_config()
10639:     $line        - full contents of the current scanline
10640:     $error       - error condition, valid values are
10641:                    'incorrectCODE', 'duplicateCODE',
10642:                    'doublebubble', 'missingbubble',
10643:                    'duplicateID', 'incorrectID'
10644:     $arg         - extra information needed
10645:        For errors:
10646:          - duplicateID   - paper number that this studentID was seen before on
10647:          - duplicateCODE - array ref of the paper numbers this CODE was
10648:                            seen on before
10649:          - incorrectCODE - current incorrect CODE 
10650:          - doublebubble  - array ref of the bubble lines that have double
10651:                            bubble errors
10652:          - missingbubble - array ref of the bubble lines that have missing
10653:                            bubble errors
10654: 
10655:    $randomorder - True if exam folder has randomorder set
10656:    $randompick  - True if exam folder has randompick set
10657:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10658:                      for current line to question number used for same question
10659:                      in "Master Seqence" (as seen by Course Coordinator).
10660:    $startline   - Reference to hash where key is question number (0 is first)
10661:                   and value is number of first bubble line for current student
10662:                   or code-based randompick and/or randomorder.
10663: 
10664: 
10665: =item  scantron_get_maxbubble() : 
10666: 
10667:    Arguments:
10668:        $nav_error  - Reference to scalar which is a flag to indicate a
10669:                       failure to retrieve a navmap object.
10670:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10671:        calling routine should trap the error condition and display the warning
10672:        found in &navmap_errormsg().
10673: 
10674:        $scantron_config - Reference to bubblesheet format configuration hash.
10675: 
10676:    Returns the maximum number of bubble lines that are expected to
10677:    occur. Does this by walking the selected sequence rendering the
10678:    resource and then checking &Apache::lonxml::get_problem_counter()
10679:    for what the current value of the problem counter is.
10680: 
10681:    Caches the results to $env{'form.scantron_maxbubble'},
10682:    $env{'form.scantron.bubble_lines.n'}, 
10683:    $env{'form.scantron.first_bubble_line.n'} and
10684:    $env{"form.scantron.sub_bubblelines.n"}
10685:    which are the total number of bubble lines, the number of bubble
10686:    lines for response n and number of the first bubble line for response n,
10687:    and a comma separated list of numbers of bubble lines for sub-questions
10688:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10689: 
10690: 
10691: =item  scantron_validate_missingbubbles() : 
10692: 
10693:    Validates all scanlines in the selected file to not have any
10694:     answers that don't have bubbles that have not been verified
10695:     to be bubble free.
10696: 
10697: =item  scantron_process_students() : 
10698: 
10699:    Routine that does the actual grading of the bubblesheet information.
10700: 
10701:    The parsed scanline hash is added to %env 
10702: 
10703:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10704:    foreach resource , with the form data of
10705: 
10706: 	'submitted'     =>'scantron' 
10707: 	'grade_target'  =>'grade',
10708: 	'grade_username'=> username of student
10709: 	'grade_domain'  => domain of student
10710: 	'grade_courseid'=> of course
10711: 	'grade_symb'    => symb of resource to grade
10712: 
10713:     This triggers a grading pass. The problem grading code takes care
10714:     of converting the bubbled letter information (now in %env) into a
10715:     valid submission.
10716: 
10717: =item  scantron_upload_scantron_data() :
10718: 
10719:     Creates the screen for adding a new bubblesheet data file to a course.
10720: 
10721: =item  scantron_upload_scantron_data_save() : 
10722: 
10723:    Adds a provided bubble information data file to the course if user
10724:    has the correct privileges to do so. 
10725: 
10726: =item  valid_file() :
10727: 
10728:    Validates that the requested bubble data file exists in the course.
10729: 
10730: =item  scantron_download_scantron_data() : 
10731: 
10732:    Shows a list of the three internal files (original, corrected,
10733:    skipped) for a specific bubblesheet data file that exists in the
10734:    course.
10735: 
10736: =item  scantron_validate_ID() : 
10737: 
10738:    Validates all scanlines in the selected file to not have any
10739:    invalid or underspecified student/employee IDs
10740: 
10741: =item navmap_errormsg() :
10742: 
10743:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10744:    Should be called whenever the request to instantiate a navmap object fails.  
10745: 
10746: =back
10747: 
10748: =cut

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