File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.23: download - view: text, annotated - select for diffs
Sun Sep 22 18:20:03 2013 UTC (10 years, 7 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  - Eliminate duplicate declaration (caused by changes in rev. 1.596.2.12.2.16).
  - Eliminate unused hash.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.23 2013/09/22 18:20:03 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::bridgetask();
   47: use String::Similarity;
   48: use LONCAPA;
   49: 
   50: use POSIX qw(floor);
   51: 
   52: 
   53: 
   54: my %perm=();
   55: my %old_essays=();
   56: 
   57: #  These variables are used to recover from ssi errors
   58: 
   59: my $ssi_retries = 5;
   60: my $ssi_error;
   61: my $ssi_error_resource;
   62: my $ssi_error_message;
   63: 
   64: 
   65: sub ssi_with_retries {
   66:     my ($resource, $retries, %form) = @_;
   67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   68:     if ($response->is_error) {
   69: 	$ssi_error          = 1;
   70: 	$ssi_error_resource = $resource;
   71: 	$ssi_error_message  = $response->code . " " . $response->message;
   72:     }
   73: 
   74:     return $content;
   75: 
   76: }
   77: #
   78: #  Prodcuces an ssi retry failure error message to the user:
   79: #
   80: 
   81: sub ssi_print_error {
   82:     my ($r) = @_;
   83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   84:     $r->print('
   85: <br />
   86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   87: <p>
   88: '.&mt('Unable to retrieve a resource from a server:').'<br />
   89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   90: '.&mt('Error:').' '.$ssi_error_message.'
   91: </p>
   92: <p>'.
   93: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   95: '</p>');
   96:     return;
   97: }
   98: 
   99: #
  100: # --- Retrieve the parts from the metadata file.---
  101: sub getpartlist {
  102:     my ($symb,$errorref) = @_;
  103: 
  104:     my $navmap   = Apache::lonnavmaps::navmap->new();
  105:     unless (ref($navmap)) {
  106:         if (ref($errorref)) { 
  107:             $$errorref = 'navmap';
  108:             return;
  109:         }
  110:     }
  111:     my $res      = $navmap->getBySymb($symb);
  112:     my $partlist = $res->parts();
  113:     my $url      = $res->src();
  114:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  115: 
  116:     my @stores;
  117:     foreach my $part (@{ $partlist }) {
  118: 	foreach my $key (@metakeys) {
  119: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  120: 	}
  121:     }
  122:     return @stores;
  123: }
  124: 
  125: # --- Get the symbolic name of a problem and the url
  126: sub get_symb {
  127:     my ($request,$silent) = @_;
  128:     my $symb=$env{'form.symb'};
  129:     unless ($symb) {
  130:         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  131:         $symb = &Apache::lonnet::symbread($url);
  132:         if ($symb eq '') { 
  133: 	    if (!$silent) {
  134:                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  135: 	        return ();
  136: 	    }
  137:         }
  138:     }
  139:     &Apache::lonenc::check_decrypt(\$symb);
  140:     return ($symb);
  141: }
  142: 
  143: #--- Format fullname, username:domain if different for display
  144: #--- Use anywhere where the student names are listed
  145: sub nameUserString {
  146:     my ($type,$fullname,$uname,$udom) = @_;
  147:     if ($type eq 'header') {
  148: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  149:     } else {
  150: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  151: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  152:     }
  153: }
  154: 
  155: #--- Get the partlist and the response type for a given problem. ---
  156: #--- Indicate if a response type is coded handgraded or not. ---
  157: sub response_type {
  158:     my ($symb,$response_error) = @_;
  159: 
  160:     my $navmap = Apache::lonnavmaps::navmap->new();
  161:     unless (ref($navmap)) {
  162:         if (ref($response_error)) {
  163:             $$response_error = 1;
  164:         }
  165:         return;
  166:     }
  167:     my $res = $navmap->getBySymb($symb);
  168:     unless (ref($res)) {
  169:         $$response_error = 1;
  170:         return;
  171:     }
  172:     my $partlist = $res->parts();
  173:     my %vPart = 
  174: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  175:     my (%response_types,%handgrade);
  176:     foreach my $part (@{ $partlist }) {
  177: 	next if (%vPart && !exists($vPart{$part}));
  178: 
  179: 	my @types = $res->responseType($part);
  180: 	my @ids = $res->responseIds($part);
  181: 	for (my $i=0; $i < scalar(@ids); $i++) {
  182: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  183: 	    $handgrade{$part.'_'.$ids[$i]} = 
  184: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  185: 				     '.handgrade',$symb);
  186: 	}
  187:     }
  188:     return ($partlist,\%handgrade,\%response_types);
  189: }
  190: 
  191: sub flatten_responseType {
  192:     my ($responseType) = @_;
  193:     my @part_response_id =
  194: 	map { 
  195: 	    my $part = $_;
  196: 	    map {
  197: 		[$part,$_]
  198: 		} sort(keys(%{ $responseType->{$part} }));
  199: 	} sort(keys(%$responseType));
  200:     return @part_response_id;
  201: }
  202: 
  203: sub get_display_part {
  204:     my ($partID,$symb)=@_;
  205:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  206:     if (defined($display) and $display ne '') {
  207:         $display.= ' (<span class="LC_internal_info">'
  208:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  209:     } else {
  210: 	$display=$partID;
  211:     }
  212:     return $display;
  213: }
  214: 
  215: #--- Show resource title
  216: #--- and parts and response type
  217: sub showResourceInfo {
  218:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  219:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  220:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  221:     if (ref($res_error)) {
  222:         if ($$res_error) {
  223:             return;
  224:         }
  225:     }
  226:     $result.=&Apache::loncommon::start_data_table()
  227:             .&Apache::loncommon::start_data_table_header_row();
  228:     if ($checkboxes) {
  229:         $result.='<th>&nbsp;</th>';
  230:     }
  231:     $result.='<th>'.&mt('Problem Part').'</th>'
  232:             .'<th>'.&mt('Res. ID').'</th>'
  233:             .'<th>'.&mt('Type').'</th>'
  234:             .&Apache::loncommon::end_data_table_header_row();
  235:     my %resptype = ();
  236:     my $hdgrade='no';
  237:     my %partsseen;
  238:     foreach my $partID (sort(keys(%$responseType))) {
  239:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  240:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  241:             my $responsetype = $responseType->{$partID}->{$resID};
  242:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  243:             $result.=&Apache::loncommon::start_data_table_row();
  244:             if ($checkboxes) {
  245:                 if (exists($partsseen{$partID})) {
  246:                     $result.="<td>&nbsp;</td>";
  247:                 } else {
  248:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  249:                 }
  250:                 $partsseen{$partID}=1;
  251:             }
  252:             my $display_part=&get_display_part($partID,$symb);
  253:             $result.='<td>'.$display_part.'</td>'
  254:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  255:                     .'<td>'.&mt($responsetype).'</td>'
  256: #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
  257:                     .&Apache::loncommon::end_data_table_row();
  258:         }
  259:     }
  260:     $result.=&Apache::loncommon::end_data_table();
  261:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  262: }
  263: 
  264: sub reset_caches {
  265:     &reset_analyze_cache();
  266:     &reset_perm();
  267:     &reset_old_essays();
  268: }
  269: 
  270: {
  271:     my %analyze_cache;
  272:     my %analyze_cache_formkeys;
  273: 
  274:     sub reset_analyze_cache {
  275: 	undef(%analyze_cache);
  276:         undef(%analyze_cache_formkeys);
  277:     }
  278: 
  279:     sub get_analyze {
  280: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  281: 	my $key = "$symb\0$uname\0$udom";
  282:         if ($type eq 'randomizetry') {
  283:             if ($trial ne '') {
  284:                 $key .= "\0".$trial;
  285:             }
  286:         }
  287: 	if (exists($analyze_cache{$key})) {
  288:             my $getupdate = 0;
  289:             if (ref($add_to_hash) eq 'HASH') {
  290:                 foreach my $item (keys(%{$add_to_hash})) {
  291:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  292:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  293:                             $getupdate = 1;
  294:                             last;
  295:                         }
  296:                     } else {
  297:                         $getupdate = 1;
  298:                     }
  299:                 }
  300:             }
  301:             if (!$getupdate) {
  302:                 return $analyze_cache{$key};
  303:             }
  304:         }
  305: 
  306: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  307: 	$url=&Apache::lonnet::clutter($url);
  308:         my %form = ('grade_target'      => 'analyze',
  309:                     'grade_domain'      => $udom,
  310:                     'grade_symb'        => $symb,
  311:                     'grade_courseid'    =>  $env{'request.course.id'},
  312:                     'grade_username'    => $uname,
  313:                     'grade_noincrement' => $no_increment);
  314:         if ($bubbles_per_row ne '') {
  315:             $form{'bubbles_per_row'} = $bubbles_per_row;
  316:         }
  317:         if ($type eq 'randomizetry') {
  318:             $form{'grade_questiontype'} = $type;
  319:             if ($rndseed ne '') {
  320:                 $form{'grade_rndseed'} = $rndseed;
  321:             }
  322:         }
  323:         if (ref($add_to_hash)) {
  324:             %form = (%form,%{$add_to_hash});
  325:         }
  326: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  327: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  328: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  329:         if (ref($add_to_hash) eq 'HASH') {
  330:             $analyze_cache_formkeys{$key} = $add_to_hash;
  331:         } else {
  332:             $analyze_cache_formkeys{$key} = {};
  333:         }
  334: 	return $analyze_cache{$key} = \%analyze;
  335:     }
  336: 
  337:     sub get_order {
  338: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  339: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  340: 	return $analyze->{"$partid.$respid.shown"};
  341:     }
  342: 
  343:     sub get_radiobutton_correct_foil {
  344: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  345: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  346:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  347:         if (ref($foils) eq 'ARRAY') {
  348: 	    foreach my $foil (@{$foils}) {
  349: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  350: 		    return $foil;
  351: 	        }
  352: 	    }
  353: 	}
  354:     }
  355: 
  356:     sub scantron_partids_tograde {
  357:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  358:         my (%analysis,@parts);
  359:         if (ref($resource)) {
  360:             my $symb = $resource->symb();
  361:             my $add_to_form;
  362:             if ($check_for_randomlist) {
  363:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  364:             }
  365:             my $analyze =
  366:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  367:                              undef,undef,undef,$bubbles_per_row);
  368:             if (ref($analyze) eq 'HASH') {
  369:                 %analysis = %{$analyze};
  370:             }
  371:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  372:                 foreach my $part (@{$analysis{'parts'}}) {
  373:                     my ($id,$respid) = split(/\./,$part);
  374:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  375:                         push(@parts,$part);
  376:                     }
  377:                 }
  378:             }
  379:         }
  380:         return (\%analysis,\@parts);
  381:     }
  382: 
  383: }
  384: 
  385: #--- Clean response type for display
  386: #--- Currently filters option/rank/radiobutton/match/essay/Task
  387: #        response types only.
  388: sub cleanRecord {
  389:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  390: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  391:     my $grayFont = '<span class="LC_internal_info">';
  392:     if ($response =~ /^(option|rank)$/) {
  393: 	my %answer=&Apache::lonnet::str2hash($answer);
  394: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  395: 	my ($toprow,$bottomrow);
  396: 	foreach my $foil (@$order) {
  397: 	    if ($grading{$foil} == 1) {
  398: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  399: 	    } else {
  400: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  401: 	    }
  402: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  403: 	}
  404: 	return '<blockquote><table border="1">'.
  405: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  406: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  407: 	    $bottomrow.'</tr></table></blockquote>';
  408:     } elsif ($response eq 'match') {
  409: 	my %answer=&Apache::lonnet::str2hash($answer);
  410: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  411: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  412: 	my ($toprow,$middlerow,$bottomrow);
  413: 	foreach my $foil (@$order) {
  414: 	    my $item=shift(@items);
  415: 	    if ($grading{$foil} == 1) {
  416: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  417: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  418: 	    } else {
  419: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  420: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  421: 	    }
  422: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  423: 	}
  424: 	return '<blockquote><table border="1">'.
  425: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  426: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  427: 	    $middlerow.'</tr>'.
  428: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  429: 	    $bottomrow.'</tr></table></blockquote>';
  430:     } elsif ($response eq 'radiobutton') {
  431: 	my %answer=&Apache::lonnet::str2hash($answer);
  432: 	my ($toprow,$bottomrow);
  433: 	my $correct = 
  434: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  435: 	foreach my $foil (@$order) {
  436: 	    if (exists($answer{$foil})) {
  437: 		if ($foil eq $correct) {
  438: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  439: 		} else {
  440: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  441: 		}
  442: 	    } else {
  443: 		$toprow.='<td>'.&mt('false').'</td>';
  444: 	    }
  445: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  446: 	}
  447: 	return '<blockquote><table border="1">'.
  448: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  449: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  450: 	    $bottomrow.'</tr></table></blockquote>';
  451:     } elsif ($response eq 'essay') {
  452: 	if (! exists ($env{'form.'.$symb})) {
  453: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  454: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  455: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  456: 
  457: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  458: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  459: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  460: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  461: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  462: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  463: 	}
  464: 	$answer =~ s-\n-<br />-g;
  465: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  466:     } elsif ( $response eq 'organic') {
  467: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  468: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  469: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  470: 	return $result;
  471:     } elsif ( $response eq 'Task') {
  472: 	if ( $answer eq 'SUBMITTED') {
  473: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  474: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  475: 	    return $result;
  476: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  477: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  478: 			       keys(%{$record}));
  479: 	    return join('<br />',($version,@matches));
  480: 			       
  481: 			       
  482: 	} else {
  483: 	    my $result =
  484: 		'<p>'
  485: 		.&mt('Overall result: [_1]',
  486: 		     $record->{$version."resource.$respid.$partid.status"})
  487: 		.'</p>';
  488: 	    
  489: 	    $result .= '<ul>';
  490: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  491: 			     keys(%{$record}));
  492: 	    foreach my $grade (sort(@grade)) {
  493: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  494: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  495: 				     $dim, $record->{$grade}).
  496: 			  '</li>';
  497: 	    }
  498: 	    $result.='</ul>';
  499: 	    return $result;
  500: 	}
  501:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  502: 	$answer = 
  503: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  504: 							      $answer);
  505:     }
  506:     return $answer;
  507: }
  508: 
  509: #-- A couple of common js functions
  510: sub commonJSfunctions {
  511:     my $request = shift;
  512:     $request->print(<<COMMONJSFUNCTIONS);
  513: <script type="text/javascript" language="javascript">
  514:     function radioSelection(radioButton) {
  515: 	var selection=null;
  516: 	if (radioButton.length > 1) {
  517: 	    for (var i=0; i<radioButton.length; i++) {
  518: 		if (radioButton[i].checked) {
  519: 		    return radioButton[i].value;
  520: 		}
  521: 	    }
  522: 	} else {
  523: 	    if (radioButton.checked) return radioButton.value;
  524: 	}
  525: 	return selection;
  526:     }
  527: 
  528:     function pullDownSelection(selectOne) {
  529: 	var selection="";
  530: 	if (selectOne.length > 1) {
  531: 	    for (var i=0; i<selectOne.length; i++) {
  532: 		if (selectOne[i].selected) {
  533: 		    return selectOne[i].value;
  534: 		}
  535: 	    }
  536: 	} else {
  537:             // only one value it must be the selected one
  538: 	    return selectOne.value;
  539: 	}
  540:     }
  541: </script>
  542: COMMONJSFUNCTIONS
  543: }
  544: 
  545: #--- Dumps the class list with usernames,list of sections,
  546: #--- section, ids and fullnames for each user.
  547: sub getclasslist {
  548:     my ($getsec,$filterlist,$getgroup) = @_;
  549:     my @getsec;
  550:     my @getgroup;
  551:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  552:     if (!ref($getsec)) {
  553: 	if ($getsec ne '' && $getsec ne 'all') {
  554: 	    @getsec=($getsec);
  555: 	}
  556:     } else {
  557: 	@getsec=@{$getsec};
  558:     }
  559:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  560:     if (!ref($getgroup)) {
  561: 	if ($getgroup ne '' && $getgroup ne 'all') {
  562: 	    @getgroup=($getgroup);
  563: 	}
  564:     } else {
  565: 	@getgroup=@{$getgroup};
  566:     }
  567:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  568: 
  569:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  570:     # Bail out if we were unable to get the classlist
  571:     return if (! defined($classlist));
  572:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  573:     #
  574:     my %sections;
  575:     my %fullnames;
  576:     foreach my $student (keys(%$classlist)) {
  577:         my $end      = 
  578:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  579:         my $start    = 
  580:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  581:         my $id       = 
  582:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  583:         my $section  = 
  584:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  585:         my $fullname = 
  586:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  587:         my $status   = 
  588:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  589:         my $group   = 
  590:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  591: 	# filter students according to status selected
  592: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  593: 	    if (!($stu_status =~ $status)) {
  594: 		delete($classlist->{$student});
  595: 		next;
  596: 	    }
  597: 	}
  598: 	# filter students according to groups selected
  599: 	my @stu_groups = split(/,/,$group);
  600: 	if (@getgroup) {
  601: 	    my $exclude = 1;
  602: 	    foreach my $grp (@getgroup) {
  603: 	        foreach my $stu_group (@stu_groups) {
  604: 	            if ($stu_group eq $grp) {
  605: 	                $exclude = 0;
  606:     	            } 
  607: 	        }
  608:     	        if (($grp eq 'none') && !$group) {
  609:         	        $exclude = 0;
  610:         	}
  611: 	    }
  612: 	    if ($exclude) {
  613: 	        delete($classlist->{$student});
  614: 	    }
  615: 	}
  616: 	$section = ($section ne '' ? $section : 'none');
  617: 	if (&canview($section)) {
  618: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  619: 		$sections{$section}++;
  620: 		if ($classlist->{$student}) {
  621: 		    $fullnames{$student}=$fullname;
  622: 		}
  623: 	    } else {
  624: 		delete($classlist->{$student});
  625: 	    }
  626: 	} else {
  627: 	    delete($classlist->{$student});
  628: 	}
  629:     }
  630:     my %seen = ();
  631:     my @sections = sort(keys(%sections));
  632:     return ($classlist,\@sections,\%fullnames);
  633: }
  634: 
  635: sub canmodify {
  636:     my ($sec)=@_;
  637:     if ($perm{'mgr'}) {
  638: 	if (!defined($perm{'mgr_section'})) {
  639: 	    # can modify whole class
  640: 	    return 1;
  641: 	} else {
  642: 	    if ($sec eq $perm{'mgr_section'}) {
  643: 		#can modify the requested section
  644: 		return 1;
  645: 	    } else {
  646: 		# can't modify the request section
  647: 		return 0;
  648: 	    }
  649: 	}
  650:     }
  651:     #can't modify
  652:     return 0;
  653: }
  654: 
  655: sub canview {
  656:     my ($sec)=@_;
  657:     if ($perm{'vgr'}) {
  658: 	if (!defined($perm{'vgr_section'})) {
  659: 	    # can modify whole class
  660: 	    return 1;
  661: 	} else {
  662: 	    if ($sec eq $perm{'vgr_section'}) {
  663: 		#can modify the requested section
  664: 		return 1;
  665: 	    } else {
  666: 		# can't modify the request section
  667: 		return 0;
  668: 	    }
  669: 	}
  670:     }
  671:     #can't modify
  672:     return 0;
  673: }
  674: 
  675: #--- Retrieve the grade status of a student for all the parts
  676: sub student_gradeStatus {
  677:     my ($symb,$udom,$uname,$partlist) = @_;
  678:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  679:     my %partstatus = ();
  680:     foreach (@$partlist) {
  681: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  682: 	$status              = 'nothing' if ($status eq '');
  683: 	$partstatus{$_}      = $status;
  684: 	my $subkey           = "resource.$_.submitted_by";
  685: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  686:     }
  687:     return %partstatus;
  688: }
  689: 
  690: # hidden form and javascript that calls the form
  691: # Use by verifyscript and viewgrades
  692: # Shows a student's view of problem and submission
  693: sub jscriptNform {
  694:     my ($symb) = @_;
  695:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  696:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  697: 	'    function viewOneStudent(user,domain) {'."\n".
  698: 	'	document.onestudent.student.value = user;'."\n".
  699: 	'	document.onestudent.userdom.value = domain;'."\n".
  700: 	'	document.onestudent.submit();'."\n".
  701: 	'    }'."\n".
  702: 	'</script>'."\n";
  703:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  704: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  705: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  706: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  707: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  708: 	'<input type="hidden" name="command" value="submission" />'."\n".
  709: 	'<input type="hidden" name="student" value="" />'."\n".
  710: 	'<input type="hidden" name="userdom" value="" />'."\n".
  711: 	'</form>'."\n";
  712:     return $jscript;
  713: }
  714: 
  715: 
  716: 
  717: # Given the score (as a number [0-1] and the weight) what is the final
  718: # point value? This function will round to the nearest tenth, third,
  719: # or quarter if one of those is within the tolerance of .00001.
  720: sub compute_points {
  721:     my ($score, $weight) = @_;
  722:     
  723:     my $tolerance = .00001;
  724:     my $points = $score * $weight;
  725: 
  726:     # Check for nearness to 1/x.
  727:     my $check_for_nearness = sub {
  728:         my ($factor) = @_;
  729:         my $num = ($points * $factor) + $tolerance;
  730:         my $floored_num = floor($num);
  731:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  732:             return $floored_num / $factor;
  733:         }
  734:         return $points;
  735:     };
  736: 
  737:     $points = $check_for_nearness->(10);
  738:     $points = $check_for_nearness->(3);
  739:     $points = $check_for_nearness->(4);
  740:     
  741:     return $points;
  742: }
  743: 
  744: #------------------ End of general use routines --------------------
  745: 
  746: #
  747: # Find most similar essay
  748: #
  749: 
  750: sub most_similar {
  751:     my ($uname,$udom,$symb,$uessay)=@_;
  752: 
  753:     unless ($symb) { return ''; }
  754: 
  755:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  756: 
  757: # ignore spaces and punctuation
  758: 
  759:     $uessay=~s/\W+/ /gs;
  760: 
  761: # ignore empty submissions (occuring when only files are sent)
  762: 
  763:     unless ($uessay=~/\w+/s) { return ''; }
  764: 
  765: # these will be returned. Do not care if not at least 50 percent similar
  766:     my $limit=0.6;
  767:     my $sname='';
  768:     my $sdom='';
  769:     my $scrsid='';
  770:     my $sessay='';
  771: # go through all essays ...
  772:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  773: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  774: # ... except the same student
  775:         next if (($tname eq $uname) && ($tdom eq $udom));
  776: 	my $tessay=$old_essays{$symb}{$tkey};
  777: 	$tessay=~s/\W+/ /gs;
  778: # String similarity gives up if not even limit
  779: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  780: # Found one
  781: 	if ($tsimilar>$limit) {
  782: 	    $limit=$tsimilar;
  783: 	    $sname=$tname;
  784: 	    $sdom=$tdom;
  785: 	    $scrsid=$tcrsid;
  786: 	    $sessay=$old_essays{$symb}{$tkey};
  787: 	}
  788:     }
  789:     if ($limit>0.6) {
  790:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  791:     } else {
  792:        return ('','','','',0);
  793:     }
  794: }
  795: 
  796: #-------------------------------------------------------------------
  797: 
  798: #------------------------------------ Receipt Verification Routines
  799: #
  800: #--- Check whether a receipt number is valid.---
  801: sub verifyreceipt {
  802:     my $request  = shift;
  803: 
  804:     my $courseid = $env{'request.course.id'};
  805:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  806: 	$env{'form.receipt'};
  807:     $receipt     =~ s/[^\-\d]//g;
  808:     my ($symb)   = &get_symb($request);
  809: 
  810:     my $title.=
  811: 	'<h3><span class="LC_info">'.
  812: 	&mt('Verifying Receipt No. [_1]',$receipt).
  813: 	'</span></h3>'."\n".
  814: 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
  815: 	'</h4>'."\n";
  816: 
  817:     my ($string,$contents,$matches) = ('','',0);
  818:     my (undef,undef,$fullname) = &getclasslist('all','0');
  819:     
  820:     my $receiptparts=0;
  821:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  822: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  823:     my $parts=['0'];
  824:     if ($receiptparts) {
  825:         my $res_error; 
  826:         ($parts)=&response_type($symb,\$res_error);
  827:         if ($res_error) {
  828:             return &navmap_errormsg();
  829:         } 
  830:     }
  831:     
  832:     my $header = 
  833: 	&Apache::loncommon::start_data_table().
  834: 	&Apache::loncommon::start_data_table_header_row().
  835: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  836: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  837: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  838:     if ($receiptparts) {
  839: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  840:     }
  841:     $header.=
  842: 	&Apache::loncommon::end_data_table_header_row();
  843: 
  844:     foreach (sort 
  845: 	     {
  846: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  847: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  848: 		 }
  849: 		 return $a cmp $b;
  850: 	     } (keys(%$fullname))) {
  851: 	my ($uname,$udom)=split(/\:/);
  852: 	foreach my $part (@$parts) {
  853: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  854: 		$contents.=
  855: 		    &Apache::loncommon::start_data_table_row().
  856: 		    '<td>&nbsp;'."\n".
  857: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  858: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  859: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  860: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  861: 		if ($receiptparts) {
  862: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  863: 		}
  864: 		$contents.= 
  865: 		    &Apache::loncommon::end_data_table_row()."\n";
  866: 		
  867: 		$matches++;
  868: 	    }
  869: 	}
  870:     }
  871:     if ($matches == 0) {
  872:         $string = $title
  873:                  .'<p class="LC_warning">'
  874:                  .&mt('No match found for the above receipt number.')
  875:                  .'</p>';
  876:     } else {
  877: 	$string = &jscriptNform($symb).$title.
  878: 	    '<p>'.
  879: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  880: 	    '</p>'.
  881: 	    $header.
  882: 	    $contents.
  883: 	    &Apache::loncommon::end_data_table()."\n";
  884:     }
  885:     return $string.&show_grading_menu_form($symb);
  886: }
  887: 
  888: #--- This is called by a number of programs.
  889: #--- Called from the Grading Menu - View/Grade an individual student
  890: #--- Also called directly when one clicks on the subm button 
  891: #    on the problem page.
  892: sub listStudents {
  893:     my ($request) = shift;
  894: 
  895:     my ($symb) = &get_symb($request);
  896:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  897:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  898:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  899:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  900:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  901:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  902:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  903: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  904: 
  905:     my $result='<h3><span class="LC_info">&nbsp;'
  906: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  907: 	.'</span></h3>';
  908: 
  909:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  910: 
  911:     my %lt = &Apache::lonlocal::texthash (
  912: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  913: 		'single'   => 'Please select the student before clicking on the Next button.',
  914: 	     );
  915:     $request->print(<<LISTJAVASCRIPT);
  916: <script type="text/javascript" language="javascript">
  917:     function checkSelect(checkBox) {
  918: 	var ctr=0;
  919: 	var sense="";
  920: 	if (checkBox.length > 1) {
  921: 	    for (var i=0; i<checkBox.length; i++) {
  922: 		if (checkBox[i].checked) {
  923: 		    ctr++;
  924: 		}
  925: 	    }
  926: 	    sense = '$lt{'multiple'}';
  927: 	} else {
  928: 	    if (checkBox.checked) {
  929: 		ctr = 1;
  930: 	    }
  931: 	    sense = '$lt{'single'}';
  932: 	}
  933: 	if (ctr == 0) {
  934: 	    alert(sense);
  935: 	    return false;
  936: 	}
  937: 	document.gradesub.submit();
  938:     }
  939: 
  940:     function reLoadList(formname) {
  941: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  942: 	formname.command.value = 'submission';
  943: 	formname.submit();
  944:     }
  945: </script>
  946: LISTJAVASCRIPT
  947: 
  948:     &commonJSfunctions($request);
  949:     $request->print($result);
  950: 
  951:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  952:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  953:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  954: 	"\n".$table;
  955: 	
  956:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  957:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  958:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  959:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  960:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  961:                   .&Apache::lonhtmlcommon::row_closure();
  962:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  963:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  964:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  965:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  966:                   .&Apache::lonhtmlcommon::row_closure();
  967: 
  968:     my $submission_options;
  969:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  970: 	$submission_options.=
  971: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  972:     }
  973:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  974:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  975:     $env{'form.Status'} = $saveStatus;
  976:     $submission_options.=
  977:         '<span class="LC_nobreak">'.
  978:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  979:         &mt('last submission only').' </label></span>'."\n".
  980:         '<span class="LC_nobreak">'.
  981:         '<label><input type="radio" name="lastSub" value="last" /> '.
  982:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  983:         '<span class="LC_nobreak">'.
  984:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  985:         &mt('by dates and submissions').'</label></span>'."\n".
  986:         '<span class="LC_nobreak">'.
  987:         '<label><input type="radio" name="lastSub" value="all" /> '.
  988:         &mt('all details').'</label></span>';
  989:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  990:                   .$submission_options
  991:                   .&Apache::lonhtmlcommon::row_closure();
  992: 
  993:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  994:                   .'<select name="increment">'
  995:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  996:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  997:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  998:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  999:                   .'</select>'
 1000:                   .&Apache::lonhtmlcommon::row_closure();
 1001: 
 1002:     $gradeTable .= 
 1003:         &build_section_inputs().
 1004: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1005: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1006: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1007: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1008: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1009: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1010: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1011: 
 1012:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1013: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1014:     } else {
 1015:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1016:                       .&Apache::lonhtmlcommon::StatusOptions(
 1017:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1018:                       .&Apache::lonhtmlcommon::row_closure();
 1019:     }
 1020: 
 1021:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1022:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1023:                   .&Apache::lonhtmlcommon::row_closure(1)
 1024:                   .&Apache::lonhtmlcommon::end_pick_box();
 1025: 
 1026:     $gradeTable .= '<p>'
 1027:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
 1028:                   .'<input type="hidden" name="command" value="processGroup" />'
 1029:                   .'</p>';
 1030: 
 1031: # checkall buttons
 1032:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1033:     $gradeTable.='<input type="button" '."\n".
 1034:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1035:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1036:     $gradeTable.=&check_buttons();
 1037:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1038:     $gradeTable.= &Apache::loncommon::start_data_table().
 1039: 	&Apache::loncommon::start_data_table_header_row();
 1040:     my $loop = 0;
 1041:     while ($loop < 2) {
 1042: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1043: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1044: 	if ($env{'form.showgrading'} eq 'yes' 
 1045: 	    && $submitonly ne 'queued'
 1046: 	    && $submitonly ne 'all') {
 1047: 	    foreach my $part (sort(@$partlist)) {
 1048: 		my $display_part=
 1049: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1050: 		$gradeTable.=
 1051: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1052: 	    }
 1053: 	} elsif ($submitonly eq 'queued') {
 1054: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1055: 	}
 1056: 	$loop++;
 1057: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1058:     }
 1059:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1060: 
 1061:     my $ctr = 0;
 1062:     foreach my $student (sort 
 1063: 			 {
 1064: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1065: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1066: 			     }
 1067: 			     return $a cmp $b;
 1068: 			 }
 1069: 			 (keys(%$fullname))) {
 1070: 	my ($uname,$udom) = split(/:/,$student);
 1071: 
 1072: 	my %status = ();
 1073: 
 1074: 	if ($submitonly eq 'queued') {
 1075: 	    my %queue_status = 
 1076: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1077: 							$udom,$uname);
 1078: 	    next if (!defined($queue_status{'gradingqueue'}));
 1079: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1080: 	}
 1081: 
 1082: 	if ($env{'form.showgrading'} eq 'yes' 
 1083: 	    && $submitonly ne 'queued'
 1084: 	    && $submitonly ne 'all') {
 1085: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1086: 	    my $submitted = 0;
 1087: 	    my $graded = 0;
 1088: 	    my $incorrect = 0;
 1089: 	    foreach (keys(%status)) {
 1090: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1091: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1092: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1093: 		
 1094: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1095: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1096: 		    $submitted = 0;
 1097: 		    my ($part)=split(/\./,$partid);
 1098: 		    $gradeTable.='<input type="hidden" name="'.
 1099: 			$student.':'.$part.':submitted_by" value="'.
 1100: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1101: 		}
 1102: 	    }
 1103: 	    
 1104: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1105: 				     $submitonly eq 'incorrect' ||
 1106: 				     $submitonly eq 'graded'));
 1107: 	    next if (!$graded && ($submitonly eq 'graded'));
 1108: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1109: 	}
 1110: 
 1111: 	$ctr++;
 1112: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1113:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1114: 	if ( $perm{'vgr'} eq 'F' ) {
 1115: 	    if ($ctr%2 ==1) {
 1116: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1117: 	    }
 1118: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1119:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1120:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1121: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1122: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1123: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1124: 
 1125: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1126: 		foreach (sort(keys(%status))) {
 1127: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1128: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1129: 		}
 1130: 	    }
 1131: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1132: 	    if ($ctr%2 ==0) {
 1133: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1134: 	    }
 1135: 	}
 1136:     }
 1137:     if ($ctr%2 ==1) {
 1138: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1139: 	    if ($env{'form.showgrading'} eq 'yes' 
 1140: 		&& $submitonly ne 'queued'
 1141: 		&& $submitonly ne 'all') {
 1142: 		foreach (@$partlist) {
 1143: 		    $gradeTable.='<td>&nbsp;</td>';
 1144: 		}
 1145: 	    } elsif ($submitonly eq 'queued') {
 1146: 		$gradeTable.='<td>&nbsp;</td>';
 1147: 	    }
 1148: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1149:     }
 1150: 
 1151:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1152:         '<input type="button" '.
 1153:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1154:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1155:     if ($ctr == 0) {
 1156: 	my $num_students=(scalar(keys(%$fullname)));
 1157: 	if ($num_students eq 0) {
 1158: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1159: 	} else {
 1160: 	    my $submissions='submissions';
 1161: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1162: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1163: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1164: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1165: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1166: 		    $num_students).
 1167: 		'</span><br />';
 1168: 	}
 1169:     } elsif ($ctr == 1) {
 1170: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1171:     }
 1172:     $gradeTable.=&show_grading_menu_form($symb);
 1173:     $request->print($gradeTable);
 1174:     return '';
 1175: }
 1176: 
 1177: #---- Called from the listStudents routine
 1178: 
 1179: sub check_script {
 1180:     my ($form, $type)=@_;
 1181:     my $chkallscript='<script type="text/javascript">
 1182:     function checkall() {
 1183:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1184:             ele = document.forms.'.$form.'.elements[i];
 1185:             if (ele.name == "'.$type.'") {
 1186:             document.forms.'.$form.'.elements[i].checked=true;
 1187:                                        }
 1188:         }
 1189:     }
 1190: 
 1191:     function checksec() {
 1192:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1193:             ele = document.forms.'.$form.'.elements[i];
 1194:            string = document.forms.'.$form.'.chksec.value;
 1195:            if
 1196:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1197:               document.forms.'.$form.'.elements[i].checked=true;
 1198:             }
 1199:         }
 1200:     }
 1201: 
 1202: 
 1203:     function uncheckall() {
 1204:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1205:             ele = document.forms.'.$form.'.elements[i];
 1206:             if (ele.name == "'.$type.'") {
 1207:             document.forms.'.$form.'.elements[i].checked=false;
 1208:                                        }
 1209:         }
 1210:     }
 1211: 
 1212: </script>'."\n";
 1213:     return $chkallscript;
 1214: }
 1215: 
 1216: sub check_buttons {
 1217:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1218:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1219:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1220:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1221:     return $buttons;
 1222: }
 1223: 
 1224: #     Displays the submissions for one student or a group of students
 1225: sub processGroup {
 1226:     my ($request)  = shift;
 1227:     my $ctr        = 0;
 1228:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1229:     my $total      = scalar(@stuchecked)-1;
 1230: 
 1231:     foreach my $student (@stuchecked) {
 1232: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1233: 	$env{'form.student'}        = $uname;
 1234: 	$env{'form.userdom'}        = $udom;
 1235: 	$env{'form.fullname'}       = $fullname;
 1236: 	&submission($request,$ctr,$total);
 1237: 	$ctr++;
 1238:     }
 1239:     return '';
 1240: }
 1241: 
 1242: #------------------------------------------------------------------------------------
 1243: #
 1244: #-------------------------- Next few routines handles grading by student, essentially
 1245: #                           handles essay response type problem/part
 1246: #
 1247: #--- Javascript to handle the submission page functionality ---
 1248: sub sub_page_js {
 1249:     my $request = shift;
 1250: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1251:     $request->print(<<SUBJAVASCRIPT);
 1252: <script type="text/javascript" language="javascript">
 1253:     function updateRadio(formname,id,weight) {
 1254: 	var gradeBox = formname["GD_BOX"+id];
 1255: 	var radioButton = formname["RADVAL"+id];
 1256: 	var oldpts = formname["oldpts"+id].value;
 1257: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1258: 	gradeBox.value = pts;
 1259: 	var resetbox = false;
 1260: 	if (isNaN(pts) || pts < 0) {
 1261: 	    alert("$alertmsg"+pts);
 1262: 	    for (var i=0; i<radioButton.length; i++) {
 1263: 		if (radioButton[i].checked) {
 1264: 		    gradeBox.value = i;
 1265: 		    resetbox = true;
 1266: 		}
 1267: 	    }
 1268: 	    if (!resetbox) {
 1269: 		formtextbox.value = "";
 1270: 	    }
 1271: 	    return;
 1272: 	}
 1273: 
 1274: 	if (pts > weight) {
 1275: 	    var resp = confirm("You entered a value ("+pts+
 1276: 			       ") greater than the weight for the part. Accept?");
 1277: 	    if (resp == false) {
 1278: 		gradeBox.value = oldpts;
 1279: 		return;
 1280: 	    }
 1281: 	}
 1282: 
 1283: 	for (var i=0; i<radioButton.length; i++) {
 1284: 	    radioButton[i].checked=false;
 1285: 	    if (pts == i && pts != "") {
 1286: 		radioButton[i].checked=true;
 1287: 	    }
 1288: 	}
 1289: 	updateSelect(formname,id);
 1290: 	formname["stores"+id].value = "0";
 1291:     }
 1292: 
 1293:     function writeBox(formname,id,pts) {
 1294: 	var gradeBox = formname["GD_BOX"+id];
 1295: 	if (checkSolved(formname,id) == 'update') {
 1296: 	    gradeBox.value = pts;
 1297: 	} else {
 1298: 	    var oldpts = formname["oldpts"+id].value;
 1299: 	    gradeBox.value = oldpts;
 1300: 	    var radioButton = formname["RADVAL"+id];
 1301: 	    for (var i=0; i<radioButton.length; i++) {
 1302: 		radioButton[i].checked=false;
 1303: 		if (i == oldpts) {
 1304: 		    radioButton[i].checked=true;
 1305: 		}
 1306: 	    }
 1307: 	}
 1308: 	formname["stores"+id].value = "0";
 1309: 	updateSelect(formname,id);
 1310: 	return;
 1311:     }
 1312: 
 1313:     function clearRadBox(formname,id) {
 1314: 	if (checkSolved(formname,id) == 'noupdate') {
 1315: 	    updateSelect(formname,id);
 1316: 	    return;
 1317: 	}
 1318: 	gradeSelect = formname["GD_SEL"+id];
 1319: 	for (var i=0; i<gradeSelect.length; i++) {
 1320: 	    if (gradeSelect[i].selected) {
 1321: 		var selectx=i;
 1322: 	    }
 1323: 	}
 1324: 	var stores = formname["stores"+id];
 1325: 	if (selectx == stores.value) { return };
 1326: 	var gradeBox = formname["GD_BOX"+id];
 1327: 	gradeBox.value = "";
 1328: 	var radioButton = formname["RADVAL"+id];
 1329: 	for (var i=0; i<radioButton.length; i++) {
 1330: 	    radioButton[i].checked=false;
 1331: 	}
 1332: 	stores.value = selectx;
 1333:     }
 1334: 
 1335:     function checkSolved(formname,id) {
 1336: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1337: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1338: 	    if (!reply) {return "noupdate";}
 1339: 	    formname.overRideScore.value = 'yes';
 1340: 	}
 1341: 	return "update";
 1342:     }
 1343: 
 1344:     function updateSelect(formname,id) {
 1345: 	formname["GD_SEL"+id][0].selected = true;
 1346: 	return;
 1347:     }
 1348: 
 1349: //=========== Check that a point is assigned for all the parts  ============
 1350:     function checksubmit(formname,val,total,parttot) {
 1351: 	formname.gradeOpt.value = val;
 1352: 	if (val == "Save & Next") {
 1353: 	    for (i=0;i<=total;i++) {
 1354: 		for (j=0;j<parttot;j++) {
 1355: 		    var partid = formname["partid"+i+"_"+j].value;
 1356: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1357: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1358: 			if (points == "") {
 1359: 			    var name = formname["name"+i].value;
 1360: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1361: 			    var resp = confirm("You did not assign a score for "+studentID+
 1362: 					       ", part "+partid+". Continue?");
 1363: 			    if (resp == false) {
 1364: 				formname["GD_BOX"+i+"_"+partid].focus();
 1365: 				return false;
 1366: 			    }
 1367: 			}
 1368: 		    }
 1369: 		    
 1370: 		}
 1371: 	    }
 1372: 	    
 1373: 	}
 1374: 	if (val == "Grade Student") {
 1375: 	    formname.showgrading.value = "yes";
 1376: 	    if (formname.Status.value == "") {
 1377: 		formname.Status.value = "Active";
 1378: 	    }
 1379: 	    formname.studentNo.value = total;
 1380: 	}
 1381: 	formname.submit();
 1382:     }
 1383: 
 1384: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1385:     function checkSubmitPage(formname,total) {
 1386: 	noscore = new Array(100);
 1387: 	var ptr = 0;
 1388: 	for (i=1;i<total;i++) {
 1389: 	    var partid = formname["q_"+i].value;
 1390: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1391: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1392: 		var status = formname["solved"+i+"_"+partid].value;
 1393: 		if (points == "" && status != "correct_by_student") {
 1394: 		    noscore[ptr] = i;
 1395: 		    ptr++;
 1396: 		}
 1397: 	    }
 1398: 	}
 1399: 	if (ptr != 0) {
 1400: 	    var sense = ptr == 1 ? ": " : "s: ";
 1401: 	    var prolist = "";
 1402: 	    if (ptr == 1) {
 1403: 		prolist = noscore[0];
 1404: 	    } else {
 1405: 		var i = 0;
 1406: 		while (i < ptr-1) {
 1407: 		    prolist += noscore[i]+", ";
 1408: 		    i++;
 1409: 		}
 1410: 		prolist += "and "+noscore[i];
 1411: 	    }
 1412: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1413: 	    if (resp == false) {
 1414: 		return false;
 1415: 	    }
 1416: 	}
 1417: 
 1418: 	formname.submit();
 1419:     }
 1420: </script>
 1421: SUBJAVASCRIPT
 1422: }
 1423: 
 1424: #--- javascript for essay type problem --
 1425: sub sub_page_kw_js {
 1426:     my $request = shift;
 1427:     my $iconpath = $request->dir_config('lonIconsURL');
 1428:     &commonJSfunctions($request);
 1429: 
 1430:     my $inner_js_msg_central=<<INNERJS;
 1431:     <script text="text/javascript">
 1432:     function checkInput() {
 1433:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1434:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1435:       var usrctr = document.msgcenter.usrctr.value;
 1436:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1437:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1438: 
 1439:       var msgchk = "";
 1440:       if (document.msgcenter.subchk.checked) {
 1441:          msgchk = "msgsub,";
 1442:       }
 1443:       var includemsg = 0;
 1444:       for (var i=1; i<=nmsg; i++) {
 1445:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1446:           var frmmsg = document.msgcenter["msg"+i];
 1447:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1448:           var showflg = opener.document.SCORE["shownOnce"+i];
 1449:           showflg.value = "1";
 1450:           var chkbox = document.msgcenter["msgn"+i];
 1451:           if (chkbox.checked) {
 1452:              msgchk += "savemsg"+i+",";
 1453:              includemsg = 1;
 1454:           }
 1455:       }
 1456:       if (document.msgcenter.newmsgchk.checked) {
 1457:          msgchk += "newmsg"+usrctr;
 1458:          includemsg = 1;
 1459:       }
 1460:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1461:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1462:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1463:       includemsg.value = msgchk;
 1464: 
 1465:       self.close()
 1466: 
 1467:     }
 1468:     </script>
 1469: INNERJS
 1470: 
 1471:     my $inner_js_highlight_central=<<INNERJS;
 1472:  <script type="text/javascript">
 1473:     function updateChoice(flag) {
 1474:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1475:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1476:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1477:       opener.document.SCORE.refresh.value = "on";
 1478:       if (opener.document.SCORE.keywords.value!=""){
 1479:          opener.document.SCORE.submit();
 1480:       }
 1481:       self.close()
 1482:     }
 1483: </script>
 1484: INNERJS
 1485: 
 1486:     my $start_page_msg_central = 
 1487:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1488: 				       {'js_ready'  => 1,
 1489: 					'only_body' => 1,
 1490: 					'bgcolor'   =>'#FFFFFF',});
 1491:     my $end_page_msg_central = 
 1492: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1493: 
 1494: 
 1495:     my $start_page_highlight_central = 
 1496:         &Apache::loncommon::start_page('Highlight Central',
 1497: 				       $inner_js_highlight_central,
 1498: 				       {'js_ready'  => 1,
 1499: 					'only_body' => 1,
 1500: 					'bgcolor'   =>'#FFFFFF',});
 1501:     my $end_page_highlight_central = 
 1502: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1503: 
 1504:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1505:     $docopen=~s/^document\.//;
 1506:     my %lt = &Apache::lonlocal::texthash(
 1507:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1508:                 plse => 'Please select a word or group of words from document and then click this link.',
 1509:                 adds => 'Add selection to keyword list? Edit if desired.',
 1510:                 comp => 'Compose Message for: ',
 1511:                 incl => 'Include',
 1512:                 type => 'Type',
 1513:                 subj => 'Subject',
 1514:                 mesa => 'Message',
 1515:                 new  => 'New',
 1516:                 save => 'Save',
 1517:                 canc => 'Cancel',
 1518:                 kehi => 'Keyword Highlight Options',
 1519:                 txtc => 'Text Color',
 1520:                 font => 'Font Size',
 1521:                 fnst => 'Font Style',
 1522:              );
 1523:     $request->print(<<SUBJAVASCRIPT);
 1524: <script type="text/javascript" language="javascript">
 1525: 
 1526: //===================== Show list of keywords ====================
 1527:   function keywords(formname) {
 1528:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1529:     if (nret==null) return;
 1530:     formname.keywords.value = nret;
 1531: 
 1532:     if (formname.keywords.value != "") {
 1533: 	formname.refresh.value = "on";
 1534: 	formname.submit();
 1535:     }
 1536:     return;
 1537:   }
 1538: 
 1539: //===================== Script to view submitted by ==================
 1540:   function viewSubmitter(submitter) {
 1541:     document.SCORE.refresh.value = "on";
 1542:     document.SCORE.NCT.value = "1";
 1543:     document.SCORE.unamedom0.value = submitter;
 1544:     document.SCORE.submit();
 1545:     return;
 1546:   }
 1547: 
 1548: //===================== Script to add keyword(s) ==================
 1549:   function getSel() {
 1550:     if (document.getSelection) txt = document.getSelection();
 1551:     else if (document.selection) txt = document.selection.createRange().text;
 1552:     else return;
 1553:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1554:     if (cleantxt=="") {
 1555: 	alert("$lt{'plse'}");
 1556: 	return;
 1557:     }
 1558:     var nret = prompt("$lt{'adds'}",cleantxt);
 1559:     if (nret==null) return;
 1560:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1561:     if (document.SCORE.keywords.value != "") {
 1562: 	document.SCORE.refresh.value = "on";
 1563: 	document.SCORE.submit();
 1564:     }
 1565:     return;
 1566:   }
 1567: 
 1568: //====================== Script for composing message ==============
 1569:    // preload images
 1570:    img1 = new Image();
 1571:    img1.src = "$iconpath/mailbkgrd.gif";
 1572:    img2 = new Image();
 1573:    img2.src = "$iconpath/mailto.gif";
 1574: 
 1575:   function msgCenter(msgform,usrctr,fullname) {
 1576:     var Nmsg  = msgform.savemsgN.value;
 1577:     savedMsgHeader(Nmsg,usrctr,fullname);
 1578:     var subject = msgform.msgsub.value;
 1579:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1580:     re = /msgsub/;
 1581:     var shwsel = "";
 1582:     if (re.test(msgchk)) { shwsel = "checked" }
 1583:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1584:     displaySubject(checkEntities(subject),shwsel);
 1585:     for (var i=1; i<=Nmsg; i++) {
 1586: 	var testmsg = "savemsg"+i+",";
 1587: 	re = new RegExp(testmsg,"g");
 1588: 	shwsel = "";
 1589: 	if (re.test(msgchk)) { shwsel = "checked" }
 1590: 	var message = document.SCORE["savemsg"+i].value;
 1591: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1592: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1593: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1594:     }
 1595:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1596:     shwsel = "";
 1597:     re = /newmsg/;
 1598:     if (re.test(msgchk)) { shwsel = "checked" }
 1599:     newMsg(newmsg,shwsel);
 1600:     msgTail(); 
 1601:     return;
 1602:   }
 1603: 
 1604:   function checkEntities(strx) {
 1605:     if (strx.length == 0) return strx;
 1606:     var orgStr = ["&", "<", ">", '"']; 
 1607:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1608:     var counter = 0;
 1609:     while (counter < 4) {
 1610: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1611: 	counter++;
 1612:     }
 1613:     return strx;
 1614:   }
 1615: 
 1616:   function strReplace(strx, orgStr, newStr) {
 1617:     return strx.split(orgStr).join(newStr);
 1618:   }
 1619: 
 1620:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1621:     var height = 70*Nmsg+250;
 1622:     if (height > 600) {
 1623: 	height = 600;
 1624:     }
 1625:     var xpos = (screen.width-600)/2;
 1626:     xpos = (xpos < 0) ? '0' : xpos;
 1627:     var ypos = (screen.height-height)/2-30;
 1628:     ypos = (ypos < 0) ? '0' : ypos;
 1629: 
 1630:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1631:     pWin.focus();
 1632:     pDoc = pWin.document;
 1633:     pDoc.$docopen;
 1634:     pDoc.write('$start_page_msg_central');
 1635: 
 1636:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1637:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1638:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1639: 
 1640:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1641:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1642:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1643: }
 1644:     function displaySubject(msg,shwsel) {
 1645:     pDoc = pWin.document;
 1646:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1647:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1648:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1649:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1650: }
 1651: 
 1652:   function displaySavedMsg(ctr,msg,shwsel) {
 1653:     pDoc = pWin.document;
 1654:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1655:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1656:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1657:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1658: }
 1659: 
 1660:   function newMsg(newmsg,shwsel) {
 1661:     pDoc = pWin.document;
 1662:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1663:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1664:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1665:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1666: }
 1667: 
 1668:   function msgTail() {
 1669:     pDoc = pWin.document;
 1670:     pDoc.write("<\\/table>");
 1671:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1672:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1673:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1674:     pDoc.write("<\\/form>");
 1675:     pDoc.write('$end_page_msg_central');
 1676:     pDoc.close();
 1677: }
 1678: 
 1679: //====================== Script for keyword highlight options ==============
 1680:   function kwhighlight() {
 1681:     var kwclr    = document.SCORE.kwclr.value;
 1682:     var kwsize   = document.SCORE.kwsize.value;
 1683:     var kwstyle  = document.SCORE.kwstyle.value;
 1684:     var redsel = "";
 1685:     var grnsel = "";
 1686:     var blusel = "";
 1687:     if (kwclr=="red")   {var redsel="checked"};
 1688:     if (kwclr=="green") {var grnsel="checked"};
 1689:     if (kwclr=="blue")  {var blusel="checked"};
 1690:     var sznsel = "";
 1691:     var sz1sel = "";
 1692:     var sz2sel = "";
 1693:     if (kwsize=="0")  {var sznsel="checked"};
 1694:     if (kwsize=="+1") {var sz1sel="checked"};
 1695:     if (kwsize=="+2") {var sz2sel="checked"};
 1696:     var synsel = "";
 1697:     var syisel = "";
 1698:     var sybsel = "";
 1699:     if (kwstyle=="")    {var synsel="checked"};
 1700:     if (kwstyle=="<i>") {var syisel="checked"};
 1701:     if (kwstyle=="<b>") {var sybsel="checked"};
 1702:     highlightCentral();
 1703:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1704:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1705:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1706:     highlightend();
 1707:     return;
 1708:   }
 1709: 
 1710:   function highlightCentral() {
 1711: //    if (window.hwdWin) window.hwdWin.close();
 1712:     var xpos = (screen.width-400)/2;
 1713:     xpos = (xpos < 0) ? '0' : xpos;
 1714:     var ypos = (screen.height-330)/2-30;
 1715:     ypos = (ypos < 0) ? '0' : ypos;
 1716: 
 1717:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1718:     hwdWin.focus();
 1719:     var hDoc = hwdWin.document;
 1720:     hDoc.$docopen;
 1721:     hDoc.write('$start_page_highlight_central');
 1722:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1723:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1724: 
 1725:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1726:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1727:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
 1728:   }
 1729: 
 1730:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1731:     var hDoc = hwdWin.document;
 1732:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1733:     hDoc.write("<td align=\\"left\\">");
 1734:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1735:     hDoc.write("<td align=\\"left\\">");
 1736:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1737:     hDoc.write("<td align=\\"left\\">");
 1738:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1739:     hDoc.write("<\\/tr>");
 1740:   }
 1741: 
 1742:   function highlightend() { 
 1743:     var hDoc = hwdWin.document;
 1744:     hDoc.write("<\\/table>");
 1745:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1746:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1747:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1748:     hDoc.write("<\\/form>");
 1749:     hDoc.write('$end_page_highlight_central');
 1750:     hDoc.close();
 1751:   }
 1752: 
 1753: </script>
 1754: SUBJAVASCRIPT
 1755: }
 1756: 
 1757: sub get_increment {
 1758:     my $increment = $env{'form.increment'};
 1759:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1760:         $increment != .1) {
 1761:         $increment = 1;
 1762:     }
 1763:     return $increment;
 1764: }
 1765: 
 1766: sub gradeBox_start {
 1767:     return (
 1768:         &Apache::loncommon::start_data_table()
 1769:        .&Apache::loncommon::start_data_table_header_row()
 1770:        .'<th>'.&mt('Part').'</th>'
 1771:        .'<th>'.&mt('Points').'</th>'
 1772:        .'<th>&nbsp;</th>'
 1773:        .'<th>'.&mt('Assign Grade').'</th>'
 1774:        .'<th>'.&mt('Weight').'</th>'
 1775:        .'<th>'.&mt('Grade Status').'</th>'
 1776:        .&Apache::loncommon::end_data_table_header_row()
 1777:     );
 1778: }
 1779: 
 1780: sub gradeBox_end {
 1781:     return (
 1782:         &Apache::loncommon::end_data_table()
 1783:     );
 1784: }
 1785: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1786: sub gradeBox {
 1787:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1788:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1789: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1790:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1791:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1792:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1793:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1794:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1795: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1796:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1797:     my $display_part= &get_display_part($partid,$symb);
 1798:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1799: 				       [$partid]);
 1800:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1801:     if ($last_resets{$partid}) {
 1802:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1803:     }
 1804:     my $result=&Apache::loncommon::start_data_table_row();
 1805:     my $ctr = 0;
 1806:     my $thisweight = 0;
 1807:     my $increment = &get_increment();
 1808: 
 1809:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1810:     while ($thisweight<=$wgt) {
 1811: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1812:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1813: 	    $thisweight.')" value="'.$thisweight.'" '.
 1814: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1815: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1816:         $thisweight += $increment;
 1817: 	$ctr++;
 1818:     }
 1819:     $radio.='</tr></table>';
 1820: 
 1821:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1822: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1823: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1824: 	$wgt.')" /></td>'."\n";
 1825:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1826: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1827: 	' </td>'."\n";
 1828:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1829: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1830:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1831: 	$line.='<option></option>'.
 1832: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1833:     } else {
 1834: 	$line.='<option selected="selected"></option>'.
 1835: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1836:     }
 1837:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1838: 
 1839: 
 1840:     $result .= 
 1841: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1842:     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
 1843:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1844: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1845: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1846: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1847:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1848:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1849:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1850:         $aggtries.'" />'."\n";
 1851:     my $res_error;
 1852:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1853:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1854:     if ($res_error) {
 1855:         return &navmap_errormsg();
 1856:     }
 1857:     return $result;
 1858: }
 1859: 
 1860: sub handback_box {
 1861:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1862:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1863:     my (@respids);
 1864:     my @part_response_id = &flatten_responseType($responseType);
 1865:     foreach my $part_response_id (@part_response_id) {
 1866:     	my ($part,$resp) = @{ $part_response_id };
 1867:         if ($part eq $partid) {
 1868:             push(@respids,$resp);
 1869:         }
 1870:     }
 1871:     my $result;
 1872:     foreach my $respid (@respids) {
 1873: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1874: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1875: 	next if (!@$files);
 1876: 	my $file_counter = 0;
 1877: 	foreach my $file (@$files) {
 1878: 	    if ($file =~ /\/portfolio\//) {
 1879:                 $file_counter++;
 1880:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1881:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1882:     	        $file_disp = "$name.$ext";
 1883:     	        $file = $file_path.$file_disp;
 1884:     	        $result.=&mt('Return commented version of [_1] to student.',
 1885:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1886:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1887:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1888: 	    }
 1889: 	}
 1890:         if ($file_counter) {
 1891:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1892:                        '<span class="LC_info">'.
 1893:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1894:         }
 1895:     }
 1896:     return $result;    
 1897: }
 1898: 
 1899: sub show_problem {
 1900:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1901:     my $rendered;
 1902:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1903:     &Apache::lonxml::remember_problem_counter();
 1904:     if ($mode eq 'both' or $mode eq 'text') {
 1905: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1906: 						       $env{'request.course.id'},
 1907: 						       undef,\%form);
 1908:     }
 1909:     if ($removeform) {
 1910: 	$rendered=~s|<form(.*?)>||g;
 1911: 	$rendered=~s|</form>||g;
 1912: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1913:     }
 1914:     my $companswer;
 1915:     if ($mode eq 'both' or $mode eq 'answer') {
 1916: 	&Apache::lonxml::restore_problem_counter();
 1917: 	$companswer=
 1918: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1919: 						    $env{'request.course.id'},
 1920: 						    %form);
 1921:     }
 1922:     if ($removeform) {
 1923: 	$companswer=~s|<form(.*?)>||g;
 1924: 	$companswer=~s|</form>||g;
 1925: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1926:     }
 1927:     my $renderheading = &mt('View of the problem');
 1928:     my $answerheading = &mt('Correct answer');
 1929:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1930:         my $stu_fullname = $env{'form.fullname'};
 1931:         if ($stu_fullname eq '') {
 1932:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1933:         }
 1934:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1935:         if ($forwhom ne '') {
 1936:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1937:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1938:         }
 1939:     }
 1940:     $rendered=
 1941:         '<div class="LC_Box">'
 1942:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1943:        .$rendered
 1944:        .'</div>';
 1945:     $companswer=
 1946:         '<div class="LC_Box">'
 1947:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1948:        .$companswer
 1949:        .'</div>';
 1950:     my $result;
 1951:     if ($mode eq 'both') {
 1952:         $result=$rendered.$companswer;
 1953:     } elsif ($mode eq 'text') {
 1954:         $result=$rendered;
 1955:     } elsif ($mode eq 'answer') {
 1956:         $result=$companswer;
 1957:     }
 1958:     return $result;
 1959: }
 1960: 
 1961: sub files_exist {
 1962:     my ($r, $symb) = @_;
 1963:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1964: 
 1965:     foreach my $student (@students) {
 1966:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1967:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1968: 					      $udom,$uname);
 1969:         my ($string,$timestamp)= &get_last_submission(\%record);
 1970:         foreach my $submission (@$string) {
 1971:             my ($partid,$respid) =
 1972: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1973:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1974: 					   \%record);
 1975:             return 1 if (@$files);
 1976:         }
 1977:     }
 1978:     return 0;
 1979: }
 1980: 
 1981: sub download_all_link {
 1982:     my ($r,$symb) = @_;
 1983:     my $all_students = 
 1984: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1985: 
 1986:     my $parts =
 1987: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1988: 
 1989:     my $identifier = &Apache::loncommon::get_cgi_id();
 1990:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1991:                              'cgi.'.$identifier.'.symb' => $symb,
 1992:                              'cgi.'.$identifier.'.parts' => $parts,});
 1993:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1994: 	      &mt('Download All Submitted Documents').'</a>');
 1995:     return
 1996: }
 1997: 
 1998: sub build_section_inputs {
 1999:     my $section_inputs;
 2000:     if ($env{'form.section'} eq '') {
 2001:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2002:     } else {
 2003:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2004:         foreach my $section (@sections) {
 2005:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2006:         }
 2007:     }
 2008:     return $section_inputs;
 2009: }
 2010: 
 2011: # --------------------------- show submissions of a student, option to grade 
 2012: sub submission {
 2013:     my ($request,$counter,$total) = @_;
 2014:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2015:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2016:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2017:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2018:     my ($symb) = &get_symb($request); 
 2019:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2020: 
 2021:     if (!&canview($usec)) {
 2022: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 2023: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 2024: 			$env{'request.course.id'}.')</span>');
 2025: 	$request->print(&show_grading_menu_form($symb));
 2026: 	return;
 2027:     }
 2028: 
 2029:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2030:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2031:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2032:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2033:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2034: 	'" src="'.$request->dir_config('lonIconsURL').
 2035: 	'/check.gif" height="16" border="0" />';
 2036: 
 2037:     # header info
 2038:     if ($counter == 0) {
 2039: 	&sub_page_js($request);
 2040: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2041: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2042: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2043: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2044: 	    &download_all_link($request, $symb);
 2045: 	}
 2046: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2047: 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
 2048: 
 2049: 	# option to display problem, only once else it cause problems 
 2050:         # with the form later since the problem has a form.
 2051: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2052: 	    my $mode;
 2053: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2054: 		$mode='both';
 2055: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2056: 		$mode='text';
 2057: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2058: 		$mode='answer';
 2059: 	    }
 2060: 	    &Apache::lonxml::clear_problem_counter();
 2061: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2062: 	}
 2063: 
 2064: 	# kwclr is the only variable that is guaranteed not to be blank 
 2065:         # if this subroutine has been called once.
 2066: 	my %keyhash = ();
 2067: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2068: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2069: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2070: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2071: 
 2072: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2073: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2074: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2075: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2076: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2077: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2078: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2079: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2080: 	}
 2081: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2082: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2083: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2084: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2085: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2086: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2087: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2088: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2089: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2090: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2091: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2092: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2093: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2094: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2095: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2096: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2097: 			&build_section_inputs().
 2098: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2099: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2100: 			'<input type="hidden" name="NCT"'.
 2101: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2102: 	if ($env{'form.handgrade'} eq 'yes') {
 2103: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2104: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2105: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2106: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2107: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2108: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2109: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2110: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2111: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2112: 	    }
 2113: 	}
 2114: 	
 2115: 	my ($cts,$prnmsg) = (1,'');
 2116: 	while ($cts <= $env{'form.savemsgN'}) {
 2117: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2118: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2119: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2120: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2121: 		'" />'."\n".
 2122: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2123: 	    $cts++;
 2124: 	}
 2125: 	$request->print($prnmsg);
 2126: 
 2127: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2128: 
 2129:             my %lt = &Apache::lonlocal::texthash(
 2130:                           keyw => 'Keyword Options',
 2131:                           list => 'List',
 2132:                           past => 'Paste Selection to List',
 2133:                           high => 'Highlight Attribute',
 2134:                      );
 2135: #
 2136: # Print out the keyword options line
 2137: #
 2138: 	    $request->print(<<KEYWORDS);
 2139: &nbsp;<b>$lt{'keyw'}:</b>&nbsp;
 2140: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2141: <a href="#" onmousedown="javascript:getSel(); return false"
 2142:  class="page">$lt{'past'}</a>&nbsp; &nbsp;
 2143: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2144: KEYWORDS
 2145: #
 2146: # Load the other essays for similarity check
 2147: #
 2148:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2149: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2150: 	    $apath=&escape($apath);
 2151: 	    $apath=~s/\W/\_/gs;
 2152:             &init_old_essays($symb,$apath,$adom,$aname);
 2153:         }
 2154:     }
 2155: 
 2156: # This is where output for one specific student would start
 2157:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2158:     $request->print(
 2159:         "\n\n"
 2160:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2161:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2162:        ."\n"
 2163:     );
 2164: 
 2165:     # Show additional functions if allowed
 2166:     if ($perm{'vgr'}) {
 2167:         $request->print(
 2168:             &Apache::loncommon::track_student_link(
 2169:                 &mt('View recent activity'),
 2170:                 $uname,$udom,'check')
 2171:            .' '
 2172:         );
 2173:     }
 2174:     if ($perm{'opa'}) {
 2175:         $request->print(
 2176:             &Apache::loncommon::pprmlink(
 2177:                 &mt('Set/Change parameters'),
 2178:                 $uname,$udom,$symb,'check'));
 2179:     }
 2180: 
 2181:     # Show Problem
 2182:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2183: 	my $mode;
 2184: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2185: 	    $mode='both';
 2186: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2187: 	    $mode='text';
 2188: 	} elsif ($env{'form.vAns'} eq 'all') {
 2189: 	    $mode='answer';
 2190: 	}
 2191: 	&Apache::lonxml::clear_problem_counter();
 2192: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2193:     }
 2194: 
 2195:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2196:     my $res_error;
 2197:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2198:     if ($res_error) {
 2199:         $request->print(&navmap_errormsg());
 2200:         return;
 2201:     }
 2202: 
 2203:     # Display student info
 2204:     $request->print(($counter == 0 ? '' : '<br />'));
 2205: 
 2206:     my $result='<div class="LC_Box">'
 2207:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2208:     $result.='<input type="hidden" name="name'.$counter.
 2209:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2210:     if ($env{'form.handgrade'} eq 'no') {
 2211:         $result.='<p class="LC_info">'
 2212:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2213:                 ."</p>\n";
 2214:     }
 2215: 
 2216:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2217:     my $fullname;
 2218:     my $col_fullnames = [];
 2219:     if ($env{'form.handgrade'} eq 'yes') {
 2220: 	(my $sub_result,$fullname,$col_fullnames)=
 2221: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2222: 				 $counter);
 2223: 	$result.=$sub_result;
 2224:     }
 2225:     $request->print($result."\n");
 2226: 
 2227:     # print student answer/submission
 2228:     # Options are (1) Handgraded submission only
 2229:     #             (2) Last submission, includes submission that is not handgraded 
 2230:     #                  (for multi-response type part)
 2231:     #             (3) Last submission plus the parts info
 2232:     #             (4) The whole record for this student
 2233: 
 2234: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2235: 	
 2236: 	my $lastsubonly;
 2237: 
 2238:         if ($$timestamp eq '') {
 2239:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2240:         } else {
 2241:             $lastsubonly =
 2242:                 '<div class="LC_grade_submissions_body">'
 2243:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2244: 
 2245: 	    my %seenparts;
 2246: 	    my @part_response_id = &flatten_responseType($responseType);
 2247: 	    foreach my $part (@part_response_id) {
 2248: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2249: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2250: 
 2251: 		my ($partid,$respid) = @{ $part };
 2252: 		my $display_part=&get_display_part($partid,$symb);
 2253: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2254: 		    if (exists($seenparts{$partid})) { next; }
 2255: 		    $seenparts{$partid}=1;
 2256:                     $request->print(
 2257:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2258:                         ' <b>'.&mt('Collaborative submission by: [_1]',
 2259:                                    '<a href="javascript:viewSubmitter(\''.
 2260:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
 2261:                                    '\');" target="_self">'.
 2262:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2263:                         '<br />');
 2264: 		    next;
 2265: 		}
 2266: 		my $responsetype = $responseType->{$partid}->{$respid};
 2267: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2268:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2269:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2270:                         ' <span class="LC_internal_info">'.
 2271:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2272:                         '</span>&nbsp; &nbsp;'.
 2273: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2274: 		    next;
 2275: 		}
 2276: 		foreach my $submission (@$string) {
 2277: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2278: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2279: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2280: 		    # Similarity check
 2281: 		    my $similar='';
 2282:                     my ($type,$trial,$rndseed);
 2283:                     if ($hide eq 'rand') {
 2284:                         $type = 'randomizetry';
 2285:                         $trial = $record{"resource.$partid.tries"};
 2286:                         $rndseed = $record{"resource.$partid.rndseed"};
 2287:                     }
 2288: 		    if ($env{'form.checkPlag'}) {
 2289: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2290: 			    &most_similar($uname,$udom,$symb,$subval);
 2291: 			if ($osim) {
 2292: 			    $osim=int($osim*100.0);
 2293: 			    my %old_course_desc = 
 2294: 				&Apache::lonnet::coursedescription($ocrsid,
 2295: 								   {'one_time' => 1});
 2296: 
 2297:                             if ($hide eq 'anon') {
 2298:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2299:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2300:                             } else {
 2301: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2302: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2303: 				        $osim,
 2304: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2305: 				        $old_course_desc{'description'},
 2306: 				        $old_course_desc{'num'},
 2307: 				        $old_course_desc{'domain'}).
 2308: 				    '</span></h3><blockquote><i>'.
 2309: 				    &keywords_highlight($oessay).
 2310: 				    '</i></blockquote><hr />';
 2311:                             }
 2312: 			}
 2313: 		    }
 2314: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2315:                                          undef,$type,$trial,$rndseed);
 2316:                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
 2317:                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2318: 			my $display_part=&get_display_part($partid,$symb);
 2319:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2320:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2321:                             ' <span class="LC_internal_info">'.
 2322:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2323:                             '</span>&nbsp; &nbsp;';
 2324: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2325: 			if (@$files) {
 2326:                             if ($hide eq 'anon') {
 2327:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2328:                             } else {
 2329:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2330:                                             .'<br /><span class="LC_warning">';
 2331:                                 if(@$files == 1) {
 2332:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2333:                                 } else {
 2334:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2335:                                 }
 2336:                                 $lastsubonly .= '</span>';
 2337: 
 2338:                                 foreach my $file (@$files) {
 2339:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2340:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2341:                                 }
 2342:                             }
 2343: 			    $lastsubonly.='<br />';
 2344: 			}
 2345:                         if ($hide eq 'anon') {
 2346:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2347:                         } else {
 2348: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
 2349: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2350: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2351:                         }
 2352: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2353: 			$lastsubonly.='</div>';
 2354: 		    }
 2355: 		}
 2356: 	    }
 2357: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2358: 	}
 2359: 	$request->print($lastsubonly);
 2360:    if ($env{'form.lastSub'} eq 'datesub') {
 2361: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2362: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2363:     }
 2364:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2365: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2366: 								 $env{'request.course.id'},
 2367: 								 $last,'.submission',
 2368: 								 'Apache::grades::keywords_highlight'));
 2369:     }
 2370: 
 2371:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2372: 	.$udom.'" />'."\n");
 2373:     # return if view submission with no grading option
 2374:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2375: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2376: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2377: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2378: 	$toGrade.='</div>'."\n";
 2379: 	if (($env{'form.command'} eq 'submission') || 
 2380: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2381: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2382: 	}
 2383: 	$request->print($toGrade);
 2384: 	return;
 2385:     } else {
 2386: 	$request->print('</div>'."\n");
 2387:     }
 2388: 
 2389:     # essay grading message center
 2390:     if ($env{'form.handgrade'} eq 'yes') {
 2391: 	my $result='<div class="LC_grade_message_center">';
 2392:     
 2393: 	$result.='<div class="LC_grade_message_center_header">'.
 2394: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2395: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2396: 	my $msgfor = $givenn.' '.$lastname;
 2397: 	if (scalar(@$col_fullnames) > 0) {
 2398: 	    my $lastone = pop(@$col_fullnames);
 2399: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2400: 	}
 2401: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2402: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2403: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2404: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2405: 	    ',\''.$msgfor.'\');" target="_self">'.
 2406: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2407: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2408: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2409: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2410: 	    '<br />&nbsp;('.
 2411: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2412: 	$result.='</div></div>';
 2413: 	$request->print($result);
 2414:     }
 2415: 
 2416:     my %seen = ();
 2417:     my @partlist;
 2418:     my @gradePartRespid;
 2419:     my @part_response_id = &flatten_responseType($responseType);
 2420:     $request->print(
 2421:         '<div class="LC_Box">'
 2422:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2423:     );
 2424:     $request->print(&gradeBox_start());
 2425:     foreach my $part_response_id (@part_response_id) {
 2426:     	my ($partid,$respid) = @{ $part_response_id };
 2427: 	my $part_resp = join('_',@{ $part_response_id });
 2428: 	next if ($seen{$partid} > 0);
 2429: 	$seen{$partid}++;
 2430: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2431: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2432: 	push(@partlist,$partid);
 2433: 	push(@gradePartRespid,$partid.'.'.$respid);
 2434: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2435:     }
 2436:     $request->print(&gradeBox_end()); # </div>
 2437:     $request->print('</div>');
 2438: 
 2439:     $request->print('<div class="LC_grade_info_links">');
 2440:     $request->print('</div>');
 2441: 
 2442:     $result='<input type="hidden" name="partlist'.$counter.
 2443: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2444:     $result.='<input type="hidden" name="gradePartRespid'.
 2445: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2446:     my $ctr = 0;
 2447:     while ($ctr < scalar(@partlist)) {
 2448: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2449: 	    $partlist[$ctr].'" />'."\n";
 2450: 	$ctr++;
 2451:     }
 2452:     $request->print($result.''."\n");
 2453: 
 2454: # Done with printing info for one student
 2455: 
 2456:     $request->print('</div>');#LC_grade_show_user
 2457: 
 2458: 
 2459:     # print end of form
 2460:     if ($counter == $total) {
 2461:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2462: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2463: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2464: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2465: 	my $ntstu ='<select name="NTSTU">'.
 2466: 	    '<option>1</option><option>2</option>'.
 2467: 	    '<option>3</option><option>5</option>'.
 2468: 	    '<option>7</option><option>10</option></select>'."\n";
 2469: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2470: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2471:         $endform.=&mt('[_1]student(s)',$ntstu);
 2472: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2473: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2474: 	    '<input type="button" value="'.&mt('Next').'" '.
 2475: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2476:         $endform.='<span class="LC_warning">'.
 2477:                   &mt('(Next and Previous (student) do not save the scores.)').
 2478:                   '</span>'."\n" ;
 2479:         $endform.="<input type='hidden' value='".&get_increment().
 2480:             "' name='increment' />";
 2481: 	$endform.='</td></tr></table></form>';
 2482: 	$endform.=&show_grading_menu_form($symb);
 2483: 	$request->print($endform);
 2484:     }
 2485:     return '';
 2486: }
 2487: 
 2488: sub check_collaborators {
 2489:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2490:     my ($result,@col_fullnames);
 2491:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2492:     foreach my $part (keys(%$handgrade)) {
 2493: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2494: 					'.maxcollaborators',
 2495: 					$symb,$udom,$uname);
 2496: 	next if ($ncol <= 0);
 2497: 	$part =~ s/\_/\./g;
 2498: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2499: 	my (@good_collaborators, @bad_collaborators);
 2500: 	foreach my $possible_collaborator
 2501: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2502: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2503: 	    next if ($possible_collaborator eq '');
 2504: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2505: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2506: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2507: 	    # Doing this grep allows 'fuzzy' specification
 2508: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2509: 			       keys(%$classlist));
 2510: 	    if (! scalar(@matches)) {
 2511: 		push(@bad_collaborators, $possible_collaborator);
 2512: 	    } else {
 2513: 		push(@good_collaborators, @matches);
 2514: 	    }
 2515: 	}
 2516: 	if (scalar(@good_collaborators) != 0) {
 2517: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2518: 	    foreach my $name (@good_collaborators) {
 2519: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2520: 		push(@col_fullnames, $givenn.' '.$lastname);
 2521: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2522: 	    }
 2523: 	    $result.='</ol><br />'."\n";
 2524: 	    my ($part)=split(/\./,$part);
 2525: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2526: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2527: 		"\n";
 2528: 	}
 2529: 	if (scalar(@bad_collaborators) > 0) {
 2530: 	    $result.='<div class="LC_warning">';
 2531: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2532: 	    $result .= '</div>';
 2533: 	}         
 2534: 	if (scalar(@bad_collaborators > $ncol)) {
 2535: 	    $result .= '<div class="LC_warning">';
 2536: 	    $result .= &mt('This student has submitted too many '.
 2537: 		'collaborators.  Maximum is [_1].',$ncol);
 2538: 	    $result .= '</div>';
 2539: 	}
 2540:     }
 2541:     return ($result,$fullname,\@col_fullnames);
 2542: }
 2543: 
 2544: #--- Retrieve the last submission for all the parts
 2545: sub get_last_submission {
 2546:     my ($returnhash)=@_;
 2547:     my (@string,$timestamp,%lasthidden);
 2548:     if ($$returnhash{'version'}) {
 2549: 	my %lasthash=();
 2550: 	my ($version);
 2551: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2552: 	    foreach my $key (sort(split(/\:/,
 2553: 					$$returnhash{$version.':keys'}))) {
 2554: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2555: 		$timestamp = 
 2556: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2557: 	    }
 2558: 	}
 2559:         my (%typeparts,%randombytry);
 2560:         my $showsurv = 
 2561:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2562:         foreach my $key (sort(keys(%lasthash))) {
 2563:             if ($key =~ /\.type$/) {
 2564:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2565:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2566:                     ($lasthash{$key} eq 'randomizetry')) {
 2567:                     my ($ign,@parts) = split(/\./,$key);
 2568:                     pop(@parts);
 2569:                     my $id = join('.',@parts);
 2570:                     if ($lasthash{$key} eq 'randomizetry') {
 2571:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2572:                     } else {
 2573:                         unless ($showsurv) {
 2574:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2575:                         }
 2576:                     }
 2577:                     delete($lasthash{$key});
 2578:                 }
 2579:             }
 2580:         }
 2581:         my @hidden = keys(%typeparts);
 2582:         my @randomize = keys(%randombytry);
 2583: 	foreach my $key (keys(%lasthash)) {
 2584: 	    next if ($key !~ /\.submission$/);
 2585:             my $hide;
 2586:             if (@hidden) {
 2587:                 foreach my $id (@hidden) {
 2588:                     if ($key =~ /^\Q$id\E/) {
 2589:                         $hide = 'anon';
 2590:                         last;
 2591:                     }
 2592:                 }
 2593:             }
 2594:             unless ($hide) {
 2595:                 if (@randomize) {
 2596:                     foreach my $id (@hidden) {
 2597:                         if ($key =~ /^\Q$id\E/) {
 2598:                             $hide = 'rand';
 2599:                             last;
 2600:                         }
 2601:                     }
 2602:                 }
 2603:             }
 2604: 	    my ($partid,$foo) = split(/submission$/,$key);
 2605: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2606: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2607: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2608: 	}
 2609:     }
 2610:     if (!@string) {
 2611: 	$string[0] =
 2612: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2613:     }
 2614:     return (\@string,\$timestamp);
 2615: }
 2616: 
 2617: #--- High light keywords, with style choosen by user.
 2618: sub keywords_highlight {
 2619:     my $string    = shift;
 2620:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2621:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2622:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2623:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2624:     foreach my $keyword (@keylist) {
 2625: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2626:     }
 2627:     return $string;
 2628: }
 2629: 
 2630: # For Tasks provide a mechanism to display previous version for one specific student
 2631: 
 2632: sub show_previous_task_version {
 2633:     my ($request,$symb) = @_;
 2634:     if ($symb eq '') {
 2635:         $request->print("Unable to handle ambiguous references.");
 2636: 
 2637:         return '';
 2638:     }
 2639:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2640:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2641:     if (!&canview($usec)) {
 2642:         $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
 2643:                         $uname.':'.$udom.' in section '.$usec.' in course id '.
 2644:                         $env{'request.course.id'}.')</span>');
 2645:         return;
 2646:     }
 2647:     my $mode = 'both';
 2648:     my $isTask = ($symb =~/\.task$/);
 2649:     if ($isTask) {
 2650:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2651:             if ($env{'form.fullname'} eq '') {
 2652:                 $env{'form.fullname'} =
 2653:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2654:             }
 2655:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2656:             $request->print("\n\n".
 2657:                             '<div class="LC_grade_show_user">'.
 2658:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2659:                             '</h2>'."\n");
 2660:             &Apache::lonxml::clear_problem_counter();
 2661:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2662:                             {'previousversion' => $env{'form.previousversion'} }));
 2663:             $request->print("\n</div>");
 2664:         }
 2665:     }
 2666:     return;
 2667: }
 2668: 
 2669: sub choose_task_version_form {
 2670:     my ($symb,$uname,$udom,$nomenu) = @_;
 2671:     my $isTask = ($symb =~/\.task$/);
 2672:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2673:     if ($isTask) {
 2674:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2675:                                               $udom,$uname);
 2676:         if (($record{'resource.0.version'} eq '') ||
 2677:             ($record{'resource.0.version'} < 2)) {
 2678:             return ($record{'resource.0.version'},
 2679:                     $record{'resource.0.version'},$result,$js);
 2680:         } else {
 2681:             $current = $record{'resource.0.version'};
 2682:         }
 2683:         if ($env{'form.previousversion'}) {
 2684:             $displayed = $env{'form.previousversion'};
 2685:             $rowtitle = &mt('Choose another version:')
 2686:         } else {
 2687:             $displayed = $current;
 2688:             $rowtitle = &mt('Show earlier version:');
 2689:         }
 2690:         $result = '<div class="LC_left_float">';
 2691:         my $list;
 2692:         my $numversions = 0;
 2693:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2694:             if ($i == $current) {
 2695:                 if (!$env{'form.previousversion'} || $nomenu) {
 2696:                     next;
 2697:                 } else {
 2698:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2699:                     $numversions ++;
 2700:                 }
 2701:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2702:                 unless ($i == $env{'form.previousversion'}) {
 2703:                     $numversions ++;
 2704:                 }
 2705:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2706:             }
 2707:         }
 2708:         if ($numversions) {
 2709:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2710:             $result .=
 2711:                 '<form name="getprev" method="post" action=""'.
 2712:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2713:                 &Apache::loncommon::start_data_table().
 2714:                 &Apache::loncommon::start_data_table_row().
 2715:                 '<th align="left">'.$rowtitle.'</th>'.
 2716:                 '<td><select name="version">'.
 2717:                 '<option>'.&mt('Select').'</option>'.
 2718:                 $list.
 2719:                 '</select></td>'.
 2720:                 &Apache::loncommon::end_data_table_row();
 2721:             unless ($nomenu) {
 2722:                 $result .= &Apache::loncommon::start_data_table_row().
 2723:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2724:                 '<td><span class="LC_nobreak">'.
 2725:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2726:                 &mt('Yes').'</label>'.
 2727:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2728:                 '</span></td>'.
 2729:                 &Apache::loncommon::end_data_table_row();
 2730:             }
 2731:             $result .=
 2732:                 &Apache::loncommon::start_data_table_row().
 2733:                 '<th align="left">&nbsp;</th>'.
 2734:                 '<td>'.
 2735:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2736:                 '</td>'.
 2737:                 &Apache::loncommon::end_data_table_row().
 2738:                 &Apache::loncommon::end_data_table().
 2739:                 '</form>';
 2740:             $js = &previous_display_javascript($nomenu,$current);
 2741:         } elsif ($displayed && $nomenu) {
 2742:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2743:         } else {
 2744:             $result .= &mt('No previous versions to show for this student');
 2745:         }
 2746:         $result .= '</div>';
 2747:     }
 2748:     return ($current,$displayed,$result,$js);
 2749: }
 2750: 
 2751: sub previous_display_javascript {
 2752:     my ($nomenu,$current) = @_;
 2753:     my $js = <<"JSONE";
 2754: <script type="text/javascript">
 2755: // <![CDATA[
 2756: function previousVersion(uname,udom,symb) {
 2757:     var current = '$current';
 2758:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2759:     var prevstr = new RegExp("^\\\\d+\$");
 2760:     if (!prevstr.test(version)) {
 2761:         return false;
 2762:     }
 2763:     var url = '';
 2764:     if (version == current) {
 2765:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2766:     } else {
 2767:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2768:     }
 2769: JSONE
 2770:     if ($nomenu) {
 2771:         $js .= <<"JSTWO";
 2772:     document.location.href = url;
 2773: JSTWO
 2774:     } else {
 2775:         $js .= <<"JSTHREE";
 2776:     var newwin = 0;
 2777:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2778:         if (document.getprev.prevwin[i].checked == true) {
 2779:             newwin = document.getprev.prevwin[i].value;
 2780:         }
 2781:     }
 2782:     if (newwin == 1) {
 2783:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2784:         url = url+'&inhibitmenu=yes';
 2785:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2786:             previousWin = window.open(url,'',options,1);
 2787:         } else {
 2788:             previousWin.location.href = url;
 2789:         }
 2790:         previousWin.focus();
 2791:         return false;
 2792:     } else {
 2793:         document.location.href = url;
 2794:         return false;
 2795:     }
 2796: JSTHREE
 2797:     }
 2798:     $js .= <<"ENDJS";
 2799:     return false;
 2800: }
 2801: // ]]>
 2802: </script>
 2803: ENDJS
 2804: 
 2805: }
 2806: 
 2807: #--- Called from submission routine
 2808: sub processHandGrade {
 2809:     my ($request) = shift;
 2810:     my ($symb)   = &get_symb($request);
 2811:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2812:     my $button = $env{'form.gradeOpt'};
 2813:     my $ngrade = $env{'form.NCT'};
 2814:     my $ntstu  = $env{'form.NTSTU'};
 2815:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2816:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2817: 
 2818:     if ($button eq 'Save & Next') {
 2819: 	my $ctr = 0;
 2820: 	while ($ctr < $ngrade) {
 2821: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2822: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2823: 	    if ($errorflag eq 'no_score') {
 2824: 		$ctr++;
 2825: 		next;
 2826: 	    }
 2827: 	    if ($errorflag eq 'not_allowed') {
 2828: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2829: 		$ctr++;
 2830: 		next;
 2831: 	    }
 2832: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2833: 	    my ($subject,$message,$msgstatus) = ('','','');
 2834: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2835:             my ($feedurl,$showsymb) =
 2836: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2837: 	    my $messagetail;
 2838: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2839: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2840: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2841: 		$subject.=' ['.$restitle.']';
 2842: 		my (@msgnum) = split(/,/,$includemsg);
 2843: 		foreach (@msgnum) {
 2844: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2845: 		}
 2846: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2847: 		if ($env{'form.withgrades'.$ctr}) {
 2848: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2849: 		    $messagetail = " for <a href=\"".
 2850: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2851: 		}
 2852: 		$msgstatus = 
 2853:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2854: 						     $message.$messagetail,
 2855:                                                      undef,$feedurl,undef,
 2856:                                                      undef,undef,$showsymb,
 2857:                                                      $restitle);
 2858: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2859: 				$msgstatus.'<br />');
 2860: 	    }
 2861: 	    if ($env{'form.collaborator'.$ctr}) {
 2862: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2863: 		foreach my $collabstr (@collabstrs) {
 2864: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2865: 		    foreach my $collaborator (@collaborators) {
 2866: 			my ($errorflag,$pts,$wgt) = 
 2867: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2868: 					   $env{'form.unamedom'.$ctr},$part);
 2869: 			if ($errorflag eq 'not_allowed') {
 2870: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2871: 			    next;
 2872: 			} elsif ($message ne '') {
 2873: 			    my ($baseurl,$showsymb) = 
 2874: 				&get_feedurl_and_symb($symb,$collaborator,
 2875: 						      $udom);
 2876: 			    if ($env{'form.withgrades'.$ctr}) {
 2877: 				$messagetail = " for <a href=\"".
 2878:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2879: 			    }
 2880: 			    $msgstatus = 
 2881: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2882: 			}
 2883: 		    }
 2884: 		}
 2885: 	    }
 2886: 	    $ctr++;
 2887: 	}
 2888:     }
 2889: 
 2890:     if ($env{'form.handgrade'} eq 'yes') {
 2891: 	# Keywords sorted in alphabatical order
 2892: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2893: 	my %keyhash = ();
 2894: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2895: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2896: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2897: 	$env{'form.keywords'} = join(' ',@keywords);
 2898: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2899: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2900: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2901: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2902: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2903: 
 2904: 	# message center - Order of message gets changed. Blank line is eliminated.
 2905: 	# New messages are saved in env for the next student.
 2906: 	# All messages are saved in nohist_handgrade.db
 2907: 	my ($ctr,$idx) = (1,1);
 2908: 	while ($ctr <= $env{'form.savemsgN'}) {
 2909: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2910: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2911: 		$idx++;
 2912: 	    }
 2913: 	    $ctr++;
 2914: 	}
 2915: 	$ctr = 0;
 2916: 	while ($ctr < $ngrade) {
 2917: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2918: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2919: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2920: 		$idx++;
 2921: 	    }
 2922: 	    $ctr++;
 2923: 	}
 2924: 	$env{'form.savemsgN'} = --$idx;
 2925: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2926: 	my $putresult = &Apache::lonnet::put
 2927: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2928:     }
 2929:     # Called by Save & Refresh from Highlight Attribute Window
 2930:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2931:     if ($env{'form.refresh'} eq 'on') {
 2932: 	my ($ctr,$total) = (0,0);
 2933: 	while ($ctr < $ngrade) {
 2934: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2935: 	    $ctr++;
 2936: 	}
 2937: 	$env{'form.NTSTU'}=$ngrade;
 2938: 	$ctr = 0;
 2939: 	while ($ctr < $total) {
 2940: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2941: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2942: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2943: 	    &submission($request,$ctr,$total-1);
 2944: 	    $ctr++;
 2945: 	}
 2946: 	return '';
 2947:     }
 2948: 
 2949: # Go directly to grade student - from submission or link from chart page
 2950:     if ($button eq 'Grade Student') {
 2951: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2952: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2953: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2954: 	$env{'form.fullname'} = $$fullname{$processUser};
 2955: 	&submission($request,0,0);
 2956: 	return '';
 2957:     }
 2958: 
 2959:     # Get the next/previous one or group of students
 2960:     my $firststu = $env{'form.unamedom0'};
 2961:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2962:     my $ctr = 2;
 2963:     while ($laststu eq '') {
 2964: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2965: 	$ctr++;
 2966: 	$laststu = $firststu if ($ctr > $ngrade);
 2967:     }
 2968: 
 2969:     my (@parsedlist,@nextlist);
 2970:     my ($nextflg) = 0;
 2971:     foreach my $item (sort 
 2972: 	     {
 2973: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2974: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2975: 		 }
 2976: 		 return $a cmp $b;
 2977: 	     } (keys(%$fullname))) {
 2978: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2979: 	    push(@parsedlist,$item);
 2980: 	}
 2981: 	$nextflg = 1 if ($item eq $laststu);
 2982: 	if ($button eq 'Previous') {
 2983: 	    last if ($item eq $firststu);
 2984: 	    push(@parsedlist,$item);
 2985: 	}
 2986:     }
 2987:     $ctr = 0;
 2988:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2989:     my $res_error;
 2990:     my ($partlist) = &response_type($symb,\$res_error);
 2991:     if ($res_error) {
 2992:         $request->print(&navmap_errormsg());
 2993:         return;
 2994:     }
 2995:     foreach my $student (@parsedlist) {
 2996: 	my $submitonly=$env{'form.submitonly'};
 2997: 	my ($uname,$udom) = split(/:/,$student);
 2998: 	
 2999: 	if ($submitonly eq 'queued') {
 3000: 	    my %queue_status = 
 3001: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3002: 							$udom,$uname);
 3003: 	    next if (!defined($queue_status{'gradingqueue'}));
 3004: 	}
 3005: 
 3006: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3007: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3008: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3009: 	    my $submitted = 0;
 3010: 	    my $ungraded = 0;
 3011: 	    my $incorrect = 0;
 3012: 	    foreach my $item (keys(%status)) {
 3013: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3014: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3015: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3016: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3017: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3018: 		    $submitted = 0;
 3019: 		}
 3020: 	    }
 3021: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3022: 				     $submitonly eq 'incorrect' ||
 3023: 				     $submitonly eq 'graded'));
 3024: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3025: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3026: 	}
 3027: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3028: 	last if ($ctr == $ntstu);
 3029: 	$ctr++;
 3030:     }
 3031: 
 3032:     $ctr = 0;
 3033:     my $total = scalar(@nextlist)-1;
 3034: 
 3035:     foreach (sort(@nextlist)) {
 3036: 	my ($uname,$udom,$submitter) = split(/:/);
 3037: 	$env{'form.student'}  = $uname;
 3038: 	$env{'form.userdom'}  = $udom;
 3039: 	$env{'form.fullname'} = $$fullname{$_};
 3040: 	&submission($request,$ctr,$total);
 3041: 	$ctr++;
 3042:     }
 3043:     if ($total < 0) {
 3044: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3045: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3046: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3047: 	$the_end.=&show_grading_menu_form($symb);
 3048: 	$request->print($the_end);
 3049:     }
 3050:     return '';
 3051: }
 3052: 
 3053: #---- Save the score and award for each student, if changed
 3054: sub saveHandGrade {
 3055:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3056:     my @version_parts;
 3057:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3058: 					   $env{'request.course.id'});
 3059:     if (!&canmodify($usec)) { return('not_allowed'); }
 3060:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3061:     my @parts_graded;
 3062:     my %newrecord  = ();
 3063:     my ($pts,$wgt) = ('','');
 3064:     my %aggregate = ();
 3065:     my $aggregateflag = 0;
 3066:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3067:     foreach my $new_part (@parts) {
 3068: 	#collaborator ($submi may vary for different parts
 3069: 	if ($submitter && $new_part ne $part) { next; }
 3070: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3071: 	if ($dropMenu eq 'excused') {
 3072: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3073: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3074: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3075: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3076: 		}
 3077: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3078: 	    }
 3079: 	} elsif ($dropMenu eq 'reset status'
 3080: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3081: 	    foreach my $key (keys(%record)) {
 3082: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3083: 	    }
 3084: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3085: 		"$env{'user.name'}:$env{'user.domain'}";
 3086:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3087: 
 3088:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3089: 					       [$new_part]);
 3090:             my $aggtries =$totaltries;
 3091:             if ($last_resets{$new_part}) {
 3092:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3093: 					   $new_part);
 3094:             }
 3095: 
 3096:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3097:             if ($aggtries > 0) {
 3098:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3099:                 $aggregateflag = 1;
 3100:             }
 3101: 	} elsif ($dropMenu eq '') {
 3102: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3103: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3104: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3105: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3106: 		next;
 3107: 	    }
 3108: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3109: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3110: 	    my $partial= $pts/$wgt;
 3111: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3112: 		#do not update score for part if not changed.
 3113:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3114: 		next;
 3115: 	    } else {
 3116: 	        push(@parts_graded,$new_part);
 3117: 	    }
 3118: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3119: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3120: 	    }
 3121: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3122: 	    if ($partial == 0) {
 3123: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3124: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3125: 		}
 3126: 	    } else {
 3127: 		if ($record{$reckey} ne 'correct_by_override') {
 3128: 		    $newrecord{$reckey} = 'correct_by_override';
 3129: 		}
 3130: 	    }	    
 3131: 	    if ($submitter && 
 3132: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3133: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3134: 	    }
 3135: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3136: 		"$env{'user.name'}:$env{'user.domain'}";
 3137: 	}
 3138: 	# unless problem has been graded, set flag to version the submitted files
 3139: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3140: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3141: 	        $dropMenu eq 'reset status')
 3142: 	   {
 3143: 	    push(@version_parts,$new_part);
 3144: 	}
 3145:     }
 3146:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3147:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3148: 
 3149:     if (%newrecord) {
 3150:         if (@version_parts) {
 3151:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3152:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3153: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3154: 	    foreach my $new_part (@version_parts) {
 3155: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3156: 				$new_part,\%newrecord);
 3157: 	    }
 3158:         }
 3159: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3160: 				$env{'request.course.id'},$domain,$stuname);
 3161: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3162: 				     $cdom,$cnum,$domain,$stuname);
 3163:     }
 3164:     if ($aggregateflag) {
 3165:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3166: 			      $cdom,$cnum);
 3167:     }
 3168:     return ('',$pts,$wgt);
 3169: }
 3170: 
 3171: sub check_and_remove_from_queue {
 3172:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3173:     my @ungraded_parts;
 3174:     foreach my $part (@{$parts}) {
 3175: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3176: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3177: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3178: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3179: 		) {
 3180: 	    push(@ungraded_parts, $part);
 3181: 	}
 3182:     }
 3183:     if ( !@ungraded_parts ) {
 3184: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3185: 					       $cnum,$domain,$stuname);
 3186:     }
 3187: }
 3188: 
 3189: sub handback_files {
 3190:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3191:     my $portfolio_root = '/userfiles/portfolio';
 3192:     my $res_error;
 3193:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3194:     if ($res_error) {
 3195:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3196:         return;
 3197:     }
 3198:     my @handedback;
 3199:     my $file_msg;
 3200:     my @part_response_id = &flatten_responseType($responseType);
 3201:     foreach my $part_response_id (@part_response_id) {
 3202:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3203: 	my $part_resp = join('_',@{ $part_response_id });
 3204:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3205:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3206:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3207: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3208:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3209:                     my ($directory,$answer_file) = 
 3210:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3211:                     my ($answer_name,$answer_ver,$answer_ext) =
 3212: 		        &file_name_version_ext($answer_file);
 3213: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3214:                     my $getpropath = 1;
 3215:                     my ($dir_list,$listerror) =
 3216:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3217:                                                  $domain,$stuname,$getpropath);
 3218: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3219:                     # fix filename
 3220:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3221:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3222:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3223:             	                                $save_file_name);
 3224:                     if ($result !~ m|^/uploaded/|) {
 3225:                         $request->print('<br /><span class="LC_error">'.
 3226:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3227:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3228:                                         '</span>');
 3229:                     } else {
 3230:                         # mark the file as read only
 3231:                         push(@handedback,$save_file_name);
 3232: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3233: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3234: 			}
 3235:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3236: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3237: 
 3238:                     }
 3239:                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 3240:                 }
 3241:             }
 3242:         }
 3243:     }
 3244:     if (@handedback > 0) {
 3245:         $request->print('<br />');
 3246:         my @what = ($symb,$env{'request.course.id'},'handback');
 3247:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3248:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3249:         my ($subject,$message);
 3250:         if (scalar(@handedback) == 1) {
 3251:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3252:         } else {
 3253:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3254:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3255:         }
 3256:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3257:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3258:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3259:         my ($feedurl,$showsymb) =
 3260:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3261:         my $restitle = &Apache::lonnet::gettitle($symb);
 3262:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3263:         my $msgstatus =
 3264:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3265:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3266:                  $restitle);
 3267:         if ($msgstatus) {
 3268:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3269:         }
 3270:     }
 3271:     return;
 3272: }
 3273: 
 3274: sub get_feedurl_and_symb {
 3275:     my ($symb,$uname,$udom) = @_;
 3276:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3277:     $url = &Apache::lonnet::clutter($url);
 3278:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3279: 					$symb,$udom,$uname);
 3280:     if ($encrypturl =~ /^yes$/i) {
 3281: 	&Apache::lonenc::encrypted(\$url,1);
 3282: 	&Apache::lonenc::encrypted(\$symb,1);
 3283:     }
 3284:     return ($url,$symb);
 3285: }
 3286: 
 3287: sub get_submitted_files {
 3288:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3289:     my @files;
 3290:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3291:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3292:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3293:     	    push(@files,$file_url.$file);
 3294:         }
 3295:     }
 3296:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3297:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3298:     }
 3299:     return (\@files);
 3300: }
 3301: 
 3302: # ----------- Provides number of tries since last reset.
 3303: sub get_num_tries {
 3304:     my ($record,$last_reset,$part) = @_;
 3305:     my $timestamp = '';
 3306:     my $num_tries = 0;
 3307:     if ($$record{'version'}) {
 3308:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3309:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3310:                 $timestamp = $$record{$version.':timestamp'};
 3311:                 if ($timestamp > $last_reset) {
 3312:                     $num_tries ++;
 3313:                 } else {
 3314:                     last;
 3315:                 }
 3316:             }
 3317:         }
 3318:     }
 3319:     return $num_tries;
 3320: }
 3321: 
 3322: # ----------- Determine decrements required in aggregate totals 
 3323: sub decrement_aggs {
 3324:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3325:     my %decrement = (
 3326:                         attempts => 0,
 3327:                         users => 0,
 3328:                         correct => 0
 3329:                     );
 3330:     $decrement{'attempts'} = $aggtries;
 3331:     if ($solvedstatus =~ /^correct/) {
 3332:         $decrement{'correct'} = 1;
 3333:     }
 3334:     if ($aggtries == $totaltries) {
 3335:         $decrement{'users'} = 1;
 3336:     }
 3337:     foreach my $type (keys(%decrement)) {
 3338:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3339:     }
 3340:     return;
 3341: }
 3342: 
 3343: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3344: sub get_last_resets {
 3345:     my ($symb,$courseid,$partids) =@_;
 3346:     my %last_resets;
 3347:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3348:     my $cname = $env{'course.'.$courseid.'.num'};
 3349:     my @keys;
 3350:     foreach my $part (@{$partids}) {
 3351: 	push(@keys,"$symb\0$part\0resettime");
 3352:     }
 3353:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3354: 				     $cdom,$cname);
 3355:     foreach my $part (@{$partids}) {
 3356: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3357:     }
 3358:     return %last_resets;
 3359: }
 3360: 
 3361: # ----------- Handles creating versions for portfolio files as answers
 3362: sub version_portfiles {
 3363:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3364:     my $version_parts = join('|',@$v_flag);
 3365:     my @returned_keys;
 3366:     my $parts = join('|', @$parts_graded);
 3367:     my $portfolio_root = '/userfiles/portfolio';
 3368:     foreach my $key (keys(%$record)) {
 3369:         my $new_portfiles;
 3370:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3371:             my @versioned_portfiles;
 3372:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3373:             foreach my $file (@portfiles) {
 3374:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3375:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3376: 		my ($answer_name,$answer_ver,$answer_ext) =
 3377: 		    &file_name_version_ext($answer_file);
 3378:                 my $getpropath = 1;
 3379:                 my ($dir_list,$listerror) =
 3380:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3381:                                              $stu_name,$getpropath);
 3382:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3383:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3384:                 if ($new_answer ne 'problem getting file') {
 3385:                     push(@versioned_portfiles, $directory.$new_answer);
 3386:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3387:                         [$directory.$new_answer],
 3388:                         [$symb,$env{'request.course.id'},'graded']);
 3389:                 }
 3390:             }
 3391:             $$record{$key} = join(',',@versioned_portfiles);
 3392:             push(@returned_keys,$key);
 3393:         }
 3394:     } 
 3395:     return (@returned_keys);   
 3396: }
 3397: 
 3398: sub get_next_version {
 3399:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3400:     my $version;
 3401:     if (ref($dir_list) eq 'ARRAY') {
 3402:         foreach my $row (@{$dir_list}) {
 3403:             my ($file) = split(/\&/,$row,2);
 3404:             my ($file_name,$file_version,$file_ext) =
 3405: 	        &file_name_version_ext($file);
 3406:             if (($file_name eq $answer_name) && 
 3407: 	        ($file_ext eq $answer_ext)) {
 3408:                 # gets here if filename and extension match, 
 3409:                 # regardless of version
 3410:                 if ($file_version ne '') {
 3411:                     # a versioned file is found  so save it for later
 3412:                     if ($file_version > $version) {
 3413: 		        $version = $file_version;
 3414:                     }
 3415: 	        }
 3416:             }
 3417:         }
 3418:     }
 3419:     $version ++;
 3420:     return($version);
 3421: }
 3422: 
 3423: sub version_selected_portfile {
 3424:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3425:     my ($answer_name,$answer_ver,$answer_ext) =
 3426:         &file_name_version_ext($file_name);
 3427:     my $new_answer;
 3428:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3429:     if($env{'form.copy'} eq '-1') {
 3430:         $new_answer = 'problem getting file';
 3431:     } else {
 3432:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3433:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3434:                             $stu_name,$domain,'copy',
 3435: 		        '/portfolio'.$directory.$new_answer);
 3436:     }    
 3437:     return ($new_answer);
 3438: }
 3439: 
 3440: sub file_name_version_ext {
 3441:     my ($file)=@_;
 3442:     my @file_parts = split(/\./, $file);
 3443:     my ($name,$version,$ext);
 3444:     if (@file_parts > 1) {
 3445: 	$ext=pop(@file_parts);
 3446: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3447: 	    $version=pop(@file_parts);
 3448: 	}
 3449: 	$name=join('.',@file_parts);
 3450:     } else {
 3451: 	$name=join('.',@file_parts);
 3452:     }
 3453:     return($name,$version,$ext);
 3454: }
 3455: 
 3456: #--------------------------------------------------------------------------------------
 3457: #
 3458: #-------------------------- Next few routines handles grading by section or whole class
 3459: #
 3460: #--- Javascript to handle grading by section or whole class
 3461: sub viewgrades_js {
 3462:     my ($request) = shift;
 3463: 
 3464:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3465:     $request->print(<<VIEWJAVASCRIPT);
 3466: <script type="text/javascript" language="javascript">
 3467:    function writePoint(partid,weight,point) {
 3468: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3469: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3470: 	if (point == "textval") {
 3471: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3472: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3473: 		alert("$alertmsg"+parseFloat(point));
 3474: 		var resetbox = false;
 3475: 		for (var i=0; i<radioButton.length; i++) {
 3476: 		    if (radioButton[i].checked) {
 3477: 			textbox.value = i;
 3478: 			resetbox = true;
 3479: 		    }
 3480: 		}
 3481: 		if (!resetbox) {
 3482: 		    textbox.value = "";
 3483: 		}
 3484: 		return;
 3485: 	    }
 3486: 	    if (parseFloat(point) > parseFloat(weight)) {
 3487: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3488: 				   ") greater than the weight for the part. Accept?");
 3489: 		if (resp == false) {
 3490: 		    textbox.value = "";
 3491: 		    return;
 3492: 		}
 3493: 	    }
 3494: 	    for (var i=0; i<radioButton.length; i++) {
 3495: 		radioButton[i].checked=false;
 3496: 		if (parseFloat(point) == i) {
 3497: 		    radioButton[i].checked=true;
 3498: 		}
 3499: 	    }
 3500: 
 3501: 	} else {
 3502: 	    textbox.value = parseFloat(point);
 3503: 	}
 3504: 	for (i=0;i<document.classgrade.total.value;i++) {
 3505: 	    var user = document.classgrade["ctr"+i].value;
 3506: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3507: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3508: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3509: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3510: 	    if (saveval != "correct") {
 3511: 		scorename.value = point;
 3512: 		if (selname[0].selected != true) {
 3513: 		    selname[0].selected = true;
 3514: 		}
 3515: 	    }
 3516: 	}
 3517: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3518:     }
 3519: 
 3520:     function writeRadText(partid,weight) {
 3521: 	var selval   = document.classgrade["SELVAL_"+partid];
 3522: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3523:         var override = document.classgrade["FORCE_"+partid].checked;
 3524: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3525: 	if (selval[1].selected || selval[2].selected) {
 3526: 	    for (var i=0; i<radioButton.length; i++) {
 3527: 		radioButton[i].checked=false;
 3528: 
 3529: 	    }
 3530: 	    textbox.value = "";
 3531: 
 3532: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3533: 		var user = document.classgrade["ctr"+i].value;
 3534: 		user = user.replace(new RegExp(':', 'g'),"_");
 3535: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3536: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3537: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3538: 		if ((saveval != "correct") || override) {
 3539: 		    scorename.value = "";
 3540: 		    if (selval[1].selected) {
 3541: 			selname[1].selected = true;
 3542: 		    } else {
 3543: 			selname[2].selected = true;
 3544: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3545: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3546: 		    }
 3547: 		}
 3548: 	    }
 3549: 	} else {
 3550: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3551: 		var user = document.classgrade["ctr"+i].value;
 3552: 		user = user.replace(new RegExp(':', 'g'),"_");
 3553: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3554: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3555: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3556: 		if ((saveval != "correct") || override) {
 3557: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3558: 		    selname[0].selected = true;
 3559: 		}
 3560: 	    }
 3561: 	}	    
 3562:     }
 3563: 
 3564:     function changeSelect(partid,user) {
 3565: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3566: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3567: 	var point  = textbox.value;
 3568: 	var weight = document.classgrade["weight_"+partid].value;
 3569: 
 3570: 	if (isNaN(point) || parseFloat(point) < 0) {
 3571: 	    alert("$alertmsg"+parseFloat(point));
 3572: 	    textbox.value = "";
 3573: 	    return;
 3574: 	}
 3575: 	if (parseFloat(point) > parseFloat(weight)) {
 3576: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3577: 			       ") greater than the weight of the part. Accept?");
 3578: 	    if (resp == false) {
 3579: 		textbox.value = "";
 3580: 		return;
 3581: 	    }
 3582: 	}
 3583: 	selval[0].selected = true;
 3584:     }
 3585: 
 3586:     function changeOneScore(partid,user) {
 3587: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3588: 	if (selval[1].selected || selval[2].selected) {
 3589: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3590: 	    if (selval[2].selected) {
 3591: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3592: 	    }
 3593:         }
 3594:     }
 3595: 
 3596:     function resetEntry(numpart) {
 3597: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3598: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3599: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3600: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3601: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3602: 	    for (var i=0; i<radioButton.length; i++) {
 3603: 		radioButton[i].checked=false;
 3604: 
 3605: 	    }
 3606: 	    textbox.value = "";
 3607: 	    selval[0].selected = true;
 3608: 
 3609: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3610: 		var user = document.classgrade["ctr"+i].value;
 3611: 		user = user.replace(new RegExp(':', 'g'),"_");
 3612: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3613: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3614: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3615: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3616: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3617: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3618: 		if (saveselval == "excused") {
 3619: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3620: 		} else {
 3621: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3622: 		}
 3623: 	    }
 3624: 	}
 3625:     }
 3626: 
 3627: </script>
 3628: VIEWJAVASCRIPT
 3629: }
 3630: 
 3631: #--- show scores for a section or whole class w/ option to change/update a score
 3632: sub viewgrades {
 3633:     my ($request) = shift;
 3634:     &viewgrades_js($request);
 3635: 
 3636:     my ($symb) = &get_symb($request);
 3637:     #need to make sure we have the correct data for later EXT calls, 
 3638:     #thus invalidate the cache
 3639:     &Apache::lonnet::devalidatecourseresdata(
 3640:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3641:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3642:     &Apache::lonnet::clear_EXT_cache_status();
 3643: 
 3644:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3645:     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3646: 
 3647:     #view individual student submission form - called using Javascript viewOneStudent
 3648:     $result.=&jscriptNform($symb);
 3649: 
 3650:     #beginning of class grading form
 3651:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3652:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3653: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3654: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3655: 	&build_section_inputs().
 3656: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3657: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3658: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3659: 
 3660:     my ($common_header,$specific_header);
 3661:     if ($env{'form.section'} eq 'all') {
 3662: 	$common_header = &mt('Assign Common Grade to Class');
 3663:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3664:     } elsif ($env{'form.section'} eq 'none') {
 3665:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3666: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3667:     } else {
 3668:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3669:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3670: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3671:     }
 3672:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3673:     #radio buttons/text box for assigning points for a section or class.
 3674:     #handles different parts of a problem
 3675:     my $res_error;
 3676:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3677:     if ($res_error) {
 3678:         return &navmap_errormsg();
 3679:     }
 3680:     my %weight = ();
 3681:     my $ctsparts = 0;
 3682:     my %seen = ();
 3683:     my @part_response_id = &flatten_responseType($responseType);
 3684:     foreach my $part_response_id (@part_response_id) {
 3685:     	my ($partid,$respid) = @{ $part_response_id };
 3686: 	my $part_resp = join('_',@{ $part_response_id });
 3687: 	next if $seen{$partid};
 3688: 	$seen{$partid}++;
 3689: 	my $handgrade=$$handgrade{$part_resp};
 3690: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3691: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3692: 
 3693: 	my $display_part=&get_display_part($partid,$symb);
 3694: 	my $radio.='<table border="0"><tr>';  
 3695: 	my $ctr = 0;
 3696: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3697: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3698: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3699: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3700: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3701: 	    $ctr++;
 3702: 	}
 3703: 	$radio.='</tr></table>';
 3704: 	my $line = '<input type="text" name="TEXTVAL_'.
 3705: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3706: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3707: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3708: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3709:                 '<select name="SELVAL_'.$partid.'" '.
 3710: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 3711: 		$weight{$partid}.')"> '.
 3712: 	    '<option selected="selected"> </option>'.
 3713: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3714: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3715: 	    '</select></td>'.
 3716:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3717: 	$line.='<input type="hidden" name="partid_'.
 3718: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3719: 	$line.='<input type="hidden" name="weight_'.
 3720: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3721: 
 3722: 	$result.=
 3723: 	    &Apache::loncommon::start_data_table_row()."\n".
 3724: 	    '<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>'.
 3725: 	    &Apache::loncommon::end_data_table_row()."\n";
 3726: 	$ctsparts++;
 3727:     }
 3728:     $result.=&Apache::loncommon::end_data_table()."\n".
 3729: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3730:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3731: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3732: 
 3733:     #table listing all the students in a section/class
 3734:     #header of table
 3735:     $result.= '<h3>'.$specific_header.'</h3>'.
 3736:               &Apache::loncommon::start_data_table().
 3737: 	      &Apache::loncommon::start_data_table_header_row().
 3738: 	      '<th>'.&mt('No.').'</th>'.
 3739: 	      '<th>'.&nameUserString('header')."</th>\n";
 3740:     my $partserror;
 3741:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3742:     if ($partserror) {
 3743:         return &navmap_errormsg();
 3744:     }
 3745:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3746:     my @partids = ();
 3747:     foreach my $part (@parts) {
 3748: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3749:         my $narrowtext = &mt('Tries');
 3750: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3751: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3752: 	my ($partid) = &split_part_type($part);
 3753:         push(@partids,$partid);
 3754: 	my $display_part=&get_display_part($partid,$symb);
 3755: 	if ($display =~ /^Partial Credit Factor/) {
 3756: 	    $result.='<th>'.
 3757:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3758:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3759: 	    next;
 3760: 	    
 3761: 	} else {
 3762: 	    if ($display =~ /Problem Status/) {
 3763: 		my $grade_status_mt = &mt('Grade Status');
 3764: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3765: 	    }
 3766: 	    my $part_mt = &mt('Part:');
 3767: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3768: 	}
 3769: 
 3770: 	$result.='<th>'.$display.'</th>'."\n";
 3771:     }
 3772:     $result.=&Apache::loncommon::end_data_table_header_row();
 3773: 
 3774:     my %last_resets = 
 3775: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3776: 
 3777:     #get info for each student
 3778:     #list all the students - with points and grade status
 3779:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3780:     my $ctr = 0;
 3781:     foreach (sort 
 3782: 	     {
 3783: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3784: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3785: 		 }
 3786: 		 return $a cmp $b;
 3787: 	     } (keys(%$fullname))) {
 3788: 	$ctr++;
 3789: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3790: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3791:     }
 3792:     $result.=&Apache::loncommon::end_data_table();
 3793:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3794:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3795: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3796:     if (scalar(%$fullname) eq 0) {
 3797: 	my $colspan=3+scalar(@parts);
 3798: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3799:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3800: 	$result='<span class="LC_warning">'.
 3801: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3802: 	        $section_display, $stu_status).
 3803: 	    '</span>';
 3804:     }
 3805:     $result.=&show_grading_menu_form($symb);
 3806:     return $result;
 3807: }
 3808: 
 3809: #--- call by previous routine to display each student
 3810: sub viewstudentgrade {
 3811:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3812:     my ($uname,$udom) = split(/:/,$student);
 3813:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3814:     my %aggregates = (); 
 3815:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3816: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3817: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3818: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3819: 	'\');" target="_self">'.$fullname.'</a> '.
 3820: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3821:     $student=~s/:/_/; # colon doen't work in javascript for names
 3822:     foreach my $apart (@$parts) {
 3823: 	my ($part,$type) = &split_part_type($apart);
 3824: 	my $score=$record{"resource.$part.$type"};
 3825:         $result.='<td align="center">';
 3826:         my ($aggtries,$totaltries);
 3827:         unless (exists($aggregates{$part})) {
 3828: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3829: 
 3830: 	    $aggtries = $totaltries;
 3831:             if ($$last_resets{$part}) {  
 3832:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3833: 					   $part);
 3834:             }
 3835:             $result.='<input type="hidden" name="'.
 3836:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3837:             $result.='<input type="hidden" name="'.
 3838:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3839:             $aggregates{$part} = 1;
 3840:         }
 3841: 	if ($type eq 'awarded') {
 3842: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3843: 	    $result.='<input type="hidden" name="'.
 3844: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3845: 	    $result.='<input type="text" name="'.
 3846: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3847:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3848: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3849: 	} elsif ($type eq 'solved') {
 3850: 	    my ($status,$foo)=split(/_/,$score,2);
 3851: 	    $status = 'nothing' if ($status eq '');
 3852: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3853: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3854: 	    $result.='&nbsp;<select name="'.
 3855: 		'GD_'.$student.'_'.$part.'_solved" '.
 3856:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3857: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3858: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3859: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3860: 	    $result.="</select>&nbsp;</td>\n";
 3861: 	} else {
 3862: 	    $result.='<input type="hidden" name="'.
 3863: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3864: 		    "\n";
 3865: 	    $result.='<input type="text" name="'.
 3866: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3867: 		'value="'.$score.'" size="4" /></td>'."\n";
 3868: 	}
 3869:     }
 3870:     $result.=&Apache::loncommon::end_data_table_row();
 3871:     return $result;
 3872: }
 3873: 
 3874: #--- change scores for all the students in a section/class
 3875: #    record does not get update if unchanged
 3876: sub editgrades {
 3877:     my ($request) = @_;
 3878: 
 3879:     my ($symb)=&get_symb($request);
 3880:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3881:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3882:     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3883:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 3884: 
 3885:     my $result= &Apache::loncommon::start_data_table().
 3886: 	&Apache::loncommon::start_data_table_header_row().
 3887: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3888: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3889:     my %scoreptr = (
 3890: 		    'correct'  =>'correct_by_override',
 3891: 		    'incorrect'=>'incorrect_by_override',
 3892: 		    'excused'  =>'excused',
 3893: 		    'ungraded' =>'ungraded_attempted',
 3894:                     'credited' =>'credit_attempted',
 3895: 		    'nothing'  => '',
 3896: 		    );
 3897:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3898: 
 3899:     my (@partid);
 3900:     my %weight = ();
 3901:     my %columns = ();
 3902:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3903: 
 3904:     my $partserror;
 3905:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3906:     if ($partserror) {
 3907:         return &navmap_errormsg();
 3908:     }
 3909:     my $header;
 3910:     while ($ctr < $env{'form.totalparts'}) {
 3911: 	my $partid = $env{'form.partid_'.$ctr};
 3912: 	push(@partid,$partid);
 3913: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3914: 	$ctr++;
 3915:     }
 3916:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3917:     foreach my $partid (@partid) {
 3918: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3919: 	    '<th align="center">'.&mt('New Score').'</th>';
 3920: 	$columns{$partid}=2;
 3921: 	foreach my $stores (@parts) {
 3922: 	    my ($part,$type) = &split_part_type($stores);
 3923: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3924: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3925: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3926: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3927:             my $narrowtext = &mt('Tries');
 3928: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3929: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3930: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3931: 	    $columns{$partid}+=2;
 3932: 	}
 3933:     }
 3934:     foreach my $partid (@partid) {
 3935: 	my $display_part=&get_display_part($partid,$symb);
 3936: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3937: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3938: 	    '</th>';
 3939: 
 3940:     }
 3941:     $result .= &Apache::loncommon::end_data_table_header_row().
 3942: 	&Apache::loncommon::start_data_table_header_row().
 3943: 	$header.
 3944: 	&Apache::loncommon::end_data_table_header_row();
 3945:     my @noupdate;
 3946:     my ($updateCtr,$noupdateCtr) = (1,1);
 3947:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3948: 	my $line;
 3949: 	my $user = $env{'form.ctr'.$i};
 3950: 	my ($uname,$udom)=split(/:/,$user);
 3951: 	my %newrecord;
 3952: 	my $updateflag = 0;
 3953: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3954: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3955: 	if (!&canmodify($usec)) {
 3956: 	    my $numcols=scalar(@partid)*4+2;
 3957: 	    push(@noupdate,
 3958: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3959: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3960: 	    next;
 3961: 	}
 3962:         my %aggregate = ();
 3963:         my $aggregateflag = 0;
 3964: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3965: 	foreach (@partid) {
 3966: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3967: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3968: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3969: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3970: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3971: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3972: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3973: 	    my $score;
 3974: 	    if ($partial eq '') {
 3975: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3976: 	    } elsif ($partial > 0) {
 3977: 		$score = 'correct_by_override';
 3978: 	    } elsif ($partial == 0) {
 3979: 		$score = 'incorrect_by_override';
 3980: 	    }
 3981: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3982: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3983: 
 3984: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3985: 		"$env{'user.name'}:$env{'user.domain'}";
 3986: 	    if ($dropMenu eq 'reset status' &&
 3987: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3988: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3989: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3990: 		$newrecord{'resource.'.$_.'.award'} = '';
 3991: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3992: 		$updateflag = 1;
 3993:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3994:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3995:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3996:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3997:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3998:                     $aggregateflag = 1;
 3999:                 }
 4000: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4001: 		$updateflag = 1;
 4002: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4003: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4004: 		$rec_update++;
 4005: 	    }
 4006: 
 4007: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4008: 		'<td align="center">'.$awarded.
 4009: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4010: 
 4011: 
 4012: 	    my $partid=$_;
 4013: 	    foreach my $stores (@parts) {
 4014: 		my ($part,$type) = &split_part_type($stores);
 4015: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4016: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4017: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4018: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4019: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4020: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4021: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4022: 		    $updateflag=1;
 4023: 		}
 4024: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4025: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4026: 	    }
 4027: 	}
 4028: 	$line.="\n";
 4029: 
 4030: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4031: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4032: 
 4033: 	if ($updateflag) {
 4034: 	    $count++;
 4035: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4036: 				    $udom,$uname);
 4037: 
 4038: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4039: 					      $cnum,$udom,$uname)) {
 4040: 		# need to figure out if should be in queue.
 4041: 		my %record =  
 4042: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4043: 					     $udom,$uname);
 4044: 		my $all_graded = 1;
 4045: 		my $none_graded = 1;
 4046: 		foreach my $part (@parts) {
 4047: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4048: 			$all_graded = 0;
 4049: 		    } else {
 4050: 			$none_graded = 0;
 4051: 		    }
 4052: 		}
 4053: 
 4054: 		if ($all_graded || $none_graded) {
 4055: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4056: 							   $symb,$cdom,$cnum,
 4057: 							   $udom,$uname);
 4058: 		}
 4059: 	    }
 4060: 
 4061: 	    $result.=&Apache::loncommon::start_data_table_row().
 4062: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4063: 		&Apache::loncommon::end_data_table_row();
 4064: 	    $updateCtr++;
 4065: 	} else {
 4066: 	    push(@noupdate,
 4067: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4068: 	    $noupdateCtr++;
 4069: 	}
 4070:         if ($aggregateflag) {
 4071:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4072: 				  $cdom,$cnum);
 4073:         }
 4074:     }
 4075:     if (@noupdate) {
 4076: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4077: 	my $numcols=scalar(@partid)*4+2;
 4078: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4079: 	    '<td align="center" colspan="'.$numcols.'">'.
 4080: 	    &mt('No Changes Occurred For the Students Below').
 4081: 	    '</td>'.
 4082: 	    &Apache::loncommon::end_data_table_row();
 4083: 	foreach my $line (@noupdate) {
 4084: 	    $result.=
 4085: 		&Apache::loncommon::start_data_table_row().
 4086: 		$line.
 4087: 		&Apache::loncommon::end_data_table_row();
 4088: 	}
 4089:     }
 4090:     $result .= &Apache::loncommon::end_data_table().
 4091: 	&show_grading_menu_form($symb);
 4092:     my $msg = '<p><b>'.
 4093: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4094: 	    $rec_update,$count).'</b><br />'.
 4095: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4096: 	'</b></p>';
 4097:     return $title.$msg.$result;
 4098: }
 4099: 
 4100: sub split_part_type {
 4101:     my ($partstr) = @_;
 4102:     my ($temp,@allparts)=split(/_/,$partstr);
 4103:     my $type=pop(@allparts);
 4104:     my $part=join('_',@allparts);
 4105:     return ($part,$type);
 4106: }
 4107: 
 4108: #------------- end of section for handling grading by section/class ---------
 4109: #
 4110: #----------------------------------------------------------------------------
 4111: 
 4112: 
 4113: #----------------------------------------------------------------------------
 4114: #
 4115: #-------------------------- Next few routines handles grading by csv upload
 4116: #
 4117: #--- Javascript to handle csv upload
 4118: sub csvupload_javascript_reverse_associate {
 4119:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4120:     my $error2=&mt('You need to specify at least one grading field');
 4121:   return(<<ENDPICK);
 4122:   function verify(vf) {
 4123:     var foundsomething=0;
 4124:     var founduname=0;
 4125:     var foundID=0;
 4126:     for (i=0;i<=vf.nfields.value;i++) {
 4127:       tw=eval('vf.f'+i+'.selectedIndex');
 4128:       if (i==0 && tw!=0) { foundID=1; }
 4129:       if (i==1 && tw!=0) { founduname=1; }
 4130:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4131:     }
 4132:     if (founduname==0 && foundID==0) {
 4133: 	alert('$error1');
 4134: 	return;
 4135:     }
 4136:     if (foundsomething==0) {
 4137: 	alert('$error2');
 4138: 	return;
 4139:     }
 4140:     vf.submit();
 4141:   }
 4142:   function flip(vf,tf) {
 4143:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4144:     var i;
 4145:     for (i=0;i<=vf.nfields.value;i++) {
 4146:       //can not pick the same destination field for both name and domain
 4147:       if (((i ==0)||(i ==1)) && 
 4148:           ((tf==0)||(tf==1)) && 
 4149:           (i!=tf) &&
 4150:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4151:         eval('vf.f'+i+'.selectedIndex=0;')
 4152:       }
 4153:     }
 4154:   }
 4155: ENDPICK
 4156: }
 4157: 
 4158: sub csvupload_javascript_forward_associate {
 4159:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4160:     my $error2=&mt('You need to specify at least one grading field');
 4161:   return(<<ENDPICK);
 4162:   function verify(vf) {
 4163:     var foundsomething=0;
 4164:     var founduname=0;
 4165:     var foundID=0;
 4166:     for (i=0;i<=vf.nfields.value;i++) {
 4167:       tw=eval('vf.f'+i+'.selectedIndex');
 4168:       if (tw==1) { foundID=1; }
 4169:       if (tw==2) { founduname=1; }
 4170:       if (tw>3) { foundsomething=1; }
 4171:     }
 4172:     if (founduname==0 && foundID==0) {
 4173: 	alert('$error1');
 4174: 	return;
 4175:     }
 4176:     if (foundsomething==0) {
 4177: 	alert('$error2');
 4178: 	return;
 4179:     }
 4180:     vf.submit();
 4181:   }
 4182:   function flip(vf,tf) {
 4183:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4184:     var i;
 4185:     //can not pick the same destination field twice
 4186:     for (i=0;i<=vf.nfields.value;i++) {
 4187:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4188:         eval('vf.f'+i+'.selectedIndex=0;')
 4189:       }
 4190:     }
 4191:   }
 4192: ENDPICK
 4193: }
 4194: 
 4195: sub csvuploadmap_header {
 4196:     my ($request,$symb,$datatoken,$distotal)= @_;
 4197:     my $javascript;
 4198:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4199: 	$javascript=&csvupload_javascript_reverse_associate();
 4200:     } else {
 4201: 	$javascript=&csvupload_javascript_forward_associate();
 4202:     }
 4203: 
 4204:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4205:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4206:     my $ignore=&mt('Ignore First Line');
 4207:     $symb = &Apache::lonenc::check_encrypt($symb);
 4208:     $request->print(<<ENDPICK);
 4209: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4210: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4211: $result
 4212: <hr />
 4213: <h3>Identify fields</h3>
 4214: Total number of records found in file: $distotal <hr />
 4215: Enter as many fields as you can. The system will inform you and bring you back
 4216: to this page if the data selected is insufficient to run your class.<hr />
 4217: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4218: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4219: <input type="hidden" name="associate"  value="" />
 4220: <input type="hidden" name="phase"      value="three" />
 4221: <input type="hidden" name="datatoken"  value="$datatoken" />
 4222: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4223: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4224: <input type="hidden" name="upfile_associate" 
 4225:                                        value="$env{'form.upfile_associate'}" />
 4226: <input type="hidden" name="symb"       value="$symb" />
 4227: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4228: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4229: <input type="hidden" name="command"    value="csvuploadoptions" />
 4230: <hr />
 4231: <script type="text/javascript" language="Javascript">
 4232: $javascript
 4233: </script>
 4234: ENDPICK
 4235:     return '';
 4236: 
 4237: }
 4238: 
 4239: sub csvupload_fields {
 4240:     my ($symb,$errorref) = @_;
 4241:     my (@parts) = &getpartlist($symb,$errorref);
 4242:     if (ref($errorref)) {
 4243:         if ($$errorref) {
 4244:             return;
 4245:         }
 4246:     }
 4247: 
 4248:     my @fields=(['ID','Student/Employee ID'],
 4249: 		['username','Student Username'],
 4250: 		['domain','Student Domain']);
 4251:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4252:     foreach my $part (sort(@parts)) {
 4253: 	my @datum;
 4254: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4255: 	my $name=$part;
 4256: 	if  (!$display) { $display = $name; }
 4257: 	@datum=($name,$display);
 4258: 	if ($name=~/^stores_(.*)_awarded/) {
 4259: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4260: 	}
 4261: 	push(@fields,\@datum);
 4262:     }
 4263:     return (@fields);
 4264: }
 4265: 
 4266: sub csvuploadmap_footer {
 4267:     my ($request,$i,$keyfields) =@_;
 4268:     my $buttontext = &mt('Assign Grades');
 4269:     $request->print(<<ENDPICK);
 4270: </table>
 4271: <input type="hidden" name="nfields" value="$i" />
 4272: <input type="hidden" name="keyfields" value="$keyfields" />
 4273: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4274: </form>
 4275: ENDPICK
 4276: }
 4277: 
 4278: sub checkforfile_js {
 4279:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4280:     my $result =<<CSVFORMJS;
 4281: <script type="text/javascript" language="javascript">
 4282:     function checkUpload(formname) {
 4283: 	if (formname.upfile.value == "") {
 4284: 	    alert("$alertmsg");
 4285: 	    return false;
 4286: 	}
 4287: 	formname.submit();
 4288:     }
 4289:     </script>
 4290: CSVFORMJS
 4291:     return $result;
 4292: }
 4293: 
 4294: sub upcsvScores_form {
 4295:     my ($request) = shift;
 4296:     my ($symb)=&get_symb($request);
 4297:     if (!$symb) {return '';}
 4298:     my $result=&checkforfile_js();
 4299:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4300:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4301:     $result.=$table;
 4302:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4303:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4304:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4305: 	'</b></td></tr>'."\n";
 4306:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4307:     my $upload=&mt("Upload Scores");
 4308:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4309:     my $ignore=&mt('Ignore First Line');
 4310:     $symb = &Apache::lonenc::check_encrypt($symb);
 4311:     $result.=<<ENDUPFORM;
 4312: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4313: <input type="hidden" name="symb" value="$symb" />
 4314: <input type="hidden" name="command" value="csvuploadmap" />
 4315: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4316: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4317: $upfile_select
 4318: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4319: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4320: </form>
 4321: ENDUPFORM
 4322:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4323:                            &mt("How do I create a CSV file from a spreadsheet"))
 4324:     .'</td></tr></table>'."\n";
 4325:     $result.='</td></tr></table><br /><br />'."\n";
 4326:     $result.=&show_grading_menu_form($symb);
 4327:     return $result;
 4328: }
 4329: 
 4330: 
 4331: sub csvuploadmap {
 4332:     my ($request)= @_;
 4333:     my ($symb)=&get_symb($request);
 4334:     if (!$symb) {return '';}
 4335: 
 4336:     my $datatoken;
 4337:     if (!$env{'form.datatoken'}) {
 4338: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4339:     } else {
 4340: 	$datatoken=$env{'form.datatoken'};
 4341: 	&Apache::loncommon::load_tmp_file($request);
 4342:     }
 4343:     my @records=&Apache::loncommon::upfile_record_sep();
 4344:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4345:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4346:     my ($i,$keyfields);
 4347:     if (@records) {
 4348:         my $fieldserror;
 4349: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4350:         if ($fieldserror) {
 4351:             $request->print(&navmap_errormsg());
 4352:             return;
 4353:         }
 4354: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4355: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4356: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4357: 							  \@fields);
 4358: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4359: 	    chop($keyfields);
 4360: 	} else {
 4361: 	    unshift(@fields,['none','']);
 4362: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4363: 							    \@fields);
 4364:             foreach my $rec (@records) {
 4365:                 my %temp = &Apache::loncommon::record_sep($rec);
 4366:                 if (%temp) {
 4367:                     $keyfields=join(',',sort(keys(%temp)));
 4368:                     last;
 4369:                 }
 4370:             }
 4371: 	}
 4372:     }
 4373:     &csvuploadmap_footer($request,$i,$keyfields);
 4374:     $request->print(&show_grading_menu_form($symb));
 4375: 
 4376:     return '';
 4377: }
 4378: 
 4379: sub csvuploadoptions {
 4380:     my ($request)= @_;
 4381:     my ($symb)=&get_symb($request);
 4382:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4383:     my $ignore=&mt('Ignore First Line');
 4384:     $request->print(<<ENDPICK);
 4385: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4386: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4387: <input type="hidden" name="command"    value="csvuploadassign" />
 4388: <!--
 4389: <p>
 4390: <label>
 4391:    <input type="checkbox" name="show_full_results" />
 4392:    Show a table of all changes
 4393: </label>
 4394: </p>
 4395: -->
 4396: <p>
 4397: <label>
 4398:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4399:    Overwrite any existing score
 4400: </label>
 4401: </p>
 4402: ENDPICK
 4403:     my %fields=&get_fields();
 4404:     if (!defined($fields{'domain'})) {
 4405: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4406: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4407:     }
 4408:     foreach my $key (sort(keys(%env))) {
 4409: 	if ($key !~ /^form\.(.*)$/) { next; }
 4410: 	my $cleankey=$1;
 4411: 	if ($cleankey eq 'command') { next; }
 4412: 	$request->print('<input type="hidden" name="'.$cleankey.
 4413: 			'"  value="'.$env{$key}.'" />'."\n");
 4414:     }
 4415:     # FIXME do a check for any duplicated user ids...
 4416:     # FIXME do a check for any invalid user ids?...
 4417:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4418: <hr /></form>'."\n");
 4419:     $request->print(&show_grading_menu_form($symb));
 4420:     return '';
 4421: }
 4422: 
 4423: sub get_fields {
 4424:     my %fields;
 4425:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4426:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4427: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4428: 	    if ($env{'form.f'.$i} ne 'none') {
 4429: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4430: 	    }
 4431: 	} else {
 4432: 	    if ($env{'form.f'.$i} ne 'none') {
 4433: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4434: 	    }
 4435: 	}
 4436:     }
 4437:     return %fields;
 4438: }
 4439: 
 4440: sub csvuploadassign {
 4441:     my ($request)= @_;
 4442:     my ($symb)=&get_symb($request);
 4443:     if (!$symb) {return '';}
 4444:     my $error_msg = '';
 4445:     &Apache::loncommon::load_tmp_file($request);
 4446:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4447:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4448:     my %fields=&get_fields();
 4449:     $request->print('<h3>Assigning Grades</h3>');
 4450:     my $courseid=$env{'request.course.id'};
 4451:     my ($classlist) = &getclasslist('all',0);
 4452:     my @notallowed;
 4453:     my @skipped;
 4454:     my @warnings;
 4455:     my $countdone=0;
 4456:     foreach my $grade (@gradedata) {
 4457: 	my %entries=&Apache::loncommon::record_sep($grade);
 4458: 	my $domain;
 4459: 	if ($entries{$fields{'domain'}}) {
 4460: 	    $domain=$entries{$fields{'domain'}};
 4461: 	} else {
 4462: 	    $domain=$env{'form.default_domain'};
 4463: 	}
 4464: 	$domain=~s/\s//g;
 4465: 	my $username=$entries{$fields{'username'}};
 4466: 	$username=~s/\s//g;
 4467: 	if (!$username) {
 4468: 	    my $id=$entries{$fields{'ID'}};
 4469: 	    $id=~s/\s//g;
 4470: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4471: 	    $username=$ids{$id};
 4472: 	}
 4473: 	if (!exists($$classlist{"$username:$domain"})) {
 4474: 	    my $id=$entries{$fields{'ID'}};
 4475: 	    $id=~s/\s//g;
 4476: 	    if ($id) {
 4477: 		push(@skipped,"$id:$domain");
 4478: 	    } else {
 4479: 		push(@skipped,"$username:$domain");
 4480: 	    }
 4481: 	    next;
 4482: 	}
 4483: 	my $usec=$classlist->{"$username:$domain"}[5];
 4484: 	if (!&canmodify($usec)) {
 4485: 	    push(@notallowed,"$username:$domain");
 4486: 	    next;
 4487: 	}
 4488: 	my %points;
 4489: 	my %grades;
 4490: 	foreach my $dest (keys(%fields)) {
 4491: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4492: 		$dest eq 'domain') { next; }
 4493: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4494: 	    if ($dest=~/stores_(.*)_points/) {
 4495: 		my $part=$1;
 4496: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4497: 					      $symb,$domain,$username);
 4498:                 if ($wgt) {
 4499:                     $entries{$fields{$dest}}=~s/\s//g;
 4500:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4501:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4502:                                           : 'correct_by_override';
 4503:                     if ($pcr>1) {
 4504:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4505:                     }
 4506:                     $grades{"resource.$part.awarded"}=$pcr;
 4507:                     $grades{"resource.$part.solved"}=$award;
 4508:                     $points{$part}=1;
 4509:                 } else {
 4510:                     $error_msg = "<br />" .
 4511:                         &mt("Some point values were assigned"
 4512:                             ." for problems with a weight "
 4513:                             ."of zero. These values were "
 4514:                             ."ignored.");
 4515:                 }
 4516: 	    } else {
 4517: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4518: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4519: 		my $store_key=$dest;
 4520: 		$store_key=~s/^stores/resource/;
 4521: 		$store_key=~s/_/\./g;
 4522: 		$grades{$store_key}=$entries{$fields{$dest}};
 4523: 	    }
 4524: 	}
 4525: 	if (! %grades) { 
 4526:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4527:         } else {
 4528: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4529: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4530: 					   $env{'request.course.id'},
 4531: 					   $domain,$username);
 4532: 	   if ($result eq 'ok') {
 4533: 	      $request->print('.');
 4534: # Remove from grading queue
 4535:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4536:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4537:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4538:                                              $domain,$username);
 4539: 	   } else {
 4540: 	      $request->print("<p><span class=\"LC_error\">".
 4541:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4542:                                   "$username:$domain",$result)."</span></p>");
 4543: 	   }
 4544: 	   $request->rflush();
 4545: 	   $countdone++;
 4546:         }
 4547:     }
 4548:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4549:     if (@warnings) {
 4550:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4551:         $request->print(join(', ',@warnings));
 4552:     }
 4553:     if (@skipped) {
 4554: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4555:         $request->print(join(', ',@skipped));
 4556:     }
 4557:     if (@notallowed) {
 4558: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4559: 	$request->print(join(', ',@notallowed));
 4560:     }
 4561:     $request->print("<br />\n");
 4562:     $request->print(&show_grading_menu_form($symb));
 4563:     return $error_msg;
 4564: }
 4565: #------------- end of section for handling csv file upload ---------
 4566: #
 4567: #-------------------------------------------------------------------
 4568: #
 4569: #-------------- Next few routines handle grading by page/sequence
 4570: #
 4571: #--- Select a page/sequence and a student to grade
 4572: sub pickStudentPage {
 4573:     my ($request) = shift;
 4574: 
 4575:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4576:     $request->print(<<LISTJAVASCRIPT);
 4577: <script type="text/javascript" language="javascript">
 4578: 
 4579: function checkPickOne(formname) {
 4580:     if (radioSelection(formname.student) == null) {
 4581: 	alert("$alertmsg");
 4582: 	return;
 4583:     }
 4584:     ptr = pullDownSelection(formname.selectpage);
 4585:     formname.page.value = formname["page"+ptr].value;
 4586:     formname.title.value = formname["title"+ptr].value;
 4587:     formname.submit();
 4588: }
 4589: 
 4590: </script>
 4591: LISTJAVASCRIPT
 4592:     &commonJSfunctions($request);
 4593:     my ($symb) = &get_symb($request);
 4594:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4595:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4596:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4597: 
 4598:     my $result='<h3><span class="LC_info">&nbsp;'.
 4599: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4600: 
 4601:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4602:     my $map_error;
 4603:     my ($titles,$symbx) = &getSymbMap($map_error);
 4604:     if ($map_error) {
 4605:         $request->print(&navmap_errormsg());
 4606:         return; 
 4607:     }
 4608:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4609: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4610: #    my $type=($curpage =~ /\.(page|sequence)/);
 4611:     my $select = '<select name="selectpage">'."\n";
 4612:     my $ctr=0;
 4613:     foreach (@$titles) {
 4614: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4615: 	$select.='<option value="'.$ctr.'" '.
 4616: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4617: 	    '>'.$showtitle.'</option>'."\n";
 4618: 	$ctr++;
 4619:     }
 4620:     $select.= '</select>';
 4621:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4622: 
 4623:     $ctr=0;
 4624:     foreach (@$titles) {
 4625: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4626: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4627: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4628: 	$ctr++;
 4629:     }
 4630:     $result.='<input type="hidden" name="page" />'."\n".
 4631: 	'<input type="hidden" name="title" />'."\n";
 4632: 
 4633:     my $options =
 4634: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4635: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4636:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4637: 
 4638:     $options =
 4639: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4640: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4641: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4642:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4643:     
 4644:     $result.=&build_section_inputs();
 4645:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4646:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4647: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4648: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4649: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4650: 
 4651:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4652: 
 4653:     $result.='&nbsp;<input type="button" '.
 4654:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4655: 
 4656:     $request->print($result);
 4657: 
 4658:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4659: 	&Apache::loncommon::start_data_table().
 4660: 	&Apache::loncommon::start_data_table_header_row().
 4661: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4662: 	'<th>'.&nameUserString('header').'</th>'.
 4663: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4664: 	'<th>'.&nameUserString('header').'</th>'.
 4665: 	&Apache::loncommon::end_data_table_header_row();
 4666:  
 4667:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4668:     my $ptr = 1;
 4669:     foreach my $student (sort 
 4670: 			 {
 4671: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4672: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4673: 			     }
 4674: 			     return $a cmp $b;
 4675: 			 } (keys(%$fullname))) {
 4676: 	my ($uname,$udom) = split(/:/,$student);
 4677: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4678:                                   : '</td>');
 4679: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4680: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4681: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4682: 	$studentTable.=
 4683: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4684:                          : '');
 4685: 	$ptr++;
 4686:     }
 4687:     if ($ptr%2 == 0) {
 4688: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4689: 	    &Apache::loncommon::end_data_table_row();
 4690:     }
 4691:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4692:     $studentTable.='<input type="button" '.
 4693:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4694: 
 4695:     $studentTable.=&show_grading_menu_form($symb);
 4696:     $request->print($studentTable);
 4697: 
 4698:     return '';
 4699: }
 4700: 
 4701: sub getSymbMap {
 4702:     my ($map_error) = @_;
 4703:     my $navmap = Apache::lonnavmaps::navmap->new();
 4704:     unless (ref($navmap)) {
 4705:         if (ref($map_error)) {
 4706:             $$map_error = 'navmap';
 4707:         }
 4708:         return;
 4709:     }
 4710:     my %symbx = ();
 4711:     my @titles = ();
 4712:     my $minder = 0;
 4713: 
 4714:     # Gather every sequence that has problems.
 4715:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4716: 					       1,0,1);
 4717:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4718: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4719: 	    my $title = $minder.'.'.
 4720: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4721: 	    push(@titles, $title); # minder in case two titles are identical
 4722: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4723: 	    $minder++;
 4724: 	}
 4725:     }
 4726:     return \@titles,\%symbx;
 4727: }
 4728: 
 4729: #
 4730: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4731: sub displayPage {
 4732:     my ($request) = shift;
 4733: 
 4734:     my ($symb) = &get_symb($request);
 4735:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4736:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4737:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4738:     my $pageTitle = $env{'form.page'};
 4739:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4740:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4741:     my $usec=$classlist->{$env{'form.student'}}[5];
 4742: 
 4743:     #need to make sure we have the correct data for later EXT calls, 
 4744:     #thus invalidate the cache
 4745:     &Apache::lonnet::devalidatecourseresdata(
 4746:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4747:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4748:     &Apache::lonnet::clear_EXT_cache_status();
 4749: 
 4750:     if (!&canview($usec)) {
 4751: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4752: 	$request->print(&show_grading_menu_form($symb));
 4753: 	return;
 4754:     }
 4755:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4756:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4757: 	'</h3>'."\n";
 4758:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4759:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4760: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4761:     } else {
 4762: 	delete($env{'form.CODE'});
 4763:     }
 4764:     &sub_page_js($request);
 4765:     $request->print($result);
 4766: 
 4767:     my $navmap = Apache::lonnavmaps::navmap->new();
 4768:     unless (ref($navmap)) {
 4769:         $request->print(&navmap_errormsg());
 4770:         $request->print(&show_grading_menu_form($symb));
 4771:         return;
 4772:     }
 4773:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4774:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4775:     if (!$map) {
 4776: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4777: 	$request->print(&show_grading_menu_form($symb));
 4778: 	return; 
 4779:     }
 4780:     my $iterator = $navmap->getIterator($map->map_start(),
 4781: 					$map->map_finish());
 4782: 
 4783:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4784: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4785: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4786: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4787: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4788: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4789: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4790: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4791: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4792: 
 4793:     if (defined($env{'form.CODE'})) {
 4794: 	$studentTable.=
 4795: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4796:     }
 4797:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4798: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4799: 
 4800:     $studentTable.='&nbsp;<span class="LC_info">'.
 4801:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4802:         '</span>'."\n".
 4803: 	&Apache::loncommon::start_data_table().
 4804: 	&Apache::loncommon::start_data_table_header_row().
 4805: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4806: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4807: 	&Apache::loncommon::end_data_table_header_row();
 4808: 
 4809:     &Apache::lonxml::clear_problem_counter();
 4810:     my ($depth,$question,$prob) = (1,1,1);
 4811:     $iterator->next(); # skip the first BEGIN_MAP
 4812:     my $curRes = $iterator->next(); # for "current resource"
 4813:     while ($depth > 0) {
 4814:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4815:         if($curRes == $iterator->END_MAP) { $depth--; }
 4816: 
 4817:         if (ref($curRes) && $curRes->is_problem()) {
 4818: 	    my $parts = $curRes->parts();
 4819:             my $title = $curRes->compTitle();
 4820: 	    my $symbx = $curRes->symb();
 4821: 	    $studentTable.=
 4822: 		&Apache::loncommon::start_data_table_row().
 4823: 		'<td align="center" valign="top" >'.$prob.
 4824: 		(scalar(@{$parts}) == 1 ? '' 
 4825: 		                        : '<br />('.&mt('[_1]parts',
 4826: 							scalar(@{$parts}).'&nbsp;').')'
 4827: 		 ).
 4828: 		 '</td>';
 4829: 	    $studentTable.='<td valign="top">';
 4830: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4831: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4832: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4833: 					     undef,'both',\%form);
 4834: 	    } else {
 4835: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4836: 		$companswer =~ s|<form(.*?)>||g;
 4837: 		$companswer =~ s|</form>||g;
 4838: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4839: #		    $companswer =~ s/$1/ /ms;
 4840: #		    $request->print('match='.$1."<br />\n");
 4841: #		}
 4842: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4843: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4844: 	    }
 4845: 
 4846: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4847: 
 4848: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4849: 		if ($record{'version'} eq '') {
 4850: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4851: 		} else {
 4852: 		    my %responseType = ();
 4853: 		    foreach my $partid (@{$parts}) {
 4854: 			my @responseIds =$curRes->responseIds($partid);
 4855: 			my @responseType =$curRes->responseType($partid);
 4856: 			my %responseIds;
 4857: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4858: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4859: 			}
 4860: 			$responseType{$partid} = \%responseIds;
 4861: 		    }
 4862: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4863: 
 4864: 		}
 4865: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4866: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4867: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4868: 									$env{'request.course.id'},
 4869: 									'','.submission');
 4870:  
 4871: 	    }
 4872: 	    if (&canmodify($usec)) {
 4873:             $studentTable.=&gradeBox_start();
 4874: 		foreach my $partid (@{$parts}) {
 4875: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4876: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4877: 		    $question++;
 4878: 		}
 4879:             $studentTable.=&gradeBox_end();
 4880: 		$prob++;
 4881: 	    }
 4882: 	    $studentTable.='</td></tr>';
 4883: 
 4884: 	}
 4885:         $curRes = $iterator->next();
 4886:     }
 4887: 
 4888:     $studentTable.=
 4889:         '</table>'."\n".
 4890:         '<input type="button" value="'.&mt('Save').'" '.
 4891:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4892:         '</form>'."\n";
 4893:     $studentTable.=&show_grading_menu_form($symb);
 4894:     $request->print($studentTable);
 4895: 
 4896:     return '';
 4897: }
 4898: 
 4899: sub displaySubByDates {
 4900:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4901:     my $isCODE=0;
 4902:     my $isTask = ($symb =~/\.task$/);
 4903:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4904:     my $studentTable=&Apache::loncommon::start_data_table().
 4905: 	&Apache::loncommon::start_data_table_header_row().
 4906: 	'<th>'.&mt('Date/Time').'</th>'.
 4907: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4908:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4909: 	'<th>'.&mt('Submission').'</th>'.
 4910: 	'<th>'.&mt('Status').'</th>'.
 4911: 	&Apache::loncommon::end_data_table_header_row();
 4912:     my ($version);
 4913:     my %mark;
 4914:     my %orders;
 4915:     $mark{'correct_by_student'} = $checkIcon;
 4916:     if (!exists($$record{'1:timestamp'})) {
 4917: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4918:     }
 4919: 
 4920:     my $interaction;
 4921:     my $no_increment = 1;
 4922:     my %lastrndseed;
 4923:     for ($version=1;$version<=$$record{'version'};$version++) {
 4924: 	my $timestamp = 
 4925: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4926: 	if (exists($$record{$version.':resource.0.version'})) {
 4927: 	    $interaction = $$record{$version.':resource.0.version'};
 4928: 	}
 4929:         if ($isTask && $env{'form.previousversion'}) {
 4930:             next unless ($interaction == $env{'form.previousversion'});
 4931:         }
 4932: 	my $where = ($isTask ? "$version:resource.$interaction"
 4933: 		             : "$version:resource");
 4934: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4935: 	    '<td>'.$timestamp.'</td>';
 4936: 	if ($isCODE) {
 4937: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4938: 	}
 4939:         if ($isTask) {
 4940:             $studentTable.='<td>'.$interaction.'</td>';
 4941:         }
 4942: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4943: 	my @displaySub = ();
 4944: 	foreach my $partid (@{$parts}) {
 4945:             my ($hidden,$type);
 4946:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4947:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4948:                 $hidden = 1;
 4949:             }
 4950: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4951: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4952: 	    
 4953: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4954: 	    my $display_part=&get_display_part($partid,$symb);
 4955: 	    foreach my $matchKey (@matchKey) {
 4956: 		if (exists($$record{$version.':'.$matchKey}) &&
 4957: 		    $$record{$version.':'.$matchKey} ne '') {
 4958:                     
 4959: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4960: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4961:                     $displaySub[0].='<span class="LC_nobreak">';
 4962:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4963:                                    .' <span class="LC_internal_info">'
 4964:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4965:                                    .'</span>'
 4966:                                    .' <b>';
 4967:                     if ($hidden) {
 4968:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4969:                     } else {
 4970:                         my ($trial,$rndseed,$newvariation);
 4971:                         if ($type eq 'randomizetry') {
 4972:                             $trial = $$record{"$where.$partid.tries"};
 4973:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4974:                         }
 4975: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4976: 			    $displaySub[0].=&mt('Trial not counted');
 4977: 		        } else {
 4978: 			    $displaySub[0].=&mt('Trial: [_1]',
 4979: 					    $$record{"$where.$partid.tries"});
 4980:                             if ($rndseed || $lastrndseed{$partid}) {
 4981:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4982:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4983:                                 }
 4984:                             }
 4985: 		        }
 4986: 		        my $responseType=($isTask ? 'Task'
 4987:                                               : $responseType->{$partid}->{$responseId});
 4988: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4989: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4990: 			    $orders{$partid}->{$responseId}=
 4991: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4992:                                            $no_increment,$type,$trial,$rndseed);
 4993: 		        }
 4994: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4995: 		        $displaySub[0].='&nbsp; '.
 4996: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4997:                     }
 4998: 		}
 4999: 	    }
 5000: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5001: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5002: 				    $$record{"$where.$partid.checkedin"},
 5003: 				    $$record{"$where.$partid.checkedin.slot"}).
 5004: 					'<br />';
 5005: 	    }
 5006: 	    if (exists $$record{"$where.$partid.award"}) {
 5007: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5008: 		    lc($$record{"$where.$partid.award"}).' '.
 5009: 		    $mark{$$record{"$where.$partid.solved"}}.
 5010: 		    '<br />';
 5011: 	    }
 5012: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5013: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5014: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5015: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5016: 		$displaySub[2].=
 5017: 		    $$record{"$version:resource.$partid.regrader"}.
 5018: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5019: 	    }
 5020: 	}
 5021: 	# needed because old essay regrader has not parts info
 5022: 	if (exists $$record{"$version:resource.regrader"}) {
 5023: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5024: 	}
 5025: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5026: 	if ($displaySub[2]) {
 5027: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5028: 	}
 5029: 	$studentTable.='&nbsp;</td>'.
 5030: 	    &Apache::loncommon::end_data_table_row();
 5031:     }
 5032:     $studentTable.=&Apache::loncommon::end_data_table();
 5033:     return $studentTable;
 5034: }
 5035: 
 5036: sub updateGradeByPage {
 5037:     my ($request) = shift;
 5038: 
 5039:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5040:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5041:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5042:     my $pageTitle = $env{'form.page'};
 5043:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5044:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5045:     my $usec=$classlist->{$env{'form.student'}}[5];
 5046:     if (!&canmodify($usec)) {
 5047: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5048: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5049: 	return;
 5050:     }
 5051:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5052:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5053: 	'</h3>'."\n";
 5054: 
 5055:     $request->print($result);
 5056: 
 5057: 
 5058:     my $navmap = Apache::lonnavmaps::navmap->new();
 5059:     unless (ref($navmap)) {
 5060:         $request->print(&navmap_errormsg());
 5061:         return;
 5062:     }
 5063:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5064:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5065:     if (!$map) {
 5066: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5067: 	my ($symb)=&get_symb($request);
 5068: 	$request->print(&show_grading_menu_form($symb));
 5069: 	return; 
 5070:     }
 5071:     my $iterator = $navmap->getIterator($map->map_start(),
 5072: 					$map->map_finish());
 5073: 
 5074:     my $studentTable=
 5075: 	&Apache::loncommon::start_data_table().
 5076: 	&Apache::loncommon::start_data_table_header_row().
 5077: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5078: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5079: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5080: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5081: 	&Apache::loncommon::end_data_table_header_row();
 5082: 
 5083:     $iterator->next(); # skip the first BEGIN_MAP
 5084:     my $curRes = $iterator->next(); # for "current resource"
 5085:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 5086:     while ($depth > 0) {
 5087:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5088:         if($curRes == $iterator->END_MAP) { $depth--; }
 5089: 
 5090:         if (ref($curRes) && $curRes->is_problem()) {
 5091: 	    my $parts = $curRes->parts();
 5092:             my $title = $curRes->compTitle();
 5093: 	    my $symbx = $curRes->symb();
 5094: 	    $studentTable.=
 5095: 		&Apache::loncommon::start_data_table_row().
 5096: 		'<td align="center" valign="top" >'.$prob.
 5097: 		(scalar(@{$parts}) == 1 ? '' 
 5098:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5099: 		.')').'</td>';
 5100: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5101: 
 5102: 	    my %newrecord=();
 5103: 	    my @displayPts=();
 5104:             my %aggregate = ();
 5105:             my $aggregateflag = 0;
 5106: 	    foreach my $partid (@{$parts}) {
 5107: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5108: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5109: 
 5110: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5111: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5112: 		my $partial = $newpts/$wgt;
 5113: 		my $score;
 5114: 		if ($partial > 0) {
 5115: 		    $score = 'correct_by_override';
 5116: 		} elsif ($newpts ne '') { #empty is taken as 0
 5117: 		    $score = 'incorrect_by_override';
 5118: 		}
 5119: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5120: 		if ($dropMenu eq 'excused') {
 5121: 		    $partial = '';
 5122: 		    $score = 'excused';
 5123: 		} elsif ($dropMenu eq 'reset status'
 5124: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5125: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5126: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5127: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5128: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5129: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5130: 		    $changeflag++;
 5131: 		    $newpts = '';
 5132:                     
 5133:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5134:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5135:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5136:                     if ($aggtries > 0) {
 5137:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5138:                         $aggregateflag = 1;
 5139:                     }
 5140: 		}
 5141: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5142: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5143: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5144: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5145: 		    '&nbsp;<br />';
 5146: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5147: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5148: 		    '&nbsp;<br />';
 5149: 		$question++;
 5150: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5151: 
 5152: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5153: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5154: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5155: 		    if (scalar(keys(%newrecord)) > 0);
 5156: 
 5157: 		$changeflag++;
 5158: 	    }
 5159: 	    if (scalar(keys(%newrecord)) > 0) {
 5160: 		my %record = 
 5161: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5162: 					     $udom,$uname);
 5163: 
 5164: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5165: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5166: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5167: 		    $newrecord{'resource.CODE'} = '';
 5168: 		}
 5169: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5170: 					$udom,$uname);
 5171: 		%record = &Apache::lonnet::restore($symbx,
 5172: 						   $env{'request.course.id'},
 5173: 						   $udom,$uname);
 5174: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5175: 					     $cdom,$cnum,$udom,$uname);
 5176: 	    }
 5177: 	    
 5178:             if ($aggregateflag) {
 5179:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5180:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5181:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5182:             }
 5183: 
 5184: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5185: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5186: 		&Apache::loncommon::end_data_table_row();
 5187: 
 5188: 	    $prob++;
 5189: 	}
 5190:         $curRes = $iterator->next();
 5191:     }
 5192: 
 5193:     $studentTable.=&Apache::loncommon::end_data_table();
 5194:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5195:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5196: 		  &mt('The scores were changed for [quant,_1,problem].',
 5197: 		  $changeflag));
 5198:     $request->print($grademsg.$studentTable);
 5199: 
 5200:     return '';
 5201: }
 5202: 
 5203: #-------- end of section for handling grading by page/sequence ---------
 5204: #
 5205: #-------------------------------------------------------------------
 5206: 
 5207: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5208: #
 5209: #------ start of section for handling grading by page/sequence ---------
 5210: 
 5211: =pod
 5212: 
 5213: =head1 Bubble sheet grading routines
 5214: 
 5215:   For this documentation:
 5216: 
 5217:    'scanline' refers to the full line of characters
 5218:    from the file that we are parsing that represents one entire sheet
 5219: 
 5220:    'bubble line' refers to the data
 5221:    representing the line of bubbles that are on the physical bubblesheet
 5222: 
 5223: 
 5224: The overall process is that a scanned in bubblesheet data is uploaded
 5225: into a course. When a user wants to grade, they select a
 5226: sequence/folder of resources, a file of bubblesheet info, and pick
 5227: one of the predefined configurations for what each scanline looks
 5228: like.
 5229: 
 5230: Next each scanline is checked for any errors of either 'missing
 5231: bubbles' (it's an error because it may have been mis-scanned
 5232: because too light bubbling), 'double bubble' (each bubble line should
 5233: have no more than one letter picked), invalid or duplicated CODE,
 5234: invalid student/employee ID
 5235: 
 5236: If the CODE option is used that determines the randomization of the
 5237: homework problems, either way the student/employee ID is looked up into a
 5238: username:domain.
 5239: 
 5240: During the validation phase the instructor can choose to skip scanlines. 
 5241: 
 5242: After the validation phase, there are now 3 bubblesheet files
 5243: 
 5244:   scantron_original_filename (unmodified original file)
 5245:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5246:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5247: 
 5248: Also there is a separate hash nohist_scantrondata that contains extra
 5249: correction information that isn't representable in the bubblesheet
 5250: file (see &scantron_getfile() for more information)
 5251: 
 5252: After all scanlines are either valid, marked as valid or skipped, then
 5253: foreach line foreach problem in the picked sequence, an ssi request is
 5254: made that simulates a user submitting their selected letter(s) against
 5255: the homework problem.
 5256: 
 5257: =over 4
 5258: 
 5259: 
 5260: 
 5261: =item defaultFormData
 5262: 
 5263:   Returns html hidden inputs used to hold context/default values.
 5264: 
 5265:  Arguments:
 5266:   $symb - $symb of the current resource 
 5267: 
 5268: =cut
 5269: 
 5270: sub defaultFormData {
 5271:     my ($symb)=@_;
 5272:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5273:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5274:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5275: }
 5276: 
 5277: 
 5278: =pod 
 5279: 
 5280: =item getSequenceDropDown
 5281: 
 5282:    Return html dropdown of possible sequences to grade
 5283:  
 5284:  Arguments:
 5285:    $symb - $symb of the current resource
 5286:    $map_error - ref to scalar which will container error if
 5287:                 $navmap object is unavailable in &getSymbMap().
 5288: 
 5289: =cut
 5290: 
 5291: sub getSequenceDropDown {
 5292:     my ($symb,$map_error)=@_;
 5293:     my $result='<select name="selectpage">'."\n";
 5294:     my ($titles,$symbx) = &getSymbMap($map_error);
 5295:     if (ref($map_error)) {
 5296:         return if ($$map_error);
 5297:     }
 5298:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5299:     my $ctr=0;
 5300:     foreach (@$titles) {
 5301: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5302: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5303: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5304: 	    '>'.$showtitle.'</option>'."\n";
 5305: 	$ctr++;
 5306:     }
 5307:     $result.= '</select>';
 5308:     return $result;
 5309: }
 5310: 
 5311: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5312:                                    # key is zero-based index - 0, 1, 2 ...
 5313: 
 5314: my %first_bubble_line;             # First bubble line no. for each bubble.
 5315: 
 5316: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5317:                                    # matchresponse or rankresponse, where 
 5318:                                    # an individual response can have multiple 
 5319:                                    # lines
 5320: 
 5321: my %responsetype_per_response;     # responsetype for each response
 5322: 
 5323: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5324:                                    # numbered response. Needed when randomorder
 5325:                                    # or randompick are in use. Key is ID, value 
 5326:                                    # is response number.
 5327: 
 5328: # Save and restore the bubble lines array to the form env.
 5329: 
 5330: 
 5331: sub save_bubble_lines {
 5332:     foreach my $line (keys(%bubble_lines_per_response)) {
 5333: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5334: 	$env{"form.scantron.first_bubble_line.$line"} =
 5335: 	    $first_bubble_line{$line};
 5336:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5337:             $subdivided_bubble_lines{$line};
 5338:         $env{"form.scantron.responsetype.$line"} =
 5339:             $responsetype_per_response{$line};
 5340:     }
 5341:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5342:         my $line = $masterseq_id_responsenum{$resid};
 5343:         $env{"form.scantron.residpart.$line"} = $resid;
 5344:     }
 5345: }
 5346: 
 5347: 
 5348: sub restore_bubble_lines {
 5349:     my $line = 0;
 5350:     %bubble_lines_per_response = ();
 5351:     %masterseq_id_responsenum = ();
 5352:     while ($env{"form.scantron.bubblelines.$line"}) {
 5353: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5354: 	$bubble_lines_per_response{$line} = $value;
 5355: 	$first_bubble_line{$line}  =
 5356: 	    $env{"form.scantron.first_bubble_line.$line"};
 5357:         $subdivided_bubble_lines{$line} =
 5358:             $env{"form.scantron.sub_bubblelines.$line"};
 5359:         $responsetype_per_response{$line} =
 5360:             $env{"form.scantron.responsetype.$line"};
 5361:         my $id = $env{"form.scantron.residpart.$line"};
 5362:         $masterseq_id_responsenum{$id} = $line;
 5363: 	$line++;
 5364:     }
 5365: }
 5366: 
 5367: =pod 
 5368: 
 5369: =item scantron_filenames
 5370: 
 5371:    Returns a list of the scantron files in the current course 
 5372: 
 5373: =cut
 5374: 
 5375: sub scantron_filenames {
 5376:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5377:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5378:     my $getpropath = 1;
 5379:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5380:                                                         $cname,$getpropath);
 5381:     my @possiblenames;
 5382:     if (ref($dirlist) eq 'ARRAY') {
 5383:         foreach my $filename (sort(@{$dirlist})) {
 5384: 	    ($filename)=split(/&/,$filename);
 5385: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5386: 	    $filename=~s/^scantron_orig_//;
 5387: 	    push(@possiblenames,$filename);
 5388:         }
 5389:     }
 5390:     return @possiblenames;
 5391: }
 5392: 
 5393: =pod 
 5394: 
 5395: =item scantron_uploads
 5396: 
 5397:    Returns  html drop-down list of scantron files in current course.
 5398: 
 5399:  Arguments:
 5400:    $file2grade - filename to set as selected in the dropdown
 5401: 
 5402: =cut
 5403: 
 5404: sub scantron_uploads {
 5405:     my ($file2grade) = @_;
 5406:     my $result=	'<select name="scantron_selectfile">';
 5407:     $result.="<option></option>";
 5408:     foreach my $filename (sort(&scantron_filenames())) {
 5409: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5410:     }
 5411:     $result.="</select>";
 5412:     return $result;
 5413: }
 5414: 
 5415: =pod 
 5416: 
 5417: =item scantron_scantab
 5418: 
 5419:   Returns html drop down of the scantron formats in the scantronformat.tab
 5420:   file.
 5421: 
 5422: =cut
 5423: 
 5424: sub scantron_scantab {
 5425:     my $result='<select name="scantron_format">'."\n";
 5426:     $result.='<option></option>'."\n";
 5427:     my @lines = &get_scantronformat_file();
 5428:     if (@lines > 0) {
 5429:         foreach my $line (@lines) {
 5430:             next if (($line =~ /^\#/) || ($line eq ''));
 5431: 	    my ($name,$descrip)=split(/:/,$line);
 5432: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5433:         }
 5434:     }
 5435:     $result.='</select>'."\n";
 5436:     return $result;
 5437: }
 5438: 
 5439: =pod
 5440: 
 5441: =item get_scantronformat_file
 5442: 
 5443:   Returns an array containing lines from the scantron format file for
 5444:   the domain of the course.
 5445: 
 5446:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5447:   lines are from this file.
 5448: 
 5449:   Otherwise, if a default.tab has been published in RES space by the 
 5450:   domainconfig user, lines are from this file.
 5451: 
 5452:   Otherwise, fall back to getting lines from the legacy file on the
 5453:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5454: 
 5455: =cut
 5456: 
 5457: sub get_scantronformat_file {
 5458:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5459:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5460:     my $gottab = 0;
 5461:     my @lines;
 5462:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5463:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5464:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5465:             if ($formatfile ne '-1') {
 5466:                 @lines = split("\n",$formatfile,-1);
 5467:                 $gottab = 1;
 5468:             }
 5469:         }
 5470:     }
 5471:     if (!$gottab) {
 5472:         my $confname = $cdom.'-domainconfig';
 5473:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5474:         my $formatfile =  &Apache::lonnet::getfile($default);
 5475:         if ($formatfile ne '-1') {
 5476:             @lines = split("\n",$formatfile,-1);
 5477:             $gottab = 1;
 5478:         }
 5479:     }
 5480:     if (!$gottab) {
 5481:         my @domains = &Apache::lonnet::current_machine_domains();
 5482:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5483:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5484:             @lines = <$fh>;
 5485:             close($fh);
 5486:         } else {
 5487:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5488:             @lines = <$fh>;
 5489:             close($fh);
 5490:         }
 5491:     }
 5492:     return @lines;
 5493: }
 5494: 
 5495: =pod 
 5496: 
 5497: =item scantron_CODElist
 5498: 
 5499:   Returns html drop down of the saved CODE lists from current course,
 5500:   generated from earlier printings.
 5501: 
 5502: =cut
 5503: 
 5504: sub scantron_CODElist {
 5505:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5506:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5507:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5508:     my $namechoice='<option></option>';
 5509:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5510: 	if ($name =~ /^error: 2 /) { next; }
 5511: 	if ($name =~ /^type\0/) { next; }
 5512: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5513:     }
 5514:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5515:     return $namechoice;
 5516: }
 5517: 
 5518: =pod 
 5519: 
 5520: =item scantron_CODEunique
 5521: 
 5522:   Returns the html for "Each CODE to be used once" radio.
 5523: 
 5524: =cut
 5525: 
 5526: sub scantron_CODEunique {
 5527:     my $result='<span class="LC_nobreak">
 5528:                  <label><input type="radio" name="scantron_CODEunique"
 5529:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5530:                 </span>
 5531:                 <span class="LC_nobreak">
 5532:                  <label><input type="radio" name="scantron_CODEunique"
 5533:                         value="no" />'.&mt('No').' </label>
 5534:                 </span>';
 5535:     return $result;
 5536: }
 5537: 
 5538: =pod 
 5539: 
 5540: =item scantron_selectphase
 5541: 
 5542:   Generates the initial screen to start the bubblesheet process.
 5543:   Allows for - starting a grading run.
 5544:              - downloading existing scan data (original, corrected
 5545:                                                 or skipped info)
 5546: 
 5547:              - uploading new scan data
 5548: 
 5549:  Arguments:
 5550:   $r          - The Apache request object
 5551:   $file2grade - name of the file that contain the scanned data to score
 5552: 
 5553: =cut
 5554: 
 5555: sub scantron_selectphase {
 5556:     my ($r,$file2grade) = @_;
 5557:     my ($symb)=&get_symb($r);
 5558:     if (!$symb) {return '';}
 5559:     my $map_error;
 5560:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5561:     if ($map_error) {
 5562:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5563:         return;
 5564:     }
 5565:     my $default_form_data=&defaultFormData($symb);
 5566:     my $grading_menu_button=&show_grading_menu_form($symb);
 5567:     my $file_selector=&scantron_uploads($file2grade);
 5568:     my $format_selector=&scantron_scantab();
 5569:     my $CODE_selector=&scantron_CODElist();
 5570:     my $CODE_unique=&scantron_CODEunique();
 5571:     my $result;
 5572: 
 5573:     $ssi_error = 0;
 5574: 
 5575:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5576:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5577: 
 5578:         # Chunk of form to prompt for a scantron file upload.
 5579: 
 5580:         $r->print('
 5581:     <br />
 5582:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5583:        '.&Apache::loncommon::start_data_table_header_row().'
 5584:             <th>
 5585:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5586:             </th>
 5587:        '.&Apache::loncommon::end_data_table_header_row().'
 5588:        '.&Apache::loncommon::start_data_table_row().'
 5589:             <td>
 5590: ');
 5591:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5592:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5593:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5594:     $r->print('
 5595:               <script type="text/javascript" language="javascript">
 5596:     function checkUpload(formname) {
 5597:         if (formname.upfile.value == "") {
 5598:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5599:             return false;
 5600:         }
 5601:         formname.submit();
 5602:     }
 5603:               </script>
 5604: 
 5605:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5606:                 '.$default_form_data.'
 5607:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5608:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5609:                 <input name="command" value="scantronupload_save" type="hidden" />
 5610:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5611:                 <br />
 5612:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5613:               </form>
 5614: ');
 5615: 
 5616:         $r->print('
 5617:             </td>
 5618:        '.&Apache::loncommon::end_data_table_row().'
 5619:        '.&Apache::loncommon::end_data_table().'
 5620: ');
 5621:     }
 5622: 
 5623:     # Chunk of form to prompt for a file to grade and how:
 5624: 
 5625:     $result.= '
 5626:     <br />
 5627:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5628:     <input type="hidden" name="command" value="scantron_warning" />
 5629:     '.$default_form_data.'
 5630:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5631:        '.&Apache::loncommon::start_data_table_header_row().'
 5632:             <th colspan="2">
 5633:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5634:             </th>
 5635:        '.&Apache::loncommon::end_data_table_header_row().'
 5636:        '.&Apache::loncommon::start_data_table_row().'
 5637:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5638:        '.&Apache::loncommon::end_data_table_row().'
 5639:        '.&Apache::loncommon::start_data_table_row().'
 5640:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5641:        '.&Apache::loncommon::end_data_table_row().'
 5642:        '.&Apache::loncommon::start_data_table_row().'
 5643:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5644:        '.&Apache::loncommon::end_data_table_row().'
 5645:        '.&Apache::loncommon::start_data_table_row().'
 5646:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5647:        '.&Apache::loncommon::end_data_table_row().'
 5648:        '.&Apache::loncommon::start_data_table_row().'
 5649:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5650:        '.&Apache::loncommon::end_data_table_row().'
 5651:        '.&Apache::loncommon::start_data_table_row().'
 5652: 	    <td> '.&mt('Options:').' </td>
 5653:             <td>
 5654: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5655:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5656:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5657: 	    </td>
 5658:        '.&Apache::loncommon::end_data_table_row().'
 5659:        '.&Apache::loncommon::start_data_table_row().'
 5660:             <td colspan="2">
 5661:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5662:             </td>
 5663:        '.&Apache::loncommon::end_data_table_row().'
 5664:     '.&Apache::loncommon::end_data_table().'
 5665:     </form>
 5666: ';
 5667:    
 5668:     $r->print($result);
 5669: 
 5670:     # Chunk of the form that prompts to view a scoring office file,
 5671:     # corrected file, skipped records in a file.
 5672: 
 5673:     $r->print('
 5674:    <br />
 5675:    <form action="/adm/grades" name="scantron_download">
 5676:      '.$default_form_data.'
 5677:      <input type="hidden" name="command" value="scantron_download" />
 5678:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5679:        '.&Apache::loncommon::start_data_table_header_row().'
 5680:               <th>
 5681:                 &nbsp;'.&mt('Download a scoring office file').'
 5682:               </th>
 5683:        '.&Apache::loncommon::end_data_table_header_row().'
 5684:        '.&Apache::loncommon::start_data_table_row().'
 5685:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5686:                 <br />
 5687:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5688:        '.&Apache::loncommon::end_data_table_row().'
 5689:      '.&Apache::loncommon::end_data_table().'
 5690:    </form>
 5691:    <br />
 5692: ');
 5693: 
 5694:     &Apache::lonpickcode::code_list($r,2);
 5695: 
 5696:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5697:              $default_form_data."\n".
 5698:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5699:              &Apache::loncommon::start_data_table_header_row()."\n".
 5700:              '<th colspan="2">
 5701:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5702:              '</th>'."\n".
 5703:               &Apache::loncommon::end_data_table_header_row()."\n".
 5704:               &Apache::loncommon::start_data_table_row()."\n".
 5705:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5706:               '<td> '.$sequence_selector.' </td>'.
 5707:               &Apache::loncommon::end_data_table_row()."\n".
 5708:               &Apache::loncommon::start_data_table_row()."\n".
 5709:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5710:               '<td> '.$file_selector.' </td>'."\n".
 5711:               &Apache::loncommon::end_data_table_row()."\n".
 5712:               &Apache::loncommon::start_data_table_row()."\n".
 5713:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5714:               '<td> '.$format_selector.' </td>'."\n".
 5715:               &Apache::loncommon::end_data_table_row()."\n".
 5716:               &Apache::loncommon::start_data_table_row()."\n".
 5717:               '<td> '.&mt('Options').' </td>'."\n".
 5718:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5719:               &Apache::loncommon::end_data_table_row()."\n".
 5720:               &Apache::loncommon::start_data_table_row()."\n".
 5721:               '<td colspan="2">'."\n".
 5722:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5723:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5724:               '</td>'."\n".
 5725:               &Apache::loncommon::end_data_table_row()."\n".
 5726:               &Apache::loncommon::end_data_table()."\n".
 5727:               '</form><br />');
 5728:     $r->print($grading_menu_button);
 5729:     return;
 5730: }
 5731: 
 5732: =pod
 5733: 
 5734: =item get_scantron_config
 5735: 
 5736:    Parse and return the scantron configuration line selected as a
 5737:    hash of configuration file fields.
 5738: 
 5739:  Arguments:
 5740:     which - the name of the configuration to parse from the file.
 5741: 
 5742: 
 5743:  Returns:
 5744:             If the named configuration is not in the file, an empty
 5745:             hash is returned.
 5746:     a hash with the fields
 5747:       name         - internal name for the this configuration setup
 5748:       description  - text to display to operator that describes this config
 5749:       CODElocation - if 0 or the string 'none'
 5750:                           - no CODE exists for this config
 5751:                      if -1 || the string 'letter'
 5752:                           - a CODE exists for this config and is
 5753:                             a string of letters
 5754:                      Unsupported value (but planned for future support)
 5755:                           if a positive integer
 5756:                                - The CODE exists as the first n items from
 5757:                                  the question section of the form
 5758:                           if the string 'number'
 5759:                                - The CODE exists for this config and is
 5760:                                  a string of numbers
 5761:       CODEstart   - (only matter if a CODE exists) column in the line where
 5762:                      the CODE starts
 5763:       CODElength  - length of the CODE
 5764:       IDstart     - column where the student/employee ID starts
 5765:       IDlength    - length of the student/employee ID info
 5766:       Qstart      - column where the information from the bubbled
 5767:                     'questions' start
 5768:       Qlength     - number of columns comprising a single bubble line from
 5769:                     the sheet. (usually either 1 or 10)
 5770:       Qon         - either a single character representing the character used
 5771:                     to signal a bubble was chosen in the positional setup, or
 5772:                     the string 'letter' if the letter of the chosen bubble is
 5773:                     in the final, or 'number' if a number representing the
 5774:                     chosen bubble is in the file (1->A 0->J)
 5775:       Qoff        - the character used to represent that a bubble was
 5776:                     left blank
 5777:       PaperID     - if the scanning process generates a unique number for each
 5778:                     sheet scanned the column that this ID number starts in
 5779:       PaperIDlength - number of columns that comprise the unique ID number
 5780:                       for the sheet of paper
 5781:       FirstName   - column that the first name starts in
 5782:       FirstNameLength - number of columns that the first name spans
 5783:  
 5784:       LastName    - column that the last name starts in
 5785:       LastNameLength - number of columns that the last name spans
 5786:       BubblesPerRow - number of bubbles available in each row used to
 5787:                       bubble an answer. (If not specified, 10 assumed).
 5788: 
 5789: =cut
 5790: 
 5791: sub get_scantron_config {
 5792:     my ($which) = @_;
 5793:     my @lines = &get_scantronformat_file();
 5794:     my %config;
 5795:     #FIXME probably should move to XML it has already gotten a bit much now
 5796:     foreach my $line (@lines) {
 5797: 	my ($name,$descrip)=split(/:/,$line);
 5798: 	if ($name ne $which ) { next; }
 5799: 	chomp($line);
 5800: 	my @config=split(/:/,$line);
 5801: 	$config{'name'}=$config[0];
 5802: 	$config{'description'}=$config[1];
 5803: 	$config{'CODElocation'}=$config[2];
 5804: 	$config{'CODEstart'}=$config[3];
 5805: 	$config{'CODElength'}=$config[4];
 5806: 	$config{'IDstart'}=$config[5];
 5807: 	$config{'IDlength'}=$config[6];
 5808: 	$config{'Qstart'}=$config[7];
 5809:  	$config{'Qlength'}=$config[8];
 5810: 	$config{'Qoff'}=$config[9];
 5811: 	$config{'Qon'}=$config[10];
 5812: 	$config{'PaperID'}=$config[11];
 5813: 	$config{'PaperIDlength'}=$config[12];
 5814: 	$config{'FirstName'}=$config[13];
 5815: 	$config{'FirstNamelength'}=$config[14];
 5816: 	$config{'LastName'}=$config[15];
 5817: 	$config{'LastNamelength'}=$config[16];
 5818:         $config{'BubblesPerRow'}=$config[17];
 5819: 	last;
 5820:     }
 5821:     return %config;
 5822: }
 5823: 
 5824: =pod 
 5825: 
 5826: =item username_to_idmap
 5827: 
 5828:     creates a hash keyed by student/employee ID with values of the corresponding
 5829:     student username:domain.
 5830: 
 5831:   Arguments:
 5832: 
 5833:     $classlist - reference to the class list hash. This is a hash
 5834:                  keyed by student name:domain  whose elements are references
 5835:                  to arrays containing various chunks of information
 5836:                  about the student. (See loncoursedata for more info).
 5837: 
 5838:   Returns
 5839:     %idmap - the constructed hash
 5840: 
 5841: =cut
 5842: 
 5843: sub username_to_idmap {
 5844:     my ($classlist)= @_;
 5845:     my %idmap;
 5846:     foreach my $student (keys(%$classlist)) {
 5847: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5848: 	    $student;
 5849:     }
 5850:     return %idmap;
 5851: }
 5852: 
 5853: =pod
 5854: 
 5855: =item scantron_fixup_scanline
 5856: 
 5857:    Process a requested correction to a scanline.
 5858: 
 5859:   Arguments:
 5860:     $scantron_config   - hash from &get_scantron_config()
 5861:     $scan_data         - hash of correction information 
 5862:                           (see &scantron_getfile())
 5863:     $line              - existing scanline
 5864:     $whichline         - line number of the passed in scanline
 5865:     $field             - type of change to process 
 5866:                          (either 
 5867:                           'ID'     -> correct the student/employee ID
 5868:                           'CODE'   -> correct the CODE
 5869:                           'answer' -> fixup the submitted answers)
 5870:     
 5871:    $args               - hash of additional info,
 5872:                           - 'ID' 
 5873:                                'newid' -> studentID to use in replacement
 5874:                                           of existing one
 5875:                           - 'CODE' 
 5876:                                'CODE_ignore_dup' - set to true if duplicates
 5877:                                                    should be ignored.
 5878: 	                       'CODE' - is new code or 'use_unfound'
 5879:                                         if the existing unfound code should
 5880:                                         be used as is
 5881:                           - 'answer'
 5882:                                'response' - new answer or 'none' if blank
 5883:                                'question' - the bubble line to change
 5884:                                'questionnum' - the question identifier,
 5885:                                                may include subquestion. 
 5886: 
 5887:   Returns:
 5888:     $line - the modified scanline
 5889: 
 5890:   Side effects: 
 5891:     $scan_data - may be updated
 5892: 
 5893: =cut
 5894: 
 5895: 
 5896: sub scantron_fixup_scanline {
 5897:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5898:     if ($field eq 'ID') {
 5899: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5900: 	    return ($line,1,'New value too large');
 5901: 	}
 5902: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5903: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5904: 				     $args->{'newid'});
 5905: 	}
 5906: 	substr($line,$$scantron_config{'IDstart'}-1,
 5907: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5908: 	if ($args->{'newid'}=~/^\s*$/) {
 5909: 	    &scan_data($scan_data,"$whichline.user",
 5910: 		       $args->{'username'}.':'.$args->{'domain'});
 5911: 	}
 5912:     } elsif ($field eq 'CODE') {
 5913: 	if ($args->{'CODE_ignore_dup'}) {
 5914: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5915: 	}
 5916: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5917: 	if ($args->{'CODE'} ne 'use_unfound') {
 5918: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5919: 		return ($line,1,'New CODE value too large');
 5920: 	    }
 5921: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5922: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5923: 	    }
 5924: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5925: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5926: 	}
 5927:     } elsif ($field eq 'answer') {
 5928: 	my $length=$scantron_config->{'Qlength'};
 5929: 	my $off=$scantron_config->{'Qoff'};
 5930: 	my $on=$scantron_config->{'Qon'};
 5931: 	my $answer=${off}x$length;
 5932: 	if ($args->{'response'} eq 'none') {
 5933: 	    &scan_data($scan_data,
 5934: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5935: 	} else {
 5936: 	    if ($on eq 'letter') {
 5937: 		my @alphabet=('A'..'Z');
 5938: 		$answer=$alphabet[$args->{'response'}];
 5939: 	    } elsif ($on eq 'number') {
 5940: 		$answer=$args->{'response'}+1;
 5941: 		if ($answer == 10) { $answer = '0'; }
 5942: 	    } else {
 5943: 		substr($answer,$args->{'response'},1)=$on;
 5944: 	    }
 5945: 	    &scan_data($scan_data,
 5946: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5947: 	}
 5948: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5949: 	substr($line,$where-1,$length)=$answer;
 5950:     }
 5951:     return $line;
 5952: }
 5953: 
 5954: =pod
 5955: 
 5956: =item scan_data
 5957: 
 5958:     Edit or look up  an item in the scan_data hash.
 5959: 
 5960:   Arguments:
 5961:     $scan_data  - The hash (see scantron_getfile)
 5962:     $key        - shorthand of the key to edit (actual key is
 5963:                   scantronfilename_key).
 5964:     $data        - New value of the hash entry.
 5965:     $delete      - If true, the entry is removed from the hash.
 5966: 
 5967:   Returns:
 5968:     The new value of the hash table field (undefined if deleted).
 5969: 
 5970: =cut
 5971: 
 5972: 
 5973: sub scan_data {
 5974:     my ($scan_data,$key,$value,$delete)=@_;
 5975:     my $filename=$env{'form.scantron_selectfile'};
 5976:     if (defined($value)) {
 5977: 	$scan_data->{$filename.'_'.$key} = $value;
 5978:     }
 5979:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5980:     return $scan_data->{$filename.'_'.$key};
 5981: }
 5982: 
 5983: # ----- These first few routines are general use routines.----
 5984: 
 5985: # Return the number of occurences of a pattern in a string.
 5986: 
 5987: sub occurence_count {
 5988:     my ($string, $pattern) = @_;
 5989: 
 5990:     my @matches = ($string =~ /$pattern/g);
 5991: 
 5992:     return scalar(@matches);
 5993: }
 5994: 
 5995: 
 5996: # Take a string known to have digits and convert all the
 5997: # digits into letters in the range J,A..I.
 5998: 
 5999: sub digits_to_letters {
 6000:     my ($input) = @_;
 6001: 
 6002:     my @alphabet = ('J', 'A'..'I');
 6003: 
 6004:     my @input    = split(//, $input);
 6005:     my $output ='';
 6006:     for (my $i = 0; $i < scalar(@input); $i++) {
 6007: 	if ($input[$i] =~ /\d/) {
 6008: 	    $output .= $alphabet[$input[$i]];
 6009: 	} else {
 6010: 	    $output .= $input[$i];
 6011: 	}
 6012:     }
 6013:     return $output;
 6014: }
 6015: 
 6016: =pod 
 6017: 
 6018: =item scantron_parse_scanline
 6019: 
 6020:   Decodes a scanline from the selected scantron file
 6021: 
 6022:  Arguments:
 6023:     line             - The text of the scantron file line to process
 6024:     whichline        - Line number
 6025:     scantron_config  - Hash describing the format of the scantron lines.
 6026:     scan_data        - Hash of extra information about the scanline
 6027:                        (see scantron_getfile for more information)
 6028:     just_header      - True if should not process question answers but only
 6029:                        the stuff to the left of the answers.
 6030:     randomorder      - True if randomorder in use
 6031:     randompick       - True if randompick in use
 6032:     sequence         - Exam folder URL
 6033:     master_seq       - Ref to array containing symbs in exam folder
 6034:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6035:                        (corresponding values are resource objects)
 6036:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6037:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6038:                        are refs to an array of resource objects, ordered
 6039:                        according to order used for CODE, when randomorder
 6040:                        and or randompick are in use.
 6041:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6042:                        for current line to question number used for same question
 6043:                         in "Master Sequence" (as seen by Course Coordinator).
 6044:     startline        - Ref to hash where key is question number (0 is first)
 6045:                        and value is number of first bubble line for current 
 6046:                        student or code-based randompick and/or randomorder.
 6047:     totalref         - Ref of scalar used to score total number of bubble
 6048:                        lines needed for responses in a scan line (used when
 6049:                        randompick in use. 
 6050: 
 6051:  Returns:
 6052:    Hash containing the result of parsing the scanline
 6053: 
 6054:    Keys are all proceeded by the string 'scantron.'
 6055: 
 6056:        CODE    - the CODE in use for this scanline
 6057:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6058:                  by the operator
 6059:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6060:                             CODEs were selected, but the usage has been
 6061:                             forced by the operator
 6062:        ID  - student/employee ID
 6063:        PaperID - if used, the ID number printed on the sheet when the 
 6064:                  paper was scanned
 6065:        FirstName - first name from the sheet
 6066:        LastName  - last name from the sheet
 6067: 
 6068:      if just_header was not true these key may also exist
 6069: 
 6070:        missingerror - a list of bubble ranges that are considered to be answers
 6071:                       to a single question that don't have any bubbles filled in.
 6072:                       Of the form questionnumber:firstbubblenumber:count.
 6073:        doubleerror  - a list of bubble ranges that are considered to be answers
 6074:                       to a single question that have more than one bubble filled in.
 6075:                       Of the form questionnumber::firstbubblenumber:count
 6076:    
 6077:                 In the above, count is the number of bubble responses in the
 6078:                 input line needed to represent the possible answers to the question.
 6079:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6080:                 per line would have count = 2.
 6081: 
 6082:        maxquest     - the number of the last bubble line that was parsed
 6083: 
 6084:        (<number> starts at 1)
 6085:        <number>.answer - zero or more letters representing the selected
 6086:                          letters from the scanline for the bubble line 
 6087:                          <number>.
 6088:                          if blank there was either no bubble or there where
 6089:                          multiple bubbles, (consult the keys missingerror and
 6090:                          doubleerror if this is an error condition)
 6091: 
 6092: =cut
 6093: 
 6094: sub scantron_parse_scanline {
 6095:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6096:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6097:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6098: 
 6099:     my %record;
 6100:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6101:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6102: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6103: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6104: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6105: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6106: 	    $record{'scantron.CODE'}=substr($data,
 6107: 					    $$scantron_config{'CODEstart'}-1,
 6108: 					    $$scantron_config{'CODElength'});
 6109: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6110: 		$record{'scantron.useCODE'}=1;
 6111: 	    }
 6112: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6113: 		$record{'scantron.CODE_ignore_dup'}=1;
 6114: 	    }
 6115: 	} else {
 6116: 	    #FIXME interpret first N questions
 6117: 	}
 6118:     }
 6119:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6120: 				  $$scantron_config{'IDlength'});
 6121:     $record{'scantron.PaperID'}=
 6122: 	substr($data,$$scantron_config{'PaperID'}-1,
 6123: 	       $$scantron_config{'PaperIDlength'});
 6124:     $record{'scantron.FirstName'}=
 6125: 	substr($data,$$scantron_config{'FirstName'}-1,
 6126: 	       $$scantron_config{'FirstNamelength'});
 6127:     $record{'scantron.LastName'}=
 6128: 	substr($data,$$scantron_config{'LastName'}-1,
 6129: 	       $$scantron_config{'LastNamelength'});
 6130:     if ($just_header) { return \%record; }
 6131: 
 6132:     my @alphabet=('A'..'Z');
 6133:     my $questnum=0;
 6134:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6135: 
 6136:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6137:     if ($randompick || $randomorder) {
 6138:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6139:                                          $master_seq,$symb_to_resource,
 6140:                                          $partids_by_symb,$orderedforcode,
 6141:                                          $respnumlookup,$startline);
 6142:         if ($total) {
 6143:             $lastpos = $total*$$scantron_config{'Qlength'};
 6144:         }
 6145:         if (ref($totalref)) {
 6146:             $$totalref = $total;
 6147:         }
 6148:     }
 6149:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6150:     chomp($questions);		# Get rid of any trailing \n.
 6151:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6152:     while (length($questions)) {
 6153:         my $answers_needed;
 6154:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6155:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6156:         } else {
 6157:             $answers_needed = $bubble_lines_per_response{$questnum};
 6158:         }
 6159:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6160:                              || 1;
 6161:         $questnum++;
 6162:         my $quest_id = $questnum;
 6163:         my $currentquest = substr($questions,0,$answer_length);
 6164:         $questions       = substr($questions,$answer_length);
 6165:         if (length($currentquest) < $answer_length) { next; }
 6166: 
 6167:         my $subdivided;
 6168:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6169:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6170:         } else {
 6171:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6172:         }
 6173:         if ($subdivided =~ /,/) {
 6174:             my $subquestnum = 1;
 6175:             my $subquestions = $currentquest;
 6176:             my @subanswers_needed = split(/,/,$subdivided);
 6177:             foreach my $subans (@subanswers_needed) {
 6178:                 my $subans_length =
 6179:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6180:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6181:                 $subquestions   = substr($subquestions,$subans_length);
 6182:                 $quest_id = "$questnum.$subquestnum";
 6183:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6184:                     ($$scantron_config{'Qon'} eq 'number')) {
 6185:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6186:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6187:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6188:                         $randomorder,$randompick,$respnumlookup);
 6189:                 } else {
 6190:                     $ansnum = &scantron_validator_positional($ansnum,
 6191:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6192:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6193:                         $randomorder,$randompick,$respnumlookup);
 6194:                 }
 6195:                 $subquestnum ++;
 6196:             }
 6197:         } else {
 6198:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6199:                 ($$scantron_config{'Qon'} eq 'number')) {
 6200:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6201:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6202:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6203:                     $randomorder,$randompick,$respnumlookup);
 6204:             } else {
 6205:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6206:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6207:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6208:                     $randomorder,$randompick,$respnumlookup);
 6209:             }
 6210:         }
 6211:     }
 6212:     $record{'scantron.maxquest'}=$questnum;
 6213:     return \%record;
 6214: }
 6215: 
 6216: sub get_master_seq {
 6217:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6218:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6219:                    (ref($symb_to_resource) eq 'HASH'));
 6220:     my $resource_error;
 6221:     foreach my $resource (@{$resources}) {
 6222:         my $ressymb;
 6223:         if (ref($resource)) {
 6224:             $ressymb = $resource->symb();
 6225:             push(@{$master_seq},$ressymb);
 6226:             $symb_to_resource->{$ressymb} = $resource;
 6227:         } else {
 6228:             $resource_error = 1;
 6229:             last;
 6230:         }
 6231:     }
 6232:     return $resource_error;
 6233: }
 6234: 
 6235: sub get_respnum_lookups {
 6236:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6237:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6238:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6239:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6240:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6241:                    (ref($startline) eq 'HASH'));
 6242:     my ($user,$scancode);
 6243:     if ((exists($record->{'scantron.CODE'})) &&
 6244:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6245:         $scancode = $record->{'scantron.CODE'};
 6246:     } else {
 6247:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6248:     }
 6249:     my @mapresources =
 6250:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6251:                      $orderedforcode);
 6252:     my $total = 0;
 6253:     my $count = 0;
 6254:     foreach my $resource (@mapresources) {
 6255:         my $id = $resource->id();
 6256:         my $symb = $resource->symb();
 6257:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6258:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6259:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6260:                 if ($respnum ne '') {
 6261:                     $respnumlookup->{$count} = $respnum;
 6262:                     $startline->{$count} = $total;
 6263:                     $total += $bubble_lines_per_response{$respnum};
 6264:                     $count ++;
 6265:                 }
 6266:             }
 6267:         }
 6268:     }
 6269:     return $total;
 6270: }
 6271: 
 6272: sub scantron_validator_lettnum {
 6273:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6274:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6275:         $randompick,$respnumlookup) = @_;
 6276: 
 6277:     # Qon 'letter' implies for each slot in currquest we have:
 6278:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6279:     #    about anything else (esp. a value of Qoff) for missing
 6280:     #    bubbles.
 6281:     #
 6282:     # Qon 'number' implies each slot gives a digit that indexes the
 6283:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6284:     #    and * or ? for double bubbles on a single line.
 6285:     #
 6286: 
 6287:     my $matchon;
 6288:     if ($$scantron_config{'Qon'} eq 'letter') {
 6289:         $matchon = '[A-Z]';
 6290:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6291:         $matchon = '\d';
 6292:     }
 6293:     my $occurrences = 0;
 6294:     my $responsenum = $questnum-1;
 6295:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6296:        $responsenum = $respnumlookup->{$questnum-1}
 6297:     }
 6298:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6299:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6300:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6301:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6302:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6303:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6304:         my @singlelines = split('',$currquest);
 6305:         foreach my $entry (@singlelines) {
 6306:             $occurrences = &occurence_count($entry,$matchon);
 6307:             if ($occurrences > 1) {
 6308:                 last;
 6309:             }
 6310:         }
 6311:     } else {
 6312:         $occurrences = &occurence_count($currquest,$matchon); 
 6313:     }
 6314:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6315:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6316:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6317:             my $bubble = substr($currquest,$ans,1);
 6318:             if ($bubble =~ /$matchon/ ) {
 6319:                 if ($$scantron_config{'Qon'} eq 'number') {
 6320:                     if ($bubble == 0) {
 6321:                         $bubble = 10; 
 6322:                     }
 6323:                     $record->{"scantron.$ansnum.answer"} = 
 6324:                         $alphabet->[$bubble-1];
 6325:                 } else {
 6326:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6327:                 }
 6328:             } else {
 6329:                 $record->{"scantron.$ansnum.answer"}='';
 6330:             }
 6331:             $ansnum++;
 6332:         }
 6333:     } elsif (!defined($currquest)
 6334:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6335:             || (&occurence_count($currquest,$matchon) == 0)) {
 6336:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6337:             $record->{"scantron.$ansnum.answer"}='';
 6338:             $ansnum++;
 6339:         }
 6340:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6341:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6342:         }
 6343:     } else {
 6344:         if ($$scantron_config{'Qon'} eq 'number') {
 6345:             $currquest = &digits_to_letters($currquest);            
 6346:         }
 6347:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6348:             my $bubble = substr($currquest,$ans,1);
 6349:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6350:             $ansnum++;
 6351:         }
 6352:     }
 6353:     return $ansnum;
 6354: }
 6355: 
 6356: sub scantron_validator_positional {
 6357:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6358:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6359:         $randomorder,$randompick,$respnumlookup) = @_;
 6360: 
 6361:     # Otherwise there's a positional notation;
 6362:     # each bubble line requires Qlength items, and there are filled in
 6363:     # bubbles for each case where there 'Qon' characters.
 6364:     #
 6365: 
 6366:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6367: 
 6368:     # If the split only gives us one element.. the full length of the
 6369:     # answer string, no bubbles are filled in:
 6370: 
 6371:     if ($answers_needed eq '') {
 6372:         return;
 6373:     }
 6374: 
 6375:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6376:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6377:             $record->{"scantron.$ansnum.answer"}='';
 6378:             $ansnum++;
 6379:         }
 6380:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6381:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6382:         }
 6383:     } elsif (scalar(@array) == 2) {
 6384:         my $location = length($array[0]);
 6385:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6386:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6387:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6388:             if ($ans eq $line_num) {
 6389:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6390:             } else {
 6391:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6392:             }
 6393:             $ansnum++;
 6394:          }
 6395:     } else {
 6396:         #  If there's more than one instance of a bubble character
 6397:         #  That's a double bubble; with positional notation we can
 6398:         #  record all the bubbles filled in as well as the
 6399:         #  fact this response consists of multiple bubbles.
 6400:         #
 6401:         my $responsenum = $questnum-1;
 6402:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6403:             $responsenum = $respnumlookup->{$questnum-1}
 6404:         }
 6405:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6406:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6407:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6408:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6409:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6410:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6411:             my $doubleerror = 0;
 6412:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6413:                    (!$doubleerror)) {
 6414:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6415:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6416:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6417:                if (length(@currarray) > 2) {
 6418:                    $doubleerror = 1;
 6419:                } 
 6420:             }
 6421:             if ($doubleerror) {
 6422:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6423:             }
 6424:         } else {
 6425:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6426:         }
 6427:         my $item = $ansnum;
 6428:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6429:             $record->{"scantron.$item.answer"} = '';
 6430:             $item ++;
 6431:         }
 6432: 
 6433:         my @ans=@array;
 6434:         my $i=0;
 6435:         my $increment = 0;
 6436:         while ($#ans) {
 6437:             $i+=length($ans[0]) + $increment;
 6438:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6439:             my $bubble = $i%$$scantron_config{'Qlength'};
 6440:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6441:             shift(@ans);
 6442:             $increment = 1;
 6443:         }
 6444:         $ansnum += $answers_needed;
 6445:     }
 6446:     return $ansnum;
 6447: }
 6448: 
 6449: =pod
 6450: 
 6451: =item scantron_add_delay
 6452: 
 6453:    Adds an error message that occurred during the grading phase to a
 6454:    queue of messages to be shown after grading pass is complete
 6455: 
 6456:  Arguments:
 6457:    $delayqueue  - arrary ref of hash ref of error messages
 6458:    $scanline    - the scanline that caused the error
 6459:    $errormesage - the error message
 6460:    $errorcode   - a numeric code for the error
 6461: 
 6462:  Side Effects:
 6463:    updates the $delayqueue to have a new hash ref of the error
 6464: 
 6465: =cut
 6466: 
 6467: sub scantron_add_delay {
 6468:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6469:     push(@$delayqueue,
 6470: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6471: 	  'ecode' => $errorcode }
 6472: 	 );
 6473: }
 6474: 
 6475: =pod
 6476: 
 6477: =item scantron_find_student
 6478: 
 6479:    Finds the username for the current scanline
 6480: 
 6481:   Arguments:
 6482:    $scantron_record - hash result from scantron_parse_scanline
 6483:    $scan_data       - hash of correction information 
 6484:                       (see &scantron_getfile() form more information)
 6485:    $idmap           - hash from &username_to_idmap()
 6486:    $line            - number of current scanline
 6487:  
 6488:   Returns:
 6489:    Either 'username:domain' or undef if unknown
 6490: 
 6491: =cut
 6492: 
 6493: sub scantron_find_student {
 6494:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6495:     my $scanID=$$scantron_record{'scantron.ID'};
 6496:     if ($scanID =~ /^\s*$/) {
 6497:  	return &scan_data($scan_data,"$line.user");
 6498:     }
 6499:     foreach my $id (keys(%$idmap)) {
 6500:  	if (lc($id) eq lc($scanID)) {
 6501:  	    return $$idmap{$id};
 6502:  	}
 6503:     }
 6504:     return undef;
 6505: }
 6506: 
 6507: =pod
 6508: 
 6509: =item scantron_filter
 6510: 
 6511:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6512:    hidden resources was selected
 6513: 
 6514: =cut
 6515: 
 6516: sub scantron_filter {
 6517:     my ($curres)=@_;
 6518: 
 6519:     if (ref($curres) && $curres->is_problem()) {
 6520: 	# if the user has asked to not have either hidden
 6521: 	# or 'randomout' controlled resources to be graded
 6522: 	# don't include them
 6523: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6524: 	    && $curres->randomout) {
 6525: 	    return 0;
 6526: 	}
 6527: 	return 1;
 6528:     }
 6529:     return 0;
 6530: }
 6531: 
 6532: =pod
 6533: 
 6534: =item scantron_process_corrections
 6535: 
 6536:    Gets correction information out of submitted form data and corrects
 6537:    the scanline
 6538: 
 6539: =cut
 6540: 
 6541: sub scantron_process_corrections {
 6542:     my ($r) = @_;
 6543:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6544:     my ($scanlines,$scan_data)=&scantron_getfile();
 6545:     my $classlist=&Apache::loncoursedata::get_classlist();
 6546:     my $which=$env{'form.scantron_line'};
 6547:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6548:     my ($skip,$err,$errmsg);
 6549:     if ($env{'form.scantron_skip_record'}) {
 6550: 	$skip=1;
 6551:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6552: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6553: 	    $env{'form.scantron_domain'};
 6554: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6555: 	($line,$err,$errmsg)=
 6556: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6557: 				     'ID',{'newid'=>$newid,
 6558: 				    'username'=>$env{'form.scantron_username'},
 6559: 				    'domain'=>$env{'form.scantron_domain'}});
 6560:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6561: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6562: 	my $newCODE;
 6563: 	my %args;
 6564: 	if      ($resolution eq 'use_unfound') {
 6565: 	    $newCODE='use_unfound';
 6566: 	} elsif ($resolution eq 'use_found') {
 6567: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6568: 	} elsif ($resolution eq 'use_typed') {
 6569: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6570: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6571: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6572: 	}
 6573: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6574: 	    $args{'CODE_ignore_dup'}=1;
 6575: 	}
 6576: 	$args{'CODE'}=$newCODE;
 6577: 	($line,$err,$errmsg)=
 6578: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6579: 				     'CODE',\%args);
 6580:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6581: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6582: 	    ($line,$err,$errmsg)=
 6583: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6584: 					 $which,'answer',
 6585: 					 { 'question'=>$question,
 6586: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6587:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6588: 	    if ($err) { last; }
 6589: 	}
 6590:     }
 6591:     if ($err) {
 6592: 	$r->print(
 6593:             '<p class="LC_error">'
 6594:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6595:                 $errmsg)
 6596:            .'</p>');
 6597:     } else {
 6598: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6599: 	&scantron_putfile($scanlines,$scan_data);
 6600:     }
 6601: }
 6602: 
 6603: =pod
 6604: 
 6605: =item reset_skipping_status
 6606: 
 6607:    Forgets the current set of remember skipped scanlines (and thus
 6608:    reverts back to considering all lines in the
 6609:    scantron_skipped_<filename> file)
 6610: 
 6611: =cut
 6612: 
 6613: sub reset_skipping_status {
 6614:     my ($scanlines,$scan_data)=&scantron_getfile();
 6615:     &scan_data($scan_data,'remember_skipping',undef,1);
 6616:     &scantron_putfile(undef,$scan_data);
 6617: }
 6618: 
 6619: =pod
 6620: 
 6621: =item start_skipping
 6622: 
 6623:    Marks a scanline to be skipped. 
 6624: 
 6625: =cut
 6626: 
 6627: sub start_skipping {
 6628:     my ($scan_data,$i)=@_;
 6629:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6630:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6631: 	$remembered{$i}=2;
 6632:     } else {
 6633: 	$remembered{$i}=1;
 6634:     }
 6635:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6636: }
 6637: 
 6638: =pod
 6639: 
 6640: =item should_be_skipped
 6641: 
 6642:    Checks whether a scanline should be skipped.
 6643: 
 6644: =cut
 6645: 
 6646: sub should_be_skipped {
 6647:     my ($scanlines,$scan_data,$i)=@_;
 6648:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6649: 	# not redoing old skips
 6650: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6651: 	return 0;
 6652:     }
 6653:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6654: 
 6655:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6656: 	return 0;
 6657:     }
 6658:     return 1;
 6659: }
 6660: 
 6661: =pod
 6662: 
 6663: =item remember_current_skipped
 6664: 
 6665:    Discovers what scanlines are in the scantron_skipped_<filename>
 6666:    file and remembers them into scan_data for later use.
 6667: 
 6668: =cut
 6669: 
 6670: sub remember_current_skipped {
 6671:     my ($scanlines,$scan_data)=&scantron_getfile();
 6672:     my %to_remember;
 6673:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6674: 	if ($scanlines->{'skipped'}[$i]) {
 6675: 	    $to_remember{$i}=1;
 6676: 	}
 6677:     }
 6678: 
 6679:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6680:     &scantron_putfile(undef,$scan_data);
 6681: }
 6682: 
 6683: =pod
 6684: 
 6685: =item check_for_error
 6686: 
 6687:     Checks if there was an error when attempting to remove a specific
 6688:     scantron_.. bubblesheet data file. Prints out an error if
 6689:     something went wrong.
 6690: 
 6691: =cut
 6692: 
 6693: sub check_for_error {
 6694:     my ($r,$result)=@_;
 6695:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6696: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6697:     }
 6698: }
 6699: 
 6700: =pod
 6701: 
 6702: =item scantron_warning_screen
 6703: 
 6704:    Interstitial screen to make sure the operator has selected the
 6705:    correct options before we start the validation phase.
 6706: 
 6707: =cut
 6708: 
 6709: sub scantron_warning_screen {
 6710:     my ($button_text)=@_;
 6711:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6712:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6713:     my $CODElist;
 6714:     if ($scantron_config{'CODElocation'} &&
 6715: 	$scantron_config{'CODEstart'} &&
 6716: 	$scantron_config{'CODElength'}) {
 6717: 	$CODElist=$env{'form.scantron_CODElist'};
 6718: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6719: 	$CODElist=
 6720: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6721: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6722:     }
 6723:     my $lastbubblepoints;
 6724:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6725:         $lastbubblepoints =
 6726:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6727:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6728:     }
 6729:     return ('
 6730: <p>
 6731: <span class="LC_warning">
 6732: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6733: </p>
 6734: <table>
 6735: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6736: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6737: '.$CODElist.$lastbubblepoints.'
 6738: </table>
 6739: <br />
 6740: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 6741: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 6742: 
 6743: <br />
 6744: ');
 6745: }
 6746: 
 6747: =pod
 6748: 
 6749: =item scantron_do_warning
 6750: 
 6751:    Check if the operator has picked something for all required
 6752:    fields. Error out if something is missing.
 6753: 
 6754: =cut
 6755: 
 6756: sub scantron_do_warning {
 6757:     my ($r)=@_;
 6758:     my ($symb)=&get_symb($r);
 6759:     if (!$symb) {return '';}
 6760:     my $default_form_data=&defaultFormData($symb);
 6761:     $r->print(&scantron_form_start().$default_form_data);
 6762:     if ( $env{'form.selectpage'} eq '' ||
 6763: 	 $env{'form.scantron_selectfile'} eq '' ||
 6764: 	 $env{'form.scantron_format'} eq '' ) {
 6765: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6766: 	if ( $env{'form.selectpage'} eq '') {
 6767: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6768: 	} 
 6769: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6770: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6771: 	} 
 6772: 	if ( $env{'form.scantron_format'} eq '') {
 6773: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6774: 	} 
 6775:     } else {
 6776: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6777:         my $bubbledbyhand=&hand_bubble_option();
 6778: 	$r->print('
 6779: '.$warning.$bubbledbyhand.'
 6780: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6781: <input type="hidden" name="command" value="scantron_validate" />
 6782: ');
 6783:     }
 6784:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6785:     return '';
 6786: }
 6787: 
 6788: =pod
 6789: 
 6790: =item scantron_form_start
 6791: 
 6792:     html hidden input for remembering all selected grading options
 6793: 
 6794: =cut
 6795: 
 6796: sub scantron_form_start {
 6797:     my ($max_bubble)=@_;
 6798:     my $result= <<SCANTRONFORM;
 6799: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6800:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6801:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6802:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6803:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6804:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6805:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6806:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6807:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6808:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6809: SCANTRONFORM
 6810: 
 6811:   my $line = 0;
 6812:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6813:        my $chunk =
 6814: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6815:        $chunk .=
 6816: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6817:        $chunk .= 
 6818:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6819:        $chunk .=
 6820:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6821:        $chunk .=
 6822:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6823:        $result .= $chunk;
 6824:        $line++;
 6825:     }
 6826:     return $result;
 6827: }
 6828: 
 6829: =pod
 6830: 
 6831: =item scantron_validate_file
 6832: 
 6833:     Dispatch routine for doing validation of a bubblesheet data file.
 6834: 
 6835:     Also processes any necessary information resets that need to
 6836:     occur before validation begins (ignore previous corrections,
 6837:     restarting the skipped records processing)
 6838: 
 6839: =cut
 6840: 
 6841: sub scantron_validate_file {
 6842:     my ($r) = @_;
 6843:     my ($symb)=&get_symb($r);
 6844:     if (!$symb) {return '';}
 6845:     my $default_form_data=&defaultFormData($symb);
 6846:     
 6847:     # do the detection of only doing skipped records first before we delete
 6848:     # them when doing the corrections reset
 6849:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6850: 	&reset_skipping_status();
 6851:     }
 6852:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6853: 	&remember_current_skipped();
 6854: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6855:     }
 6856: 
 6857:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6858: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6859: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6860: 	&check_for_error($r,&scantron_remove_scan_data());
 6861: 	$env{'form.scantron_options_ignore'}='done';
 6862:     }
 6863: 
 6864:     if ($env{'form.scantron_corrections'}) {
 6865: 	&scantron_process_corrections($r);
 6866:     }
 6867:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6868:     #get the student pick code ready
 6869:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6870:     my $nav_error;
 6871:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6872:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6873:     if ($nav_error) {
 6874:         $r->print(&navmap_errormsg());
 6875:         return '';
 6876:     }
 6877:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6878:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6879:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6880:     }
 6881:     $r->print($result);
 6882:     
 6883:     my @validate_phases=( 'sequence',
 6884: 			  'ID',
 6885: 			  'CODE',
 6886: 			  'doublebubble',
 6887: 			  'missingbubbles');
 6888:     if (!$env{'form.validatepass'}) {
 6889: 	$env{'form.validatepass'} = 0;
 6890:     }
 6891:     my $currentphase=$env{'form.validatepass'};
 6892: 
 6893: 
 6894:     my $stop=0;
 6895:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6896: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6897: 	$r->rflush();
 6898: 
 6899: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6900: 	{
 6901: 	    no strict 'refs';
 6902: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6903: 	}
 6904:     }
 6905:     if (!$stop) {
 6906: 	my $warning=&scantron_warning_screen('Start Grading');
 6907: 	$r->print(&mt('Validation process complete.').'<br />'.
 6908:                   $warning.
 6909:                   &mt('Perform verification for each student after storage of submissions?').
 6910:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6911:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6912:                   ('&nbsp;'x3).'<label>'.
 6913:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6914:                   '</label></span><br />'.
 6915:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6916:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6917:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6918:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6919:     } else {
 6920: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6921: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6922:     }
 6923:     if ($stop) {
 6924: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6925: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6926: 	    $r->print(' '.&mt('this error').' <br />');
 6927: 
 6928: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6929: 	} else {
 6930:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6931: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6932:             } else {
 6933:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6934:             }
 6935: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6936: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6937: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6938: 	}
 6939:     }
 6940:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6941:     return '';
 6942: }
 6943: 
 6944: 
 6945: =pod
 6946: 
 6947: =item scantron_remove_file
 6948: 
 6949:    Removes the requested bubblesheet data file, makes sure that
 6950:    scantron_original_<filename> is never removed
 6951: 
 6952: 
 6953: =cut
 6954: 
 6955: sub scantron_remove_file {
 6956:     my ($which)=@_;
 6957:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6958:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6959:     my $file='scantron_';
 6960:     if ($which eq 'corrected' || $which eq 'skipped') {
 6961: 	$file.=$which.'_';
 6962:     } else {
 6963: 	return 'refused';
 6964:     }
 6965:     $file.=$env{'form.scantron_selectfile'};
 6966:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6967: }
 6968: 
 6969: 
 6970: =pod
 6971: 
 6972: =item scantron_remove_scan_data
 6973: 
 6974:    Removes all scan_data correction for the requested bubblesheet
 6975:    data file.  (In the case that both the are doing skipped records we need
 6976:    to remember the old skipped lines for the time being so that element
 6977:    persists for a while.)
 6978: 
 6979: =cut
 6980: 
 6981: sub scantron_remove_scan_data {
 6982:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6983:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6984:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6985:     my @todelete;
 6986:     my $filename=$env{'form.scantron_selectfile'};
 6987:     foreach my $key (@keys) {
 6988: 	if ($key=~/^\Q$filename\E_/) {
 6989: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6990: 		$key=~/remember_skipping/) {
 6991: 		next;
 6992: 	    }
 6993: 	    push(@todelete,$key);
 6994: 	}
 6995:     }
 6996:     my $result;
 6997:     if (@todelete) {
 6998: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6999: 				       \@todelete,$cdom,$cname);
 7000:     } else {
 7001: 	$result = 'ok';
 7002:     }
 7003:     return $result;
 7004: }
 7005: 
 7006: 
 7007: =pod
 7008: 
 7009: =item scantron_getfile
 7010: 
 7011:     Fetches the requested bubblesheet data file (all 3 versions), and
 7012:     the scan_data hash
 7013:   
 7014:   Arguments:
 7015:     None
 7016: 
 7017:   Returns:
 7018:     2 hash references
 7019: 
 7020:      - first one has 
 7021:          orig      -
 7022:          corrected -
 7023:          skipped   -  each of which points to an array ref of the specified
 7024:                       file broken up into individual lines
 7025:          count     - number of scanlines
 7026:  
 7027:      - second is the scan_data hash possible keys are
 7028:        ($number refers to scanline numbered $number and thus the key affects
 7029:         only that scanline
 7030:         $bubline refers to the specific bubble line element and the aspects
 7031:         refers to that specific bubble line element)
 7032: 
 7033:        $number.user - username:domain to use
 7034:        $number.CODE_ignore_dup 
 7035:                     - ignore the duplicate CODE error 
 7036:        $number.useCODE
 7037:                     - use the CODE in the scanline as is
 7038:        $number.no_bubble.$bubline
 7039:                     - it is valid that there is no bubbled in bubble
 7040:                       at $number $bubline
 7041:        remember_skipping
 7042:                     - a frozen hash containing keys of $number and values
 7043:                       of either 
 7044:                         1 - we are on a 'do skipped records pass' and plan
 7045:                             on processing this line
 7046:                         2 - we are on a 'do skipped records pass' and this
 7047:                             scanline has been marked to skip yet again
 7048: 
 7049: =cut
 7050: 
 7051: sub scantron_getfile {
 7052:     #FIXME really would prefer a scantron directory
 7053:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7054:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7055:     my $lines;
 7056:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7057: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7058:     my %scanlines;
 7059:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7060:     my $temp=$scanlines{'orig'};
 7061:     $scanlines{'count'}=$#$temp;
 7062: 
 7063:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7064: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7065:     if ($lines eq '-1') {
 7066: 	$scanlines{'corrected'}=[];
 7067:     } else {
 7068: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7069:     }
 7070:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7071: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7072:     if ($lines eq '-1') {
 7073: 	$scanlines{'skipped'}=[];
 7074:     } else {
 7075: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7076:     }
 7077:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7078:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7079:     my %scan_data = @tmp;
 7080:     return (\%scanlines,\%scan_data);
 7081: }
 7082: 
 7083: =pod
 7084: 
 7085: =item lonnet_putfile
 7086: 
 7087:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7088: 
 7089:  Arguments:
 7090:    $contents - data to store
 7091:    $filename - filename to store $contents into
 7092: 
 7093:  Returns:
 7094:    result value from &Apache::lonnet::finishuserfileupload
 7095: 
 7096: =cut
 7097: 
 7098: sub lonnet_putfile {
 7099:     my ($contents,$filename)=@_;
 7100:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7101:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7102:     $env{'form.sillywaytopassafilearound'}=$contents;
 7103:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7104: 
 7105: }
 7106: 
 7107: =pod
 7108: 
 7109: =item scantron_putfile
 7110: 
 7111:     Stores the current version of the bubblesheet data files, and the
 7112:     scan_data hash. (Does not modify the original version only the
 7113:     corrected and skipped versions.
 7114: 
 7115:  Arguments:
 7116:     $scanlines - hash ref that looks like the first return value from
 7117:                  &scantron_getfile()
 7118:     $scan_data - hash ref that looks like the second return value from
 7119:                  &scantron_getfile()
 7120: 
 7121: =cut
 7122: 
 7123: sub scantron_putfile {
 7124:     my ($scanlines,$scan_data) = @_;
 7125:     #FIXME really would prefer a scantron directory
 7126:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7127:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7128:     if ($scanlines) {
 7129: 	my $prefix='scantron_';
 7130: # no need to update orig, shouldn't change
 7131: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7132: #		    $env{'form.scantron_selectfile'});
 7133: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7134: 			$prefix.'corrected_'.
 7135: 			$env{'form.scantron_selectfile'});
 7136: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7137: 			$prefix.'skipped_'.
 7138: 			$env{'form.scantron_selectfile'});
 7139:     }
 7140:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7141: }
 7142: 
 7143: =pod
 7144: 
 7145: =item scantron_get_line
 7146: 
 7147:    Returns the correct version of the scanline
 7148: 
 7149:  Arguments:
 7150:     $scanlines - hash ref that looks like the first return value from
 7151:                  &scantron_getfile()
 7152:     $scan_data - hash ref that looks like the second return value from
 7153:                  &scantron_getfile()
 7154:     $i         - number of the requested line (starts at 0)
 7155: 
 7156:  Returns:
 7157:    A scanline, (either the original or the corrected one if it
 7158:    exists), or undef if the requested scanline should be
 7159:    skipped. (Either because it's an skipped scanline, or it's an
 7160:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7161:    pass.
 7162: 
 7163: =cut
 7164: 
 7165: sub scantron_get_line {
 7166:     my ($scanlines,$scan_data,$i)=@_;
 7167:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7168:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7169:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7170:     return $scanlines->{'orig'}[$i]; 
 7171: }
 7172: 
 7173: =pod
 7174: 
 7175: =item scantron_todo_count
 7176: 
 7177:     Counts the number of scanlines that need processing.
 7178: 
 7179:  Arguments:
 7180:     $scanlines - hash ref that looks like the first return value from
 7181:                  &scantron_getfile()
 7182:     $scan_data - hash ref that looks like the second return value from
 7183:                  &scantron_getfile()
 7184: 
 7185:  Returns:
 7186:     $count - number of scanlines to process
 7187: 
 7188: =cut
 7189: 
 7190: sub get_todo_count {
 7191:     my ($scanlines,$scan_data)=@_;
 7192:     my $count=0;
 7193:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7194: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7195: 	if ($line=~/^[\s\cz]*$/) { next; }
 7196: 	$count++;
 7197:     }
 7198:     return $count;
 7199: }
 7200: 
 7201: =pod
 7202: 
 7203: =item scantron_put_line
 7204: 
 7205:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7206:     data file.
 7207: 
 7208:  Arguments:
 7209:     $scanlines - hash ref that looks like the first return value from
 7210:                  &scantron_getfile()
 7211:     $scan_data - hash ref that looks like the second return value from
 7212:                  &scantron_getfile()
 7213:     $i         - line number to update
 7214:     $newline   - contents of the updated scanline
 7215:     $skip      - if true make the line for skipping and update the
 7216:                  'skipped' file
 7217: 
 7218: =cut
 7219: 
 7220: sub scantron_put_line {
 7221:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7222:     if ($skip) {
 7223: 	$scanlines->{'skipped'}[$i]=$newline;
 7224: 	&start_skipping($scan_data,$i);
 7225: 	return;
 7226:     }
 7227:     $scanlines->{'corrected'}[$i]=$newline;
 7228: }
 7229: 
 7230: =pod
 7231: 
 7232: =item scantron_clear_skip
 7233: 
 7234:    Remove a line from the 'skipped' file
 7235: 
 7236:  Arguments:
 7237:     $scanlines - hash ref that looks like the first return value from
 7238:                  &scantron_getfile()
 7239:     $scan_data - hash ref that looks like the second return value from
 7240:                  &scantron_getfile()
 7241:     $i         - line number to update
 7242: 
 7243: =cut
 7244: 
 7245: sub scantron_clear_skip {
 7246:     my ($scanlines,$scan_data,$i)=@_;
 7247:     if (exists($scanlines->{'skipped'}[$i])) {
 7248: 	undef($scanlines->{'skipped'}[$i]);
 7249: 	return 1;
 7250:     }
 7251:     return 0;
 7252: }
 7253: 
 7254: =pod
 7255: 
 7256: =item scantron_filter_not_exam
 7257: 
 7258:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7259:    filter out resources that are not marked as 'exam' mode
 7260: 
 7261: =cut
 7262: 
 7263: sub scantron_filter_not_exam {
 7264:     my ($curres)=@_;
 7265:     
 7266:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7267: 	# if the user has asked to not have either hidden
 7268: 	# or 'randomout' controlled resources to be graded
 7269: 	# don't include them
 7270: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7271: 	    && $curres->randomout) {
 7272: 	    return 0;
 7273: 	}
 7274: 	return 1;
 7275:     }
 7276:     return 0;
 7277: }
 7278: 
 7279: =pod
 7280: 
 7281: =item scantron_validate_sequence
 7282: 
 7283:     Validates the selected sequence, checking for resource that are
 7284:     not set to exam mode.
 7285: 
 7286: =cut
 7287: 
 7288: sub scantron_validate_sequence {
 7289:     my ($r,$currentphase) = @_;
 7290: 
 7291:     my $navmap=Apache::lonnavmaps::navmap->new();
 7292:     unless (ref($navmap)) {
 7293:         $r->print(&navmap_errormsg());
 7294:         return (1,$currentphase);
 7295:     }
 7296:     my (undef,undef,$sequence)=
 7297: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7298: 
 7299:     my $map=$navmap->getResourceByUrl($sequence);
 7300: 
 7301:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7302:                                     value="ignore" />');
 7303:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7304: 	my @resources=
 7305: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7306: 	if (@resources) {
 7307: 	    $r->print('<p class="LC_warning">'
 7308:                .&mt('Some resources in the sequence currently are not set to'
 7309:                    .' exam mode. Grading these resources currently may not'
 7310:                    .' work correctly.')
 7311:                .'</p>'
 7312:             );
 7313: 	    return (1,$currentphase);
 7314: 	}
 7315:     }
 7316: 
 7317:     return (0,$currentphase+1);
 7318: }
 7319: 
 7320: 
 7321: 
 7322: sub scantron_validate_ID {
 7323:     my ($r,$currentphase) = @_;
 7324:     
 7325:     #get student info
 7326:     my $classlist=&Apache::loncoursedata::get_classlist();
 7327:     my %idmap=&username_to_idmap($classlist);
 7328: 
 7329:     #get scantron line setup
 7330:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7331:     my ($scanlines,$scan_data)=&scantron_getfile();
 7332: 
 7333:     my $nav_error;
 7334:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7335:     if ($nav_error) {
 7336:         $r->print(&navmap_errormsg());
 7337:         return(1,$currentphase);
 7338:     }
 7339: 
 7340:     my %found=('ids'=>{},'usernames'=>{});
 7341:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7342: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7343: 	if ($line=~/^[\s\cz]*$/) { next; }
 7344: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7345: 						 $scan_data);
 7346: 	my $id=$$scan_record{'scantron.ID'};
 7347: 	my $found;
 7348: 	foreach my $checkid (keys(%idmap)) {
 7349: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7350: 	}
 7351: 	if ($found) {
 7352: 	    my $username=$idmap{$found};
 7353: 	    if ($found{'ids'}{$found}) {
 7354: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7355: 					 $line,'duplicateID',$found);
 7356: 		return(1,$currentphase);
 7357: 	    } elsif ($found{'usernames'}{$username}) {
 7358: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7359: 					 $line,'duplicateID',$username);
 7360: 		return(1,$currentphase);
 7361: 	    }
 7362: 	    #FIXME store away line we previously saw the ID on to use above
 7363: 	    $found{'ids'}{$found}++;
 7364: 	    $found{'usernames'}{$username}++;
 7365: 	} else {
 7366: 	    if ($id =~ /^\s*$/) {
 7367: 		my $username=&scan_data($scan_data,"$i.user");
 7368: 		if (defined($username) && $found{'usernames'}{$username}) {
 7369: 		    &scantron_get_correction($r,$i,$scan_record,
 7370: 					     \%scantron_config,
 7371: 					     $line,'duplicateID',$username);
 7372: 		    return(1,$currentphase);
 7373: 		} elsif (!defined($username)) {
 7374: 		    &scantron_get_correction($r,$i,$scan_record,
 7375: 					     \%scantron_config,
 7376: 					     $line,'incorrectID');
 7377: 		    return(1,$currentphase);
 7378: 		}
 7379: 		$found{'usernames'}{$username}++;
 7380: 	    } else {
 7381: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7382: 					 $line,'incorrectID');
 7383: 		return(1,$currentphase);
 7384: 	    }
 7385: 	}
 7386:     }
 7387: 
 7388:     return (0,$currentphase+1);
 7389: }
 7390: 
 7391: 
 7392: sub scantron_get_correction {
 7393:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7394:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7395: #FIXME in the case of a duplicated ID the previous line, probably need
 7396: #to show both the current line and the previous one and allow skipping
 7397: #the previous one or the current one
 7398: 
 7399:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7400:         $r->print(
 7401:             '<p class="LC_warning">'
 7402:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7403:                 "<b>$error</b>",
 7404:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7405:            ."</p> \n");
 7406:     } else {
 7407:         $r->print(
 7408:             '<p class="LC_warning">'
 7409:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7410:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7411:            ."</p> \n");
 7412:     }
 7413:     my $message =
 7414:         '<p>'
 7415:        .&mt('The ID on the form is [_1]',
 7416:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7417:        .'<br />'
 7418:        .&mt('The name on the paper is [_1], [_2]',
 7419:             $$scan_record{'scantron.LastName'},
 7420:             $$scan_record{'scantron.FirstName'})
 7421:        .'</p>';
 7422: 
 7423:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7424:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7425:                            # Array populated for doublebubble or
 7426:     my @lines_to_correct;  # missingbubble errors to build javascript
 7427:                            # to validate radio button checking   
 7428: 
 7429:     if ($error =~ /ID$/) {
 7430: 	if ($error eq 'incorrectID') {
 7431: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7432: 		      "</p>\n");
 7433: 	} elsif ($error eq 'duplicateID') {
 7434: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7435: 	}
 7436: 	$r->print($message);
 7437: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7438: 	$r->print("\n<ul><li> ");
 7439: 	#FIXME it would be nice if this sent back the user ID and
 7440: 	#could do partial userID matches
 7441: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7442: 				       'scantron_username','scantron_domain'));
 7443: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7444: 	$r->print("\n:\n".
 7445: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7446: 
 7447: 	$r->print('</li>');
 7448:     } elsif ($error =~ /CODE$/) {
 7449: 	if ($error eq 'incorrectCODE') {
 7450: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7451: 	} elsif ($error eq 'duplicateCODE') {
 7452: 	    $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");
 7453: 	}
 7454:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7455:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7456:                  ."</p>\n");
 7457: 	$r->print($message);
 7458: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7459: 	$r->print("\n<br /> ");
 7460: 	my $i=0;
 7461: 	if ($error eq 'incorrectCODE' 
 7462: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7463: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7464: 	    if ($closest > 0) {
 7465: 		foreach my $testcode (@{$closest}) {
 7466: 		    my $checked='';
 7467: 		    if (!$i) { $checked=' checked="checked"'; }
 7468: 		    $r->print("
 7469:    <label>
 7470:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7471:        ".&mt("Use the similar CODE [_1] instead.",
 7472: 	    "<b><tt>".$testcode."</tt></b>")."
 7473:     </label>
 7474:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7475: 		    $r->print("\n<br />");
 7476: 		    $i++;
 7477: 		}
 7478: 	    }
 7479: 	}
 7480: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7481: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7482: 	    $r->print("
 7483:     <label>
 7484:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7485:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7486: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7487:     </label>");
 7488: 	    $r->print("\n<br />");
 7489: 	}
 7490: 
 7491: 	$r->print(<<ENDSCRIPT);
 7492: <script type="text/javascript">
 7493: function change_radio(field) {
 7494:     var slct=document.scantronupload.scantron_CODE_resolution;
 7495:     var i;
 7496:     for (i=0;i<slct.length;i++) {
 7497:         if (slct[i].value==field) { slct[i].checked=true; }
 7498:     }
 7499: }
 7500: </script>
 7501: ENDSCRIPT
 7502: 	my $href="/adm/pickcode?".
 7503: 	   "form=".&escape("scantronupload").
 7504: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7505: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7506: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7507: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7508: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7509: 	    $r->print("
 7510:     <label>
 7511:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7512:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7513: 	     "<a target='_blank' href='$href'>","</a>")."
 7514:     </label> 
 7515:     ".&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\')" />'));
 7516: 	    $r->print("\n<br />");
 7517: 	}
 7518: 	$r->print("
 7519:     <label>
 7520:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7521:        ".&mt("Use [_1] as the CODE.",
 7522: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7523: 	$r->print("\n<br /><br />");
 7524:     } elsif ($error eq 'doublebubble') {
 7525: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7526: 
 7527: 	# The form field scantron_questions is acutally a list of line numbers.
 7528: 	# represented by this form so:
 7529: 
 7530: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7531:                                                 $respnumlookup,$startline);
 7532: 
 7533: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7534: 		  $line_list.'" />');
 7535: 	$r->print($message);
 7536: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7537: 	foreach my $question (@{$arg}) {
 7538: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7539:                                                    $scan_record, $error,
 7540:                                                    $randomorder,$randompick,
 7541:                                                    $respnumlookup,$startline);
 7542:             push(@lines_to_correct,@linenums);
 7543: 	}
 7544:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7545:     } elsif ($error eq 'missingbubble') {
 7546: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7547: 	$r->print($message);
 7548: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7549: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7550: 
 7551: 	# The form field scantron_questions is actually a list of line numbers not
 7552: 	# a list of question numbers. Therefore:
 7553: 	#
 7554: 	
 7555: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7556:                                                 $respnumlookup,$startline);
 7557: 
 7558: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7559: 		  $line_list.'" />');
 7560: 	foreach my $question (@{$arg}) {
 7561: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7562:                                                    $scan_record, $error,
 7563:                                                    $randomorder,$randompick,
 7564:                                                    $respnumlookup,$startline);
 7565:             push(@lines_to_correct,@linenums);
 7566: 	}
 7567:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7568:     } else {
 7569: 	$r->print("\n<ul>");
 7570:     }
 7571:     $r->print("\n</li></ul>");
 7572: }
 7573: 
 7574: sub verify_bubbles_checked {
 7575:     my (@ansnums) = @_;
 7576:     my $ansnumstr = join('","',@ansnums);
 7577:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7578:     my $output = (<<ENDSCRIPT);
 7579: <script type="text/javascript">
 7580: function verify_bubble_radio(form) {
 7581:     var ansnumArray = new Array ("$ansnumstr");
 7582:     var need_bubble_count = 0;
 7583:     for (var i=0; i<ansnumArray.length; i++) {
 7584:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7585:             var bubble_picked = 0; 
 7586:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7587:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7588:                     bubble_picked = 1;
 7589:                 }
 7590:             }
 7591:             if (bubble_picked == 0) {
 7592:                 need_bubble_count ++;
 7593:             }
 7594:         }
 7595:     }
 7596:     if (need_bubble_count) {
 7597:         alert("$warning");
 7598:         return;
 7599:     }
 7600:     form.submit(); 
 7601: }
 7602: </script>
 7603: ENDSCRIPT
 7604:     return $output;
 7605: }
 7606: 
 7607: =pod
 7608: 
 7609: =item  questions_to_line_list
 7610: 
 7611: Converts a list of questions into a string of comma separated
 7612: line numbers in the answer sheet used by the questions.  This is
 7613: used to fill in the scantron_questions form field.
 7614: 
 7615:   Arguments:
 7616:      questions    - Reference to an array of questions.
 7617:      randomorder  - True if randomorder in use.
 7618:      randompick   - True if randompick in use.
 7619:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7620:                      for current line to question number used for same question
 7621:                      in "Master Seqence" (as seen by Course Coordinator).
 7622:      startline    - Reference to hash where key is question number (0 is first)
 7623:                     and key is number of first bubble line for current student
 7624:                     or code-based randompick and/or randomorder.
 7625: 
 7626: =cut
 7627: 
 7628: 
 7629: sub questions_to_line_list {
 7630:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7631:     my @lines;
 7632: 
 7633:     foreach my $item (@{$questions}) {
 7634:         my $question = $item;
 7635:         my ($first,$count,$last);
 7636:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7637:             $question = $1;
 7638:             my $subquestion = $2;
 7639:             my $responsenum = $question-1;
 7640:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7641:                 $responsenum = $respnumlookup->{$question-1};
 7642:                 if (ref($startline) eq 'HASH') {
 7643:                     $first = $startline->{$question-1} + 1;
 7644:                 }
 7645:             } else {
 7646:                 $first = $first_bubble_line{$responsenum} + 1;
 7647:             }
 7648:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7649:             my $subcount = 1;
 7650:             while ($subcount<$subquestion) {
 7651:                 $first += $subans[$subcount-1];
 7652:                 $subcount ++;
 7653:             }
 7654:             $count = $subans[$subquestion-1];
 7655:         } else {
 7656:             my $responsenum = $question-1;
 7657:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7658:                 $responsenum = $respnumlookup->{$question-1};
 7659:                 if (ref($startline) eq 'HASH') {
 7660:                     $first = $startline->{$question-1} + 1;
 7661:                 }
 7662:             } else {
 7663:                 $first = $first_bubble_line{$responsenum} + 1;
 7664:             }
 7665:             $count   = $bubble_lines_per_response{$responsenum};
 7666:         }
 7667:         $last = $first+$count-1;
 7668:         push(@lines, ($first..$last));
 7669:     }
 7670:     return join(',', @lines);
 7671: }
 7672: 
 7673: =pod 
 7674: 
 7675: =item prompt_for_corrections
 7676: 
 7677: Prompts for a potentially multiline correction to the
 7678: user's bubbling (factors out common code from scantron_get_correction
 7679: for multi and missing bubble cases).
 7680: 
 7681:  Arguments:
 7682:    $r           - Apache request object.
 7683:    $question    - The question number to prompt for.
 7684:    $scan_config - The scantron file configuration hash.
 7685:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7686:    $error       - Type of error
 7687:    $randomorder - True if randomorder in use.
 7688:    $randompick  - True if randompick in use.
 7689:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7690:                     for current line to question number used for same question
 7691:                     in "Master Seqence" (as seen by Course Coordinator).
 7692:    $startline   - Reference to hash where key is question number (0 is first)
 7693:                   and value is number of first bubble line for current student
 7694:                   or code-based randompick and/or randomorder.
 7695: 
 7696:  Implicit inputs:
 7697:    %bubble_lines_per_response   - Starting line numbers for each question.
 7698:                                   Numbered from 0 (but question numbers are from
 7699:                                   1.
 7700:    %first_bubble_line           - Starting bubble line for each question.
 7701:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7702:                                   type problems render as separate sub-questions, 
 7703:                                   in exam mode. This hash contains a 
 7704:                                   comma-separated list of the lines per 
 7705:                                   sub-question.
 7706:    %responsetype_per_response   - essayresponse, formularesponse,
 7707:                                   stringresponse, imageresponse, reactionresponse,
 7708:                                   and organicresponse type problem parts can have
 7709:                                   multiple lines per response if the weight
 7710:                                   assigned exceeds 10.  In this case, only
 7711:                                   one bubble per line is permitted, but more 
 7712:                                   than one line might contain bubbles, e.g.
 7713:                                   bubbling of: line 1 - J, line 2 - J, 
 7714:                                   line 3 - B would assign 22 points.  
 7715: 
 7716: =cut
 7717: 
 7718: sub prompt_for_corrections {
 7719:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7720:         $randompick, $respnumlookup, $startline) = @_;
 7721:     my ($current_line,$lines);
 7722:     my @linenums;
 7723:     my $questionnum = $question;
 7724:     my ($first,$responsenum);
 7725:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7726:         $question = $1;
 7727:         my $subquestion = $2;
 7728:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7729:             $responsenum = $respnumlookup->{$question-1};
 7730:             if (ref($startline) eq 'HASH') {
 7731:                 $first = $startline->{$question-1};
 7732:             }
 7733:         } else {
 7734:             $responsenum = $question-1;
 7735:             $first = $first_bubble_line{$responsenum} + 1;
 7736:         }
 7737:         $current_line = $first + 1 ;
 7738:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7739:         my $subcount = 1;
 7740:         while ($subcount<$subquestion) {
 7741:             $current_line += $subans[$subcount-1];
 7742:             $subcount ++;
 7743:         }
 7744:         $lines = $subans[$subquestion-1];
 7745:     } else {
 7746:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7747:             $responsenum = $respnumlookup->{$question-1};
 7748:             if (ref($startline) eq 'HASH') {
 7749:                 $first = $startline->{$question-1};
 7750:             }
 7751:         } else {
 7752:             $responsenum = $question-1;
 7753:             $first = $first_bubble_line{$responsenum};
 7754:         }
 7755:         $current_line = $first + 1;
 7756:         $lines        = $bubble_lines_per_response{$responsenum};
 7757:     }
 7758:     if ($lines > 1) {
 7759:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7760:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7761:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7762:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7763:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7764:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7765:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7766:             $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 />');
 7767:         } else {
 7768:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7769:         }
 7770:     }
 7771:     for (my $i =0; $i < $lines; $i++) {
 7772:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7773: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7774: 	        		  $questionnum,$error,split('', $selected));
 7775:         push(@linenums,$current_line);
 7776: 	$current_line++;
 7777:     }
 7778:     if ($lines > 1) {
 7779: 	$r->print("<hr /><br />");
 7780:     }
 7781:     return @linenums;
 7782: }
 7783: 
 7784: =pod
 7785: 
 7786: =item scantron_bubble_selector
 7787:   
 7788:    Generates the html radiobuttons to correct a single bubble line
 7789:    possibly showing the existing the selected bubbles if known
 7790: 
 7791:  Arguments:
 7792:     $r           - Apache request object
 7793:     $scan_config - hash from &get_scantron_config()
 7794:     $line        - Number of the line being displayed.
 7795:     $questionnum - Question number (may include subquestion)
 7796:     $error       - Type of error.
 7797:     @selected    - Array of bubbles picked on this line.
 7798: 
 7799: =cut
 7800: 
 7801: sub scantron_bubble_selector {
 7802:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7803:     my $max=$$scan_config{'Qlength'};
 7804: 
 7805:     my $scmode=$$scan_config{'Qon'};
 7806:     if ($scmode eq 'number' || $scmode eq 'letter') {
 7807:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7808:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7809:             $max=$$scan_config{'BubblesPerRow'};
 7810:             if (($scmode eq 'number') && ($max > 10)) {
 7811:                 $max = 10;
 7812:             } elsif (($scmode eq 'letter') && $max > 26) {
 7813:                 $max = 26;
 7814:             }
 7815:         } else {
 7816:             $max = 10;
 7817:         }
 7818:     }
 7819: 
 7820:     my @alphabet=('A'..'Z');
 7821:     $r->print(&Apache::loncommon::start_data_table().
 7822:               &Apache::loncommon::start_data_table_row());
 7823:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7824:     for (my $i=0;$i<$max+1;$i++) {
 7825: 	$r->print("\n".'<td align="center">');
 7826: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7827: 	else { $r->print('&nbsp;'); }
 7828: 	$r->print('</td>');
 7829:     }
 7830:     $r->print(&Apache::loncommon::end_data_table_row().
 7831:               &Apache::loncommon::start_data_table_row());
 7832:     for (my $i=0;$i<$max;$i++) {
 7833: 	$r->print("\n".
 7834: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7835: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7836:     }
 7837:     my $nobub_checked = ' ';
 7838:     if ($error eq 'missingbubble') {
 7839:         $nobub_checked = ' checked = "checked" ';
 7840:     }
 7841:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7842: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7843:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7844:               $line.'" value="'.$questionnum.'" /></td>');
 7845:     $r->print(&Apache::loncommon::end_data_table_row().
 7846:               &Apache::loncommon::end_data_table());
 7847: }
 7848: 
 7849: =pod
 7850: 
 7851: =item num_matches
 7852: 
 7853:    Counts the number of characters that are the same between the two arguments.
 7854: 
 7855:  Arguments:
 7856:    $orig - CODE from the scanline
 7857:    $code - CODE to match against
 7858: 
 7859:  Returns:
 7860:    $count - integer count of the number of same characters between the
 7861:             two arguments
 7862: 
 7863: =cut
 7864: 
 7865: sub num_matches {
 7866:     my ($orig,$code) = @_;
 7867:     my @code=split(//,$code);
 7868:     my @orig=split(//,$orig);
 7869:     my $same=0;
 7870:     for (my $i=0;$i<scalar(@code);$i++) {
 7871: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7872:     }
 7873:     return $same;
 7874: }
 7875: 
 7876: =pod
 7877: 
 7878: =item scantron_get_closely_matching_CODEs
 7879: 
 7880:    Cycles through all CODEs and finds the set that has the greatest
 7881:    number of same characters as the provided CODE
 7882: 
 7883:  Arguments:
 7884:    $allcodes - hash ref returned by &get_codes()
 7885:    $CODE     - CODE from the current scanline
 7886: 
 7887:  Returns:
 7888:    2 element list
 7889:     - first elements is number of how closely matching the best fit is 
 7890:       (5 means best set has 5 matching characters)
 7891:     - second element is an arrary ref containing the set of valid CODEs
 7892:       that best fit the passed in CODE
 7893: 
 7894: =cut
 7895: 
 7896: sub scantron_get_closely_matching_CODEs {
 7897:     my ($allcodes,$CODE)=@_;
 7898:     my @CODEs;
 7899:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7900: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7901:     }
 7902: 
 7903:     return ($#CODEs,$CODEs[-1]);
 7904: }
 7905: 
 7906: =pod
 7907: 
 7908: =item get_codes
 7909: 
 7910:    Builds a hash which has keys of all of the valid CODEs from the selected
 7911:    set of remembered CODEs.
 7912: 
 7913:  Arguments:
 7914:   $old_name - name of the set of remembered CODEs
 7915:   $cdom     - domain of the course
 7916:   $cnum     - internal course name
 7917: 
 7918:  Returns:
 7919:   %allcodes - keys are the valid CODEs, values are all 1
 7920: 
 7921: =cut
 7922: 
 7923: sub get_codes {
 7924:     my ($old_name, $cdom, $cnum) = @_;
 7925:     if (!$old_name) {
 7926: 	$old_name=$env{'form.scantron_CODElist'};
 7927:     }
 7928:     if (!$cdom) {
 7929: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7930:     }
 7931:     if (!$cnum) {
 7932: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7933:     }
 7934:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7935: 				    $cdom,$cnum);
 7936:     my %allcodes;
 7937:     if ($result{"type\0$old_name"} eq 'number') {
 7938: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7939:     } else {
 7940: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7941:     }
 7942:     return %allcodes;
 7943: }
 7944: 
 7945: =pod
 7946: 
 7947: =item scantron_validate_CODE
 7948: 
 7949:    Validates all scanlines in the selected file to not have any
 7950:    invalid or underspecified CODEs and that none of the codes are
 7951:    duplicated if this was requested.
 7952: 
 7953: =cut
 7954: 
 7955: sub scantron_validate_CODE {
 7956:     my ($r,$currentphase) = @_;
 7957:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7958:     if ($scantron_config{'CODElocation'} &&
 7959: 	$scantron_config{'CODEstart'} &&
 7960: 	$scantron_config{'CODElength'}) {
 7961: 	if (!defined($env{'form.scantron_CODElist'})) {
 7962: 	    &FIXME_blow_up()
 7963: 	}
 7964:     } else {
 7965: 	return (0,$currentphase+1);
 7966:     }
 7967:     
 7968:     my %usedCODEs;
 7969: 
 7970:     my %allcodes=&get_codes();
 7971: 
 7972:     my $nav_error;
 7973:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7974:     if ($nav_error) {
 7975:         $r->print(&navmap_errormsg());
 7976:         return(1,$currentphase);
 7977:     }
 7978: 
 7979:     my ($scanlines,$scan_data)=&scantron_getfile();
 7980:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7981: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7982: 	if ($line=~/^[\s\cz]*$/) { next; }
 7983: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7984: 						 $scan_data);
 7985: 	my $CODE=$$scan_record{'scantron.CODE'};
 7986: 	my $error=0;
 7987: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7988: 	    &scantron_get_correction($r,$i,$scan_record,
 7989: 				     \%scantron_config,
 7990: 				     $line,'incorrectCODE',\%allcodes);
 7991: 	    return(1,$currentphase);
 7992: 	}
 7993: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7994: 	    && !$$scan_record{'scantron.useCODE'}) {
 7995: 	    &scantron_get_correction($r,$i,$scan_record,
 7996: 				     \%scantron_config,
 7997: 				     $line,'incorrectCODE',\%allcodes);
 7998: 	    return(1,$currentphase);
 7999: 	}
 8000: 	if (exists($usedCODEs{$CODE}) 
 8001: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8002: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8003: 	    &scantron_get_correction($r,$i,$scan_record,
 8004: 				     \%scantron_config,
 8005: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8006: 	    return(1,$currentphase);
 8007: 	}
 8008: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8009:     }
 8010:     return (0,$currentphase+1);
 8011: }
 8012: 
 8013: =pod
 8014: 
 8015: =item scantron_validate_doublebubble
 8016: 
 8017:    Validates all scanlines in the selected file to not have any
 8018:    bubble lines with multiple bubbles marked.
 8019: 
 8020: =cut
 8021: 
 8022: sub scantron_validate_doublebubble {
 8023:     my ($r,$currentphase) = @_;
 8024:     #get student info
 8025:     my $classlist=&Apache::loncoursedata::get_classlist();
 8026:     my %idmap=&username_to_idmap($classlist);
 8027:     my (undef,undef,$sequence)=
 8028:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8029: 
 8030:     #get scantron line setup
 8031:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8032:     my ($scanlines,$scan_data)=&scantron_getfile();
 8033: 
 8034:     my $navmap = Apache::lonnavmaps::navmap->new();
 8035:     unless (ref($navmap)) {
 8036:         $r->print(&navmap_errormsg());
 8037:         return(1,$currentphase);
 8038:     }
 8039:     my $map=$navmap->getResourceByUrl($sequence);
 8040:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8041:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8042:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8043:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8044: 
 8045:     my $nav_error;
 8046:     if (ref($map)) {
 8047:         $randomorder = $map->randomorder();
 8048:         $randompick = $map->randompick();
 8049:         if ($randomorder || $randompick) {
 8050:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8051:             if ($nav_error) {
 8052:                 $r->print(&navmap_errormsg());
 8053:                 return(1,$currentphase);
 8054:             }
 8055:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8056:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8057:         }
 8058:     } else {
 8059:         $r->print(&navmap_errormsg());
 8060:         return(1,$currentphase);
 8061:     }
 8062: 
 8063:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8064:     if ($nav_error) {
 8065:         $r->print(&navmap_errormsg());
 8066:         return(1,$currentphase);
 8067:     }
 8068: 
 8069:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8070: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8071: 	if ($line=~/^[\s\cz]*$/) { next; }
 8072: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8073: 						 $scan_data,undef,\%idmap,$randomorder,
 8074:                                                  $randompick,$sequence,\@master_seq,
 8075:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8076:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8077: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8078: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8079: 				 'doublebubble',
 8080: 				 $$scan_record{'scantron.doubleerror'},
 8081:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8082:     	return (1,$currentphase);
 8083:     }
 8084:     return (0,$currentphase+1);
 8085: }
 8086: 
 8087: 
 8088: sub scantron_get_maxbubble {
 8089:     my ($nav_error,$scantron_config) = @_;
 8090:     if (defined($env{'form.scantron_maxbubble'}) &&
 8091: 	$env{'form.scantron_maxbubble'}) {
 8092: 	&restore_bubble_lines();
 8093: 	return $env{'form.scantron_maxbubble'};
 8094:     }
 8095: 
 8096:     my (undef, undef, $sequence) =
 8097: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8098: 
 8099:     my $navmap=Apache::lonnavmaps::navmap->new();
 8100:     unless (ref($navmap)) {
 8101:         if (ref($nav_error)) {
 8102:             $$nav_error = 1;
 8103:         }
 8104:         return;
 8105:     }
 8106:     my $map=$navmap->getResourceByUrl($sequence);
 8107:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8108:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8109: 
 8110:     &Apache::lonxml::clear_problem_counter();
 8111: 
 8112:     my $uname       = $env{'user.name'};
 8113:     my $udom        = $env{'user.domain'};
 8114:     my $cid         = $env{'request.course.id'};
 8115:     my $total_lines = 0;
 8116:     %bubble_lines_per_response = ();
 8117:     %first_bubble_line         = ();
 8118:     %subdivided_bubble_lines   = ();
 8119:     %responsetype_per_response = ();
 8120:     %masterseq_id_responsenum  = ();
 8121: 
 8122:     my $response_number = 0;
 8123:     my $bubble_line     = 0;
 8124:     foreach my $resource (@resources) {
 8125:         my $resid = $resource->id();
 8126:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8127:                                                           $udom,undef,$bubbles_per_row);
 8128:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8129: 	    foreach my $part_id (@{$parts}) {
 8130:                 my $lines;
 8131: 
 8132: 	        # TODO - make this a persistent hash not an array.
 8133: 
 8134:                 # optionresponse, matchresponse and rankresponse type items 
 8135:                 # render as separate sub-questions in exam mode.
 8136:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8137:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8138:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8139:                     my ($numbub,$numshown);
 8140:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8141:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8142:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8143:                         }
 8144:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8145:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8146:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8147:                         }
 8148:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8149:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8150:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8151:                         }
 8152:                     }
 8153:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8154:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8155:                     }
 8156:                     my $bubbles_per_row =
 8157:                         &bubblesheet_bubbles_per_row($scantron_config);
 8158:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8159:                     if (($numbub % $bubbles_per_row) != 0) {
 8160:                         $inner_bubble_lines++;
 8161:                     }
 8162:                     for (my $i=0; $i<$numshown; $i++) {
 8163:                         $subdivided_bubble_lines{$response_number} .= 
 8164:                             $inner_bubble_lines.',';
 8165:                     }
 8166:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8167:                     $lines = $numshown * $inner_bubble_lines;
 8168:                 } else {
 8169:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8170:                 }
 8171: 
 8172:                 $first_bubble_line{$response_number} = $bubble_line;
 8173: 	        $bubble_lines_per_response{$response_number} = $lines;
 8174:                 $responsetype_per_response{$response_number} = 
 8175:                     $analysis->{$part_id.'.type'};
 8176:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8177: 	        $response_number++;
 8178: 
 8179: 	        $bubble_line +=  $lines;
 8180: 	        $total_lines +=  $lines;
 8181: 	    }
 8182:         }
 8183:     }
 8184:     &Apache::lonnet::delenv('scantron.');
 8185: 
 8186:     &save_bubble_lines();
 8187:     $env{'form.scantron_maxbubble'} =
 8188: 	$total_lines;
 8189:     return $env{'form.scantron_maxbubble'};
 8190: }
 8191: 
 8192: sub bubblesheet_bubbles_per_row {
 8193:     my ($scantron_config) = @_;
 8194:     my $bubbles_per_row;
 8195:     if (ref($scantron_config) eq 'HASH') {
 8196:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8197:     }
 8198:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8199:         $bubbles_per_row = 10;
 8200:     }
 8201:     return $bubbles_per_row;
 8202: }
 8203: 
 8204: sub scantron_validate_missingbubbles {
 8205:     my ($r,$currentphase) = @_;
 8206:     #get student info
 8207:     my $classlist=&Apache::loncoursedata::get_classlist();
 8208:     my %idmap=&username_to_idmap($classlist);
 8209:     my (undef,undef,$sequence)=
 8210:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8211: 
 8212:     #get scantron line setup
 8213:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8214:     my ($scanlines,$scan_data)=&scantron_getfile();
 8215: 
 8216:     my $navmap = Apache::lonnavmaps::navmap->new();
 8217:     unless (ref($navmap)) {
 8218:         $r->print(&navmap_errormsg());
 8219:         return(1,$currentphase);
 8220:     }
 8221: 
 8222:     my $map=$navmap->getResourceByUrl($sequence);
 8223:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8224:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8225:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8226:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8227: 
 8228:     my $nav_error;
 8229:     if (ref($map)) {
 8230:         $randomorder = $map->randomorder();
 8231:         $randompick = $map->randompick();
 8232:         if ($randomorder || $randompick) {
 8233:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8234:             if ($nav_error) {
 8235:                 $r->print(&navmap_errormsg());
 8236:                 return(1,$currentphase);
 8237:             }
 8238:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8239:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8240:         }
 8241:     } else {
 8242:         $r->print(&navmap_errormsg());
 8243:         return(1,$currentphase);
 8244:     }
 8245: 
 8246: 
 8247:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8248:     if ($nav_error) {
 8249:         $r->print(&navmap_errormsg());
 8250:         return(1,$currentphase);
 8251:     }
 8252: 
 8253:     if (!$max_bubble) { $max_bubble=2**31; }
 8254:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8255: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8256: 	if ($line=~/^[\s\cz]*$/) { next; }
 8257:         my $scan_record =
 8258:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8259:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8260:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8261:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8262: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8263: 	my @to_correct;
 8264: 	
 8265: 	# Probably here's where the error is...
 8266: 
 8267: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8268:             my $lastbubble;
 8269:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8270:                 my $question = $1;
 8271:                 my $subquestion = $2;
 8272:                 my ($first,$responsenum);
 8273:                 if ($randomorder || $randompick) {
 8274:                     $responsenum = $respnumlookup{$question-1};
 8275:                     $first = $startline{$question-1};
 8276:                 } else {
 8277:                     $responsenum = $question-1;
 8278:                     $first = $first_bubble_line{$responsenum};
 8279:                 }
 8280:                 if (!defined($first)) { next; }
 8281:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8282:                 my $subcount = 1;
 8283:                 while ($subcount<$subquestion) {
 8284:                     $first += $subans[$subcount-1];
 8285:                     $subcount ++;
 8286:                 }
 8287:                 my $count = $subans[$subquestion-1];
 8288:                 $lastbubble = $first + $count;
 8289:             } else {
 8290:                 my ($first,$responsenum);
 8291:                 if ($randomorder || $randompick) {
 8292:                     $responsenum = $respnumlookup{$missing-1};
 8293:                     $first = $startline{$missing-1};
 8294:                 } else {
 8295:                     $responsenum = $missing-1;
 8296:                     $first = $first_bubble_line{$responsenum};
 8297:                 }
 8298:                 if (!defined($first)) { next; }
 8299:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8300:             }
 8301:             if ($lastbubble > $max_bubble) { next; }
 8302: 	    push(@to_correct,$missing);
 8303: 	}
 8304: 	if (@to_correct) {
 8305: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8306: 				     $line,'missingbubble',\@to_correct,
 8307:                                      $randomorder,$randompick,\%respnumlookup,
 8308:                                      \%startline);
 8309: 	    return (1,$currentphase);
 8310: 	}
 8311: 
 8312:     }
 8313:     return (0,$currentphase+1);
 8314: }
 8315: 
 8316: sub hand_bubble_option {
 8317:     my (undef, undef, $sequence) =
 8318:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8319:     return if ($sequence eq '');
 8320:     my $navmap = Apache::lonnavmaps::navmap->new();
 8321:     unless (ref($navmap)) {
 8322:         return;
 8323:     }
 8324:     my $needs_hand_bubbles;
 8325:     my $map=$navmap->getResourceByUrl($sequence);
 8326:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8327:     foreach my $res (@resources) {
 8328:         if (ref($res)) {
 8329:             if ($res->is_problem()) {
 8330:                 my $partlist = $res->parts();
 8331:                 foreach my $part (@{ $partlist }) {
 8332:                     my @types = $res->responseType($part);
 8333:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8334:                         $needs_hand_bubbles = 1;
 8335:                         last;
 8336:                     }
 8337:                 }
 8338:             }
 8339:         }
 8340:     }
 8341:     if ($needs_hand_bubbles) {
 8342:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8343:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8344:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8345:                &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 />').
 8346:                '<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;'.
 8347:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
 8348:     }
 8349:     return;
 8350: }
 8351: 
 8352: sub scantron_process_students {
 8353:     my ($r) = @_;
 8354: 
 8355:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8356:     my ($symb)=&get_symb($r);
 8357:     if (!$symb) {
 8358: 	return '';
 8359:     }
 8360:     my $default_form_data=&defaultFormData($symb);
 8361: 
 8362:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8363:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8364:     my ($scanlines,$scan_data)=&scantron_getfile();
 8365:     my $classlist=&Apache::loncoursedata::get_classlist();
 8366:     my %idmap=&username_to_idmap($classlist);
 8367:     my $navmap=Apache::lonnavmaps::navmap->new();
 8368:     unless (ref($navmap)) {
 8369:         $r->print(&navmap_errormsg());
 8370:         return '';
 8371:     }
 8372:     my $map=$navmap->getResourceByUrl($sequence);
 8373:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8374:         %grader_randomlists_by_symb);
 8375:     if (ref($map)) {
 8376:         $randomorder = $map->randomorder();
 8377:         $randompick = $map->randompick();
 8378:     } else {
 8379:         $r->print(&navmap_errormsg());
 8380:         return '';
 8381:     }
 8382:     my $nav_error;
 8383:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8384:     if ($randomorder || $randompick) {
 8385:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8386:         if ($nav_error) {
 8387:             $r->print(&navmap_errormsg());
 8388:             return '';
 8389:         }
 8390:     }
 8391:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8392:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8393: 
 8394:     my ($uname,$udom);
 8395:     my $result= <<SCANTRONFORM;
 8396: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8397:   <input type="hidden" name="command" value="scantron_configphase" />
 8398:   $default_form_data
 8399: SCANTRONFORM
 8400:     $r->print($result);
 8401: 
 8402:     my @delayqueue;
 8403:     my (%completedstudents,%scandata);
 8404:     
 8405:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8406:     my $count=&get_todo_count($scanlines,$scan_data);
 8407:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8408:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8409: 					  'Processing first student');
 8410:     $r->print('<br />');
 8411:     my $start=&Time::HiRes::time();
 8412:     my $i=-1;
 8413:     my $started;
 8414: 
 8415:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8416:     if ($nav_error) {
 8417:         $r->print(&navmap_errormsg());
 8418:         return '';
 8419:     }
 8420: 
 8421:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8422:     # the user and return.
 8423: 
 8424:     if ($ssi_error) {
 8425: 	$r->print("</form>");
 8426: 	&ssi_print_error($r);
 8427: 	$r->print(&show_grading_menu_form($symb));
 8428:         &Apache::lonnet::remove_lock($lock);
 8429: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8430:     }
 8431: 
 8432:     my %lettdig = &letter_to_digits();
 8433:     my $numletts = scalar(keys(%lettdig));
 8434:     my %orderedforcode;
 8435: 
 8436:     while ($i<$scanlines->{'count'}) {
 8437:  	($uname,$udom)=('','');
 8438:  	$i++;
 8439:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8440:  	if ($line=~/^[\s\cz]*$/) { next; }
 8441: 	if ($started) {
 8442: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8443: 						     'last student');
 8444: 	}
 8445: 	$started=1;
 8446:         my %respnumlookup = ();
 8447:         my %startline = ();
 8448:         my $total;
 8449:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8450:  						 $scan_data,undef,\%idmap,$randomorder,
 8451:                                                  $randompick,$sequence,\@master_seq,
 8452:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8453:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8454:                                                  \$total);
 8455:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8456:  					      \%idmap,$i)) {
 8457:   	    &scantron_add_delay(\@delayqueue,$line,
 8458:  				'Unable to find a student that matches',1);
 8459:  	    next;
 8460:   	}
 8461:  	if (exists $completedstudents{$uname}) {
 8462:  	    &scantron_add_delay(\@delayqueue,$line,
 8463:  				'Student '.$uname.' has multiple sheets',2);
 8464:  	    next;
 8465:  	}
 8466:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8467:         my $user = $uname.':'.$usec;
 8468:   	($uname,$udom)=split(/:/,$uname);
 8469: 
 8470:         my $scancode;
 8471:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8472:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8473:             $scancode = $scan_record->{'scantron.CODE'};
 8474:         } else {
 8475:             $scancode = '';
 8476:         }
 8477: 
 8478:         my @mapresources = @resources;
 8479:         if ($randomorder || $randompick) {
 8480:             @mapresources =
 8481:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8482:                              \%orderedforcode);
 8483:         }
 8484:         my (%partids_by_symb,$res_error);
 8485:         foreach my $resource (@mapresources) {
 8486:             my $ressymb;
 8487:             if (ref($resource)) {
 8488:                 $ressymb = $resource->symb();
 8489:             } else {
 8490:                 $res_error = 1;
 8491:                 last;
 8492:             }
 8493:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8494:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8495:                 my ($analysis,$parts) =
 8496:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8497:                                               $uname,$udom,undef,$bubbles_per_row);
 8498:                 $partids_by_symb{$ressymb} = $parts;
 8499:             } else {
 8500:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8501:             }
 8502:         }
 8503: 
 8504:         if ($res_error) {
 8505:             &scantron_add_delay(\@delayqueue,$line,
 8506:                                 'An error occurred while grading student '.$uname,2);
 8507:             next;
 8508:         }
 8509: 
 8510: 	&Apache::lonxml::clear_problem_counter();
 8511:   	&Apache::lonnet::appenv($scan_record);
 8512: 
 8513: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8514: 	    &scantron_putfile($scanlines,$scan_data);
 8515: 	}
 8516: 	
 8517:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8518:                                    \@mapresources,\%partids_by_symb,
 8519:                                    $bubbles_per_row,$randomorder,$randompick,
 8520:                                    \%respnumlookup,\%startline) 
 8521:             eq 'ssi_error') {
 8522:             $ssi_error = 0; # So end of handler error message does not trigger.
 8523:             $r->print("</form>");
 8524:             &ssi_print_error($r);
 8525:             $r->print(&show_grading_menu_form($symb));
 8526:             &Apache::lonnet::remove_lock($lock);
 8527:             return '';      # Why return ''?  Beats me.
 8528:         }
 8529: 
 8530:         if (($scancode) && ($randomorder || $randompick)) {
 8531:             my $parmresult =
 8532:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8533:                                                        '0_examcode',2,$scancode,
 8534:                                                        'string_examcode',$uname,
 8535:                                                        $udom);
 8536:         }
 8537: 	$completedstudents{$uname}={'line'=>$line};
 8538:         if ($env{'form.verifyrecord'}) {
 8539:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8540:             if ($randompick) {
 8541:                 if ($total) {
 8542:                     $lastpos = $total*$scantron_config{'Qlength'};
 8543:                 }
 8544:             }
 8545: 
 8546:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8547:             chomp($studentdata);
 8548:             $studentdata =~ s/\r$//;
 8549:             my $studentrecord = '';
 8550:             my $counter = -1;
 8551:             foreach my $resource (@mapresources) {
 8552:                 my $ressymb = $resource->symb();
 8553:                 ($counter,my $recording) =
 8554:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8555:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8556:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8557:                                              $randompick,\%respnumlookup,\%startline);
 8558:                 $studentrecord .= $recording;
 8559:             }
 8560:             if ($studentrecord ne $studentdata) {
 8561:                 &Apache::lonxml::clear_problem_counter();
 8562:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8563:                                            \@mapresources,\%partids_by_symb,
 8564:                                            $bubbles_per_row,$randomorder,$randompick,
 8565:                                            \%respnumlookup,\%startline)
 8566:                     eq 'ssi_error') {
 8567:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8568:                     $r->print("</form>");
 8569:                     &ssi_print_error($r);
 8570:                     $r->print(&show_grading_menu_form($symb));
 8571:                     &Apache::lonnet::remove_lock($lock);
 8572:                     delete($completedstudents{$uname});
 8573:                     return '';
 8574:                 }
 8575:                 $counter = -1;
 8576:                 $studentrecord = '';
 8577:                 foreach my $resource (@mapresources) {
 8578:                     my $ressymb = $resource->symb();
 8579:                     ($counter,my $recording) =
 8580:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8581:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8582:                                                  \%scantron_config,\%lettdig,$numletts,
 8583:                                                  $randomorder,$randompick,\%respnumlookup,
 8584:                                                  \%startline);
 8585:                     $studentrecord .= $recording;
 8586:                 }
 8587:                 if ($studentrecord ne $studentdata) {
 8588:                     $r->print('<p><span class="LC_warning">');
 8589:                     if ($scancode eq '') {
 8590:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8591:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8592:                     } else {
 8593:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8594:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8595:                     }
 8596:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8597:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8598:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8599:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8600:                               &Apache::loncommon::start_data_table_row().
 8601:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8602:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 8603:                               &Apache::loncommon::end_data_table_row().
 8604:                               &Apache::loncommon::start_data_table_row().
 8605:                               '<td>'.&mt('Stored submissions').'</td>'.
 8606:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 8607:                               &Apache::loncommon::end_data_table_row().
 8608:                               &Apache::loncommon::end_data_table().'</p>');
 8609:                 } else {
 8610:                     $r->print('<br /><span class="LC_warning">'.
 8611:                              &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 />'.
 8612:                              &mt("As a consequence, this user's submission history records two tries.").
 8613:                                  '</span><br />');
 8614:                 }
 8615:             }
 8616:         }
 8617:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8618:     } continue {
 8619: 	&Apache::lonxml::clear_problem_counter();
 8620: 	&Apache::lonnet::delenv('scantron.');
 8621:     }
 8622:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8623:     &Apache::lonnet::remove_lock($lock);
 8624: #    my $lasttime = &Time::HiRes::time()-$start;
 8625: #    $r->print("<p>took $lasttime</p>");
 8626: 
 8627:     $r->print("</form>");
 8628:     $r->print(&show_grading_menu_form($symb));
 8629:     return '';
 8630: }
 8631: 
 8632: sub graders_resources_pass {
 8633:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8634:         $bubbles_per_row) = @_;
 8635:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8636:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8637:         foreach my $resource (@{$resources}) {
 8638:             my $ressymb = $resource->symb();
 8639:             my ($analysis,$parts) =
 8640:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8641:                                           $env{'user.name'},$env{'user.domain'},
 8642:                                           1,$bubbles_per_row);
 8643:             $grader_partids_by_symb->{$ressymb} = $parts;
 8644:             if (ref($analysis) eq 'HASH') {
 8645:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8646:                     $grader_randomlists_by_symb->{$ressymb} =
 8647:                         $analysis->{'parts_withrandomlist'};
 8648:                 }
 8649:             }
 8650:         }
 8651:     }
 8652:     return;
 8653: }
 8654: 
 8655: =pod
 8656: 
 8657: =item users_order
 8658: 
 8659:   Returns array of resources in current map, ordered based on either CODE,
 8660:   if this is a CODEd exam, or based on student's identity if this is a
 8661:   "NAMEd" exam.
 8662: 
 8663:   Should be used when randomorder and/or randompick applied when the 
 8664:   corresponding exam was printed, prior to students completing bubblesheets 
 8665:   for the version of the exam the student received.
 8666: 
 8667: =cut
 8668: 
 8669: sub users_order  {
 8670:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8671:     my @mapresources;
 8672:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8673:         return @mapresources;
 8674:     }
 8675:     if ($scancode) {
 8676:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8677:             @mapresources = @{$orderedforcode->{$scancode}};
 8678:         } else {
 8679:             $env{'form.CODE'} = $scancode;
 8680:             my $actual_seq =
 8681:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8682:                                                                $master_seq,
 8683:                                                                $user,$scancode,1);
 8684:             if (ref($actual_seq) eq 'ARRAY') {
 8685:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8686:                 if (ref($orderedforcode) eq 'HASH') {
 8687:                     if (@mapresources > 0) {
 8688:                         $orderedforcode->{$scancode} = \@mapresources;
 8689:                     }
 8690:                 }
 8691:             }
 8692:             delete($env{'form.CODE'});
 8693:         }
 8694:     } else {
 8695:         my $actual_seq =
 8696:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8697:                                                            $master_seq,
 8698:                                                            $user,undef,1);
 8699:         if (ref($actual_seq) eq 'ARRAY') {
 8700:             @mapresources =
 8701:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8702:         }
 8703:     }
 8704:     return @mapresources;
 8705: }
 8706: 
 8707: sub grade_student_bubbles {
 8708:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8709:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8710:     my $uselookup = 0;
 8711:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8712:         (ref($startline) eq 'HASH')) {
 8713:         $uselookup = 1;
 8714:     }
 8715: 
 8716:     if (ref($resources) eq 'ARRAY') {
 8717:         my $count = 0;
 8718:         foreach my $resource (@{$resources}) {
 8719:             my $ressymb = $resource->symb();
 8720:             my %form = ('submitted'      => 'scantron',
 8721:                         'grade_target'   => 'grade',
 8722:                         'grade_username' => $uname,
 8723:                         'grade_domain'   => $udom,
 8724:                         'grade_courseid' => $env{'request.course.id'},
 8725:                         'grade_symb'     => $ressymb,
 8726:                         'CODE'           => $scancode
 8727:                        );
 8728:             if ($bubbles_per_row ne '') {
 8729:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8730:             }
 8731:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8732:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8733:             }
 8734:             if (ref($parts) eq 'HASH') {
 8735:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8736:                     foreach my $part (@{$parts->{$ressymb}}) {
 8737:                         if ($uselookup) {
 8738:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8739:                         } else {
 8740:                             $form{'scantron_questnum_start.'.$part} =
 8741:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8742:                         }
 8743:                         $count++;
 8744:                     }
 8745:                 }
 8746:             }
 8747:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8748:             return 'ssi_error' if ($ssi_error);
 8749:             last if (&Apache::loncommon::connection_aborted($r));
 8750:         }
 8751:     }
 8752:     return;
 8753: }
 8754: 
 8755: sub scantron_upload_scantron_data {
 8756:     my ($r)=@_;
 8757:     my $dom = $env{'request.role.domain'};
 8758:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8759:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8760:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8761: 							  'domainid',
 8762: 							  'coursename',$dom);
 8763:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8764:                        ('&nbsp'x2).&mt('(shows course personnel)');
 8765:     my ($symb) = &get_symb($r,1);
 8766:     my $default_form_data=&defaultFormData($symb);
 8767:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8768:     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.");
 8769:     $r->print('
 8770: <script type="text/javascript" language="javascript">
 8771:     function checkUpload(formname) {
 8772: 	if (formname.upfile.value == "") {
 8773: 	    alert("'.$nofile_alert.'");
 8774: 	    return false;
 8775: 	}
 8776:         if (formname.courseid.value == "") {
 8777:             alert("'.$nocourseid_alert.'");
 8778:             return false;
 8779:         }
 8780: 	formname.submit();
 8781:     }
 8782: 
 8783:     function ToSyllabus() {
 8784:         var cdom = '."'$dom'".';
 8785:         var cnum = document.rules.courseid.value;
 8786:         if (cdom == "" || cdom == null) {
 8787:             return;
 8788:         }
 8789:         if (cnum == "" || cnum == null) {
 8790:            return;
 8791:         }
 8792:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8793:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8794:         return;
 8795:     }
 8796: 
 8797: </script>
 8798: 
 8799: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8800: 
 8801: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8802: '.$default_form_data.
 8803:   &Apache::lonhtmlcommon::start_pick_box().
 8804:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8805:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8806:   &Apache::lonhtmlcommon::row_closure().
 8807:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8808:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8809:   &Apache::lonhtmlcommon::row_closure().
 8810:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8811:   '<input name="domainid" type="hidden" />'.$domdesc.
 8812:   &Apache::lonhtmlcommon::row_closure().
 8813:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8814:   '<input type="file" name="upfile" size="50" />'.
 8815:   &Apache::lonhtmlcommon::row_closure(1).
 8816:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8817: 
 8818: <input name="command" value="scantronupload_save" type="hidden" />
 8819: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8820: </form>
 8821: ');
 8822:     return '';
 8823: }
 8824: 
 8825: 
 8826: sub scantron_upload_scantron_data_save {
 8827:     my($r)=@_;
 8828:     my ($symb)=&get_symb($r,1);
 8829:     my $doanotherupload=
 8830: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8831: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8832: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8833: 	'</form>'."\n";
 8834:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8835: 	!&Apache::lonnet::allowed('usc',
 8836: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8837: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8838: 	if ($symb) {
 8839: 	    $r->print(&show_grading_menu_form($symb));
 8840: 	} else {
 8841: 	    $r->print($doanotherupload);
 8842: 	}
 8843: 	return '';
 8844:     }
 8845:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8846:     my $uploadedfile;
 8847:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8848:     if (length($env{'form.upfile'}) < 2) {
 8849:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8850:     } else {
 8851:         my $result = 
 8852:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8853:                                             $env{'form.courseid'},$env{'form.domainid'});
 8854: 	if ($result =~ m{^/uploaded/}) {
 8855: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8856:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8857: 			  '<span class="LC_filename">'.$result.'</span>'));
 8858:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8859:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8860:                                                        $env{'form.courseid'},$uploadedfile));
 8861: 	} else {
 8862: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8863:                           '<span class="LC_error">','</span>',$result,
 8864: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8865: 	}
 8866:     }
 8867:     if ($symb) {
 8868: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8869:     } else {
 8870: 	$r->print($doanotherupload);
 8871:     }
 8872:     return '';
 8873: }
 8874: 
 8875: sub validate_uploaded_scantron_file {
 8876:     my ($cdom,$cname,$fname) = @_;
 8877:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8878:     my @lines;
 8879:     if ($scanlines ne '-1') {
 8880:         @lines=split("\n",$scanlines,-1);
 8881:     }
 8882:     my $output;
 8883:     if (@lines) {
 8884:         my (%counts,$max_match_format);
 8885:         my ($max_match_count,$max_match_pct) = (0,0);
 8886:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8887:         my %idmap = &username_to_idmap($classlist);
 8888:         foreach my $key (keys(%idmap)) {
 8889:             my $lckey = lc($key);
 8890:             $idmap{$lckey} = $idmap{$key};
 8891:         }
 8892:         my %unique_formats;
 8893:         my @formatlines = &get_scantronformat_file();
 8894:         foreach my $line (@formatlines) {
 8895:             chomp($line);
 8896:             my @config = split(/:/,$line);
 8897:             my $idstart = $config[5];
 8898:             my $idlength = $config[6];
 8899:             if (($idstart ne '') && ($idlength > 0)) {
 8900:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8901:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8902:                 } else {
 8903:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8904:                 }
 8905:             }
 8906:         }
 8907:         foreach my $key (keys(%unique_formats)) {
 8908:             my ($idstart,$idlength) = split(':',$key);
 8909:             %{$counts{$key}} = (
 8910:                                'found'   => 0,
 8911:                                'total'   => 0,
 8912:                               );
 8913:             foreach my $line (@lines) {
 8914:                 next if ($line =~ /^#/);
 8915:                 next if ($line =~ /^[\s\cz]*$/);
 8916:                 my $id = substr($line,$idstart-1,$idlength);
 8917:                 $id = lc($id);
 8918:                 if (exists($idmap{$id})) {
 8919:                     $counts{$key}{'found'} ++;
 8920:                 }
 8921:                 $counts{$key}{'total'} ++;
 8922:             }
 8923:             if ($counts{$key}{'total'}) {
 8924:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8925:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8926:                     $max_match_pct = $percent_match;
 8927:                     $max_match_format = $key;
 8928:                     $max_match_count = $counts{$key}{'total'};
 8929:                 }
 8930:             }
 8931:         }
 8932:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8933:             my $format_descs;
 8934:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8935:             for (my $i=0; $i<$numwithformat; $i++) {
 8936:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8937:                 if ($i<$numwithformat-2) {
 8938:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8939:                 } elsif ($i==$numwithformat-2) {
 8940:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8941:                 } elsif ($i==$numwithformat-1) {
 8942:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8943:                 }
 8944:             }
 8945:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8946:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8947:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8948:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8949:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8950:                                   '<i>'.$cdom.'</i>').'</li>'.
 8951:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8952:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8953:                        '</ul>';
 8954:         }
 8955:     } else {
 8956:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8957:     }
 8958:     return $output;
 8959: }
 8960: 
 8961: sub valid_file {
 8962:     my ($requested_file)=@_;
 8963:     foreach my $filename (sort(&scantron_filenames())) {
 8964: 	if ($requested_file eq $filename) { return 1; }
 8965:     }
 8966:     return 0;
 8967: }
 8968: 
 8969: sub scantron_download_scantron_data {
 8970:     my ($r)=@_;
 8971:     my ($symb) = &get_symb($r,1);
 8972:     my $default_form_data=&defaultFormData($symb);
 8973:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8974:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8975:     my $file=$env{'form.scantron_selectfile'};
 8976:     if (! &valid_file($file)) {
 8977: 	$r->print('
 8978: 	<p>
 8979: 	    '.&mt('The requested filename was invalid.').'
 8980:         </p>
 8981: ');
 8982: 	$r->print(&show_grading_menu_form($symb));
 8983: 	return;
 8984:     }
 8985:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8986:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8987:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8988:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8989:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8990:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8991:     $r->print('
 8992:     <p>
 8993: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8994: 	      '<a href="'.$orig.'">','</a>').'
 8995:     </p>
 8996:     <p>
 8997: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8998: 	      '<a href="'.$corrected.'">','</a>').'
 8999:     </p>
 9000:     <p>
 9001: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9002: 	      '<a href="'.$skipped.'">','</a>').'
 9003:     </p>
 9004: ');
 9005:     $r->print(&show_grading_menu_form($symb));
 9006:     return '';
 9007: }
 9008: 
 9009: sub checkscantron_results {
 9010:     my ($r) = @_;
 9011:     my ($symb)=&get_symb($r);
 9012:     if (!$symb) {return '';}
 9013:     my $grading_menu_button=&show_grading_menu_form($symb);
 9014:     my $cid = $env{'request.course.id'};
 9015:     my %lettdig = &letter_to_digits();
 9016:     my $numletts = scalar(keys(%lettdig));
 9017:     my $cnum = $env{'course.'.$cid.'.num'};
 9018:     my $cdom = $env{'course.'.$cid.'.domain'};
 9019:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9020:     my %record;
 9021:     my %scantron_config =
 9022:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9023:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9024:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9025:     my $classlist=&Apache::loncoursedata::get_classlist();
 9026:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9027:     my $navmap=Apache::lonnavmaps::navmap->new();
 9028:     unless (ref($navmap)) {
 9029:         $r->print(&navmap_errormsg());
 9030:         return '';
 9031:     }
 9032:     my $map=$navmap->getResourceByUrl($sequence);
 9033:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9034:         %grader_randomlists_by_symb,%orderedforcode);
 9035:     if (ref($map)) {
 9036:         $randomorder=$map->randomorder();
 9037:         $randompick=$map->randompick();
 9038:     }
 9039:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9040:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9041:     if ($nav_error) {
 9042:         $r->print(&navmap_errormsg());
 9043:         return '';
 9044:     }
 9045:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9046:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9047:     my ($uname,$udom);
 9048:     my (%scandata,%lastname,%bylast);
 9049:     $r->print('
 9050: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9051: 
 9052:     my @delayqueue;
 9053:     my %completedstudents;
 9054: 
 9055:     my $count=&get_todo_count($scanlines,$scan_data);
 9056:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9057:     my ($username,$domain,$started,%ordered);
 9058:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9059:     if ($nav_error) {
 9060:         $r->print(&navmap_errormsg());
 9061:         return '';
 9062:     }
 9063: 
 9064:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9065:                                           'Processing first student');
 9066:     my $start=&Time::HiRes::time();
 9067:     my $i=-1;
 9068: 
 9069:     while ($i<$scanlines->{'count'}) {
 9070:         ($username,$domain,$uname)=('','','');
 9071:         $i++;
 9072:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9073:         if ($line=~/^[\s\cz]*$/) { next; }
 9074:         if ($started) {
 9075:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9076:                                                      'last student');
 9077:         }
 9078:         $started=1;
 9079:         my $scan_record=
 9080:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9081:                                                      $scan_data);
 9082:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9083:                                               \%idmap,$i)) {
 9084:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9085:                                 'Unable to find a student that matches',1);
 9086:             next;
 9087:         }
 9088:         if (exists $completedstudents{$uname}) {
 9089:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9090:                                 'Student '.$uname.' has multiple sheets',2);
 9091:             next;
 9092:         }
 9093:         my $pid = $scan_record->{'scantron.ID'};
 9094:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9095:         push(@{$bylast{$lastname{$pid}}},$pid);
 9096:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9097:         my $user = $uname.':'.$usec;
 9098:         ($username,$domain)=split(/:/,$uname);
 9099: 
 9100:         my $scancode;
 9101:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9102:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9103:             $scancode = $scan_record->{'scantron.CODE'};
 9104:         } else {
 9105:             $scancode = '';
 9106:         }
 9107: 
 9108:         my @mapresources = @resources;
 9109:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9110:         my %respnumlookup=();
 9111:         my %startline=();
 9112:         if ($randomorder || $randompick) {
 9113:             @mapresources =
 9114:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9115:                              \%orderedforcode);
 9116:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9117:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9118:                                              \%grader_partids_by_symb,\%orderedforcode,
 9119:                                              \%respnumlookup,\%startline);
 9120:             if ($randompick && $total) {
 9121:                 $lastpos = $total*$scantron_config{'Qlength'};
 9122:             }
 9123:         }
 9124:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9125:         chomp($scandata{$pid});
 9126:         $scandata{$pid} =~ s/\r$//;
 9127: 
 9128:         my $counter = -1;
 9129:         foreach my $resource (@mapresources) {
 9130:             my $parts;
 9131:             my $ressymb = $resource->symb();
 9132:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9133:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9134:                 (my $analysis,$parts) =
 9135:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9136:                                               $username,$domain,undef,
 9137:                                               $bubbles_per_row);
 9138:             } else {
 9139:                 $parts = $grader_partids_by_symb{$ressymb};
 9140:             }
 9141:             ($counter,my $recording) =
 9142:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9143:                                          $scandata{$pid},$parts,
 9144:                                          \%scantron_config,\%lettdig,$numletts,
 9145:                                          $randomorder,$randompick,
 9146:                                          \%respnumlookup,\%startline);
 9147:             $record{$pid} .= $recording;
 9148:         }
 9149:     }
 9150:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9151:     $r->print('<br />');
 9152:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9153:     $passed = 0;
 9154:     $failed = 0;
 9155:     $numstudents = 0;
 9156:     foreach my $last (sort(keys(%bylast))) {
 9157:         if (ref($bylast{$last}) eq 'ARRAY') {
 9158:             foreach my $pid (sort(@{$bylast{$last}})) {
 9159:                 my $showscandata = $scandata{$pid};
 9160:                 my $showrecord = $record{$pid};
 9161:                 $showscandata =~ s/\s/&nbsp;/g;
 9162:                 $showrecord =~ s/\s/&nbsp;/g;
 9163:                 if ($scandata{$pid} eq $record{$pid}) {
 9164:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9165:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9166: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9167: '</tr>'."\n".
 9168: '<tr class="'.$css_class.'">'."\n".
 9169: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 9170:                     $passed ++;
 9171:                 } else {
 9172:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9173:                     $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".
 9174: '</tr>'."\n".
 9175: '<tr class="'.$css_class.'">'."\n".
 9176: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9177: '</tr>'."\n";
 9178:                     $failed ++;
 9179:                 }
 9180:                 $numstudents ++;
 9181:             }
 9182:         }
 9183:     }
 9184:     $r->print('<p>'.
 9185:               &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).',
 9186:                   '<b>',
 9187:                   $numstudents,
 9188:                   '</b>',
 9189:                   $env{'form.scantron_maxbubble'}).
 9190:               '</p>'
 9191:     );
 9192:     $r->print('<p>'
 9193:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9194:              .'<br />'
 9195:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9196:              .'</p>');
 9197:     if ($passed) {
 9198:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9199:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9200:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9201:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9202:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9203:                  $okstudents."\n".
 9204:                  &Apache::loncommon::end_data_table().'<br />');
 9205:     }
 9206:     if ($failed) {
 9207:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9208:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9209:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9210:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9211:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9212:                  $badstudents."\n".
 9213:                  &Apache::loncommon::end_data_table()).'<br />'.
 9214:                  &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.');  
 9215:     }
 9216:     $r->print('</form><br />'.$grading_menu_button);
 9217:     return;
 9218: }
 9219: 
 9220: sub verify_scantron_grading {
 9221:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9222:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9223:         $respnumlookup,$startline) = @_;
 9224:     my ($record,%expected,%startpos);
 9225:     return ($counter,$record) if (!ref($resource));
 9226:     return ($counter,$record) if (!$resource->is_problem());
 9227:     my $symb = $resource->symb();
 9228:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9229:     foreach my $part_id (@{$partids}) {
 9230:         $counter ++;
 9231:         $expected{$part_id} = 0;
 9232:         my $respnum = $counter;
 9233:         if ($randomorder || $randompick) {
 9234:             $respnum = $respnumlookup->{$counter};
 9235:             $startpos{$part_id} = $startline->{$counter} + 1;
 9236:         } else {
 9237:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9238:         }
 9239:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9240:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9241:             foreach my $item (@sub_lines) {
 9242:                 $expected{$part_id} += $item;
 9243:             }
 9244:         } else {
 9245:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9246:         }
 9247:     }
 9248:     if ($symb) {
 9249:         my %recorded;
 9250:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9251:         if ($returnhash{'version'}) {
 9252:             my %lasthash=();
 9253:             my $version;
 9254:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9255:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9256:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9257:                 }
 9258:             }
 9259:             foreach my $key (keys(%lasthash)) {
 9260:                 if ($key =~ /\.scantron$/) {
 9261:                     my $value = &unescape($lasthash{$key});
 9262:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9263:                     if ($value eq '') {
 9264:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9265:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9266:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9267:                             }
 9268:                         }
 9269:                     } else {
 9270:                         my @tocheck;
 9271:                         my @items = split(//,$value);
 9272:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9273:                             ($scantron_config->{'Qon'} eq 'number')) {
 9274:                             if (@items < $expected{$part_id}) {
 9275:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9276:                                 my @singles = split(//,$fragment);
 9277:                                 foreach my $pos (@singles) {
 9278:                                     if ($pos eq ' ') {
 9279:                                         push(@tocheck,$pos);
 9280:                                     } else {
 9281:                                         my $next = shift(@items);
 9282:                                         push(@tocheck,$next);
 9283:                                     }
 9284:                                 }
 9285:                             } else {
 9286:                                 @tocheck = @items;
 9287:                             }
 9288:                             foreach my $letter (@tocheck) {
 9289:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9290:                                     if ($letter !~ /^[A-J]$/) {
 9291:                                         $letter = $scantron_config->{'Qoff'};
 9292:                                     }
 9293:                                     $recorded{$part_id} .= $letter;
 9294:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9295:                                     my $digit;
 9296:                                     if ($letter !~ /^[A-J]$/) {
 9297:                                         $digit = $scantron_config->{'Qoff'};
 9298:                                     } else {
 9299:                                         $digit = $lettdig->{$letter};
 9300:                                     }
 9301:                                     $recorded{$part_id} .= $digit;
 9302:                                 }
 9303:                             }
 9304:                         } else {
 9305:                             @tocheck = @items;
 9306:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9307:                                 my $curr_sub = shift(@tocheck);
 9308:                                 my $digit;
 9309:                                 if ($curr_sub =~ /^[A-J]$/) {
 9310:                                     $digit = $lettdig->{$curr_sub}-1;
 9311:                                 }
 9312:                                 if ($curr_sub eq 'J') {
 9313:                                     $digit += scalar($numletts);
 9314:                                 }
 9315:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9316:                                     if ($j == $digit) {
 9317:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9318:                                     } else {
 9319:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9320:                                     }
 9321:                                 }
 9322:                             }
 9323:                         }
 9324:                     }
 9325:                 }
 9326:             }
 9327:         }
 9328:         foreach my $part_id (@{$partids}) {
 9329:             if ($recorded{$part_id} eq '') {
 9330:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9331:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9332:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9333:                     }
 9334:                 }
 9335:             }
 9336:             $record .= $recorded{$part_id};
 9337:         }
 9338:     }
 9339:     return ($counter,$record);
 9340: }
 9341: 
 9342: sub letter_to_digits {
 9343:     my %lettdig = (
 9344:                     A => 1,
 9345:                     B => 2,
 9346:                     C => 3,
 9347:                     D => 4,
 9348:                     E => 5,
 9349:                     F => 6,
 9350:                     G => 7,
 9351:                     H => 8,
 9352:                     I => 9,
 9353:                     J => 0,
 9354:                   );
 9355:     return %lettdig;
 9356: }
 9357: 
 9358: 
 9359: #-------- end of section for handling grading scantron forms -------
 9360: #
 9361: #-------------------------------------------------------------------
 9362: 
 9363: #-------------------------- Menu interface -------------------------
 9364: #
 9365: #--- Show a Grading Menu button - Calls the next routine ---
 9366: sub show_grading_menu_form {
 9367:     my ($symb)=@_;
 9368:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9369: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9370: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9371: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9372: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9373: 	'</form>'."\n";
 9374:     return $result;
 9375: }
 9376: 
 9377: # -- Retrieve choices for grading form
 9378: sub savedState {
 9379:     my %savedState = ();
 9380:     if ($env{'form.saveState'}) {
 9381: 	foreach (split(/:/,$env{'form.saveState'})) {
 9382: 	    my ($key,$value) = split(/=/,$_,2);
 9383: 	    $savedState{$key} = $value;
 9384: 	}
 9385:     }
 9386:     return \%savedState;
 9387: }
 9388: 
 9389: #--- Href with symb and command ---
 9390: 
 9391: sub href_symb_cmd {
 9392:     my ($symb,$cmd)=@_;
 9393:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9394: }
 9395: 
 9396: sub grading_menu {
 9397:     my ($request) = @_;
 9398:     my ($symb)=&get_symb($request);
 9399:     if (!$symb) {return '';}
 9400:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9401:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9402: 
 9403:     $request->print($table);
 9404:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9405:                   'handgrade'=>$hdgrade,
 9406:                   'probTitle'=>$probTitle,
 9407:                   'command'=>'submit_options',
 9408:                   'saveState'=>"",
 9409:                   'gradingMenu'=>1,
 9410:                   'showgrading'=>"yes");
 9411:     
 9412:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9413:     
 9414:     $fields{'command'} = 'csvform';
 9415:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9416:     
 9417:     $fields{'command'} = 'processclicker';
 9418:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9419:     
 9420:     $fields{'command'} = 'scantron_selectphase';
 9421:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9422:     
 9423:     my @menu = ({	categorytitle=>'Course Grading',
 9424:             items =>[
 9425:                         {	linktext => 'Manual Grading/View Submissions',
 9426:                     		url => $url1,
 9427:                     		permission => 'F',
 9428:                     		icon => 'edit-find-replace.png',
 9429:                     		linktitle => 'Start the process of hand grading submissions.'
 9430:                         },
 9431:                 	    {	linktext => 'Upload Scores',
 9432:                     		url => $url2,
 9433:                     		permission => 'F',
 9434:                     		icon => 'uploadscores.png',
 9435:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9436:                 	    },
 9437:                 	    {	linktext => 'Process Clicker',
 9438:                     		url => $url3,
 9439:                     		permission => 'F',
 9440:                     		icon => 'addClickerInfoFile.png',
 9441:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9442:                 	    },
 9443:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9444:                     		url => $url4,
 9445:                     		permission => 'F',
 9446:                     		icon => 'stat.png',
 9447:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9448:                 	    }
 9449:                     ]
 9450:             });
 9451: 
 9452:     #$fields{'command'} = 'verify';
 9453:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9454:     #
 9455:     # Create the menu
 9456:     my $Str;
 9457:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9458:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9459:     $Str .= '<input type="hidden" name="command" value="" />'.
 9460:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9461: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9462: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9463: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9464: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9465: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9466: 
 9467:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9468:     #$menudata->{'jscript'}
 9469:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9470:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9471:         ' /> '.
 9472:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9473:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9474: 
 9475:     $Str .="</form>\n";
 9476:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9477:     $request->print(<<GRADINGMENUJS);
 9478: <script type="text/javascript" language="javascript">
 9479:     function checkChoice(formname,val,cmdx) {
 9480: 	if (val <= 2) {
 9481: 	    var cmd = radioSelection(formname.radioChoice);
 9482: 	    var cmdsave = cmd;
 9483: 	} else {
 9484: 	    cmd = cmdx;
 9485: 	    cmdsave = 'submission';
 9486: 	}
 9487: 	formname.command.value = cmd;
 9488: 	if (val < 5) formname.submit();
 9489: 	if (val == 5) {
 9490: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9491: 	        return false;
 9492: 	    } else {
 9493: 	        formname.submit();
 9494: 	    }
 9495: 	}
 9496:     }
 9497: 
 9498:     function checkReceiptNo(formname,nospace) {
 9499: 	var receiptNo = formname.receipt.value;
 9500: 	var checkOpt = false;
 9501: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9502: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9503: 	if (checkOpt) {
 9504: 	    alert("$receiptalert");
 9505: 	    formname.receipt.value = "";
 9506: 	    formname.receipt.focus();
 9507: 	    return false;
 9508: 	}
 9509: 	return true;
 9510:     }
 9511: </script>
 9512: GRADINGMENUJS
 9513:     &commonJSfunctions($request);
 9514:     return $Str;    
 9515: }
 9516: 
 9517: 
 9518: #--- Displays the submissions first page -------
 9519: sub submit_options {
 9520:     my ($request) = @_;
 9521:     my ($symb)=&get_symb($request);
 9522:     if (!$symb) {return '';}
 9523:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9524: 
 9525:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9526:     $request->print(<<GRADINGMENUJS);
 9527: <script type="text/javascript" language="javascript">
 9528:     function checkChoice(formname,val,cmdx) {
 9529: 	if (val <= 2) {
 9530: 	    var cmd = radioSelection(formname.radioChoice);
 9531: 	    var cmdsave = cmd;
 9532: 	} else {
 9533: 	    cmd = cmdx;
 9534: 	    cmdsave = 'submission';
 9535: 	}
 9536: 	formname.command.value = cmd;
 9537: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9538: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9539: 	if (val < 5) formname.submit();
 9540: 	if (val == 5) {
 9541: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9542: 	    formname.submit();
 9543: 	}
 9544: 	if (val < 7) formname.submit();
 9545:     }
 9546: 
 9547:     function checkReceiptNo(formname,nospace) {
 9548: 	var receiptNo = formname.receipt.value;
 9549: 	var checkOpt = false;
 9550: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9551: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9552: 	if (checkOpt) {
 9553: 	    alert("$receiptalert");
 9554: 	    formname.receipt.value = "";
 9555: 	    formname.receipt.focus();
 9556: 	    return false;
 9557: 	}
 9558: 	return true;
 9559:     }
 9560: </script>
 9561: GRADINGMENUJS
 9562:     &commonJSfunctions($request);
 9563:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9564:     my $result;
 9565:     my (undef,$sections) = &getclasslist('all','0');
 9566:     my $savedState = &savedState();
 9567:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9568:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9569:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9570:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9571: 
 9572:     # Preselect sections
 9573:     my $selsec="";
 9574:     if (ref($sections)) {
 9575:         foreach my $section (sort(@$sections)) {
 9576:             $selsec.='<option value="'.$section.'" '.
 9577:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9578:         }
 9579:     }
 9580: 
 9581:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9582: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9583: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9584: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9585: 	'<input type="hidden" name="command"     value="" />'."\n".
 9586: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9587: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9588: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9589: 
 9590:     $result.='
 9591: <h2>
 9592:   '.&mt('Grade Current Resource').'
 9593: </h2>
 9594: <div>
 9595:   '.$table.'
 9596: </div>
 9597: 
 9598: <div class="LC_columnSection">
 9599:   
 9600:     <fieldset>
 9601:       <legend>
 9602:        '.&mt('Sections').'
 9603:       </legend>
 9604:       <select name="section" multiple="multiple" size="5">'."\n";
 9605:     $result.= $selsec;
 9606:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9607:     $result.='
 9608:     </fieldset>
 9609:   
 9610:     <fieldset>
 9611:       <legend>
 9612:         '.&mt('Groups').'
 9613:       </legend>
 9614:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9615:     </fieldset>
 9616:   
 9617:     <fieldset>
 9618:       <legend>
 9619:         '.&mt('Access Status').'
 9620:       </legend>
 9621:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9622:     </fieldset>
 9623:   
 9624:     <fieldset>
 9625:       <legend>
 9626:         '.&mt('Submission Status').'
 9627:       </legend>
 9628:       <select name="submitonly" size="5">
 9629: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9630: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9631: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9632: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9633:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9634:       </select>
 9635:     </fieldset>
 9636:   
 9637: </div>
 9638: 
 9639: <br />
 9640:           <div>
 9641:             <div>
 9642:               <label>
 9643:                 <input type="radio" name="radioChoice" value="submission" '.
 9644:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9645:              &mt('Select individual students to grade and view submissions.').'
 9646: 	      </label> 
 9647:             </div>
 9648:             <div>
 9649: 	      <label>
 9650:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9651:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 9652:                     &mt('Grade all selected students in a grading table.').'
 9653:               </label>
 9654:             </div>
 9655:             <div>
 9656: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9657:             </div>
 9658:           </div>
 9659: 
 9660: 
 9661:         <h2>
 9662:          '.&mt('Grade Complete Folder for One Student').'
 9663:         </h2>
 9664:         <div>
 9665:             <div>
 9666:               <label>
 9667:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 9668: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 9669:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 9670:               </label>
 9671:             </div>
 9672:             <div>
 9673: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9674:             </div>
 9675:         </div>
 9676:   </form>';
 9677:     $result .= &show_grading_menu_form($symb);
 9678:     return $result;
 9679: }
 9680: 
 9681: sub reset_perm {
 9682:     undef(%perm);
 9683: }
 9684: 
 9685: sub init_perm {
 9686:     &reset_perm();
 9687:     foreach my $test_perm ('vgr','mgr','opa') {
 9688: 
 9689: 	my $scope = $env{'request.course.id'};
 9690: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9691: 
 9692: 	    $scope .= '/'.$env{'request.course.sec'};
 9693: 	    if ( $perm{$test_perm}=
 9694: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9695: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9696: 	    } else {
 9697: 		delete($perm{$test_perm});
 9698: 	    }
 9699: 	}
 9700:     }
 9701: }
 9702: 
 9703: sub init_old_essays {
 9704:     my ($symb,$apath,$adom,$aname) = @_;
 9705:     if ($symb ne '') {
 9706:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9707:         if (keys(%essays) > 0) {
 9708:             $old_essays{$symb} = \%essays;
 9709:         }
 9710:     }
 9711:     return;
 9712: }
 9713: 
 9714: sub reset_old_essays {
 9715:     undef(%old_essays);
 9716: }
 9717: 
 9718: sub gather_clicker_ids {
 9719:     my %clicker_ids;
 9720: 
 9721:     my $classlist = &Apache::loncoursedata::get_classlist();
 9722: 
 9723:     # Set up a couple variables.
 9724:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9725:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9726:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9727: 
 9728:     foreach my $student (keys(%$classlist)) {
 9729:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9730:         my $username = $classlist->{$student}->[$username_idx];
 9731:         my $domain   = $classlist->{$student}->[$domain_idx];
 9732:         my $clickers =
 9733: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9734:         foreach my $id (split(/\,/,$clickers)) {
 9735:             $id=~s/^[\#0]+//;
 9736:             $id=~s/[\-\:]//g;
 9737:             if (exists($clicker_ids{$id})) {
 9738: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9739:             } else {
 9740: 		$clicker_ids{$id}=$username.':'.$domain;
 9741:             }
 9742:         }
 9743:     }
 9744:     return %clicker_ids;
 9745: }
 9746: 
 9747: sub gather_adv_clicker_ids {
 9748:     my %clicker_ids;
 9749:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9750:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9751:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9752:     foreach my $element (sort(keys(%coursepersonnel))) {
 9753:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9754:             my ($puname,$pudom)=split(/\:/,$person);
 9755:             my $clickers =
 9756: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9757:             foreach my $id (split(/\,/,$clickers)) {
 9758: 		$id=~s/^[\#0]+//;
 9759:                 $id=~s/[\-\:]//g;
 9760: 		if (exists($clicker_ids{$id})) {
 9761: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9762: 		} else {
 9763: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9764: 		}
 9765:             }
 9766:         }
 9767:     }
 9768:     return %clicker_ids;
 9769: }
 9770: 
 9771: sub clicker_grading_parameters {
 9772:     return ('gradingmechanism' => 'scalar',
 9773:             'upfiletype' => 'scalar',
 9774:             'specificid' => 'scalar',
 9775:             'pcorrect' => 'scalar',
 9776:             'pincorrect' => 'scalar');
 9777: }
 9778: 
 9779: sub process_clicker {
 9780:     my ($r)=@_;
 9781:     my ($symb)=&get_symb($r);
 9782:     if (!$symb) {return '';}
 9783:     my $result=&checkforfile_js();
 9784:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 9785:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 9786:     $result.=$table;
 9787:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 9788:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 9789:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 9790:         '</b></td></tr>'."\n";
 9791:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 9792: # Attempt to restore parameters from last session, set defaults if not present
 9793:     my %Saveable_Parameters=&clicker_grading_parameters();
 9794:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9795:                                                  \%Saveable_Parameters);
 9796:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9797:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9798:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9799:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9800: 
 9801:     my %checked;
 9802:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9803:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9804:           $checked{$gradingmechanism}=' checked="checked"';
 9805:        }
 9806:     }
 9807: 
 9808:     my $upload=&mt("Upload File");
 9809:     my $type=&mt("Type");
 9810:     my $attendance=&mt("Award points just for participation");
 9811:     my $personnel=&mt("Correctness determined from response by course personnel");
 9812:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9813:     my $given=&mt("Correctness determined from given list of answers").' '.
 9814:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9815:     my $pcorrect=&mt("Percentage points for correct solution");
 9816:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9817:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9818:                                                    {'iclicker' => 'i>clicker',
 9819:                                                     'interwrite' => 'interwrite PRS',
 9820:                                                     'turning' => 'Turning Technologies'});
 9821:     $symb = &Apache::lonenc::check_encrypt($symb);
 9822:     $result.=<<ENDUPFORM;
 9823: <script type="text/javascript">
 9824: function sanitycheck() {
 9825: // Accept only integer percentages
 9826:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9827:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9828: // Find out grading choice
 9829:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9830:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9831:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9832:       }
 9833:    }
 9834: // By default, new choice equals user selection
 9835:    newgradingchoice=gradingchoice;
 9836: // Not good to give more points for false answers than correct ones
 9837:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9838:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9839:    }
 9840: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9841:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9842:       document.forms.gradesupload.pcorrect.value=100;
 9843:       document.forms.gradesupload.pincorrect.value=100;
 9844:    }
 9845: // If the values are different, cannot be attendance only
 9846:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9847:        (gradingchoice=='attendance')) {
 9848:        newgradingchoice='personnel';
 9849:    }
 9850: // Change grading choice to new one
 9851:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9852:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9853:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9854:       } else {
 9855:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9856:       }
 9857:    }
 9858: // Remember the old state
 9859:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9860: }
 9861: </script>
 9862: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9863: <input type="hidden" name="symb" value="$symb" />
 9864: <input type="hidden" name="command" value="processclickerfile" />
 9865: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9866: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9867: <input type="file" name="upfile" size="50" />
 9868: <br /><label>$type: $selectform</label>
 9869: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9870: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9871: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9872: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9873: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9874: <br />&nbsp;&nbsp;&nbsp;
 9875: <input type="text" name="givenanswer" size="50" />
 9876: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9877: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9878: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9879: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9880: </form>
 9881: ENDUPFORM
 9882:     $result.='</td></tr></table>'."\n".
 9883:              '</td></tr></table><br /><br />'."\n";
 9884:     $result.=&show_grading_menu_form($symb);
 9885:     return $result;
 9886: }
 9887: 
 9888: sub process_clicker_file {
 9889:     my ($r)=@_;
 9890:     my ($symb)=&get_symb($r);
 9891:     if (!$symb) {return '';}
 9892: 
 9893:     my %Saveable_Parameters=&clicker_grading_parameters();
 9894:     &Apache::loncommon::store_course_settings('grades_clicker',
 9895:                                               \%Saveable_Parameters);
 9896: 
 9897:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9898:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9899: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9900: 	return $result.&show_grading_menu_form($symb);
 9901:     }
 9902:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9903:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9904:         return $result.&show_grading_menu_form($symb);
 9905:     }
 9906:     my $foundgiven=0;
 9907:     if ($env{'form.gradingmechanism'} eq 'given') {
 9908:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9909:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9910:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9911:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9912:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9913:         $foundgiven=$#answers+1;
 9914:     }
 9915:     my %clicker_ids=&gather_clicker_ids();
 9916:     my %correct_ids;
 9917:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9918: 	%correct_ids=&gather_adv_clicker_ids();
 9919:     }
 9920:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9921: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9922: 	   $correct_id=~tr/a-z/A-Z/;
 9923: 	   $correct_id=~s/\s//gs;
 9924: 	   $correct_id=~s/^[\#0]+//;
 9925:            $correct_id=~s/[\-\:]//g;
 9926:            if ($correct_id) {
 9927: 	      $correct_ids{$correct_id}='specified';
 9928:            }
 9929:         }
 9930:     }
 9931:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9932: 	$result.=&mt('Score based on attendance only');
 9933:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9934:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9935:     } else {
 9936: 	my $number=0;
 9937: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9938: 	foreach my $id (sort(keys(%correct_ids))) {
 9939: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9940: 	    if ($correct_ids{$id} eq 'specified') {
 9941: 		$result.=&mt('specified');
 9942: 	    } else {
 9943: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9944: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9945: 	    }
 9946: 	    $number++;
 9947: 	}
 9948:         $result.="</p>\n";
 9949: 	if ($number==0) {
 9950: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9951: 	    return $result.&show_grading_menu_form($symb);
 9952: 	}
 9953:     }
 9954:     if (length($env{'form.upfile'}) < 2) {
 9955:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9956: 		     '<span class="LC_error">',
 9957: 		     '</span>',
 9958: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9959:         return $result.&show_grading_menu_form($symb);
 9960:     }
 9961: 
 9962: # Were able to get all the info needed, now analyze the file
 9963: 
 9964:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9965:     $symb = &Apache::lonenc::check_encrypt($symb);
 9966:     my $heading=&mt('Scanning clicker file');
 9967:     $result.=(<<ENDHEADER);
 9968: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9969: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9970: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
 9971: <form method="post" action="/adm/grades" name="clickeranalysis">
 9972: <input type="hidden" name="symb" value="$symb" />
 9973: <input type="hidden" name="command" value="assignclickergrades" />
 9974: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9975: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9976: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9977: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9978: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9979: ENDHEADER
 9980:     if ($env{'form.gradingmechanism'} eq 'given') {
 9981:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9982:     } 
 9983:     my %responses;
 9984:     my @questiontitles;
 9985:     my $errormsg='';
 9986:     my $number=0;
 9987:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9988: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9989:     }
 9990:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9991:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9992:     }
 9993:     if ($env{'form.upfiletype'} eq 'turning') {
 9994:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9995:     }
 9996:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9997:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9998:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9999:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10000:              '<br />';
10001:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10002:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10003:        return $result.&show_grading_menu_form($symb);
10004:     } 
10005: # Remember Question Titles
10006: # FIXME: Possibly need delimiter other than ":"
10007:     for (my $i=0;$i<$number;$i++) {
10008:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10009:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10010:     }
10011:     my $correct_count=0;
10012:     my $student_count=0;
10013:     my $unknown_count=0;
10014: # Match answers with usernames
10015: # FIXME: Possibly need delimiter other than ":"
10016:     foreach my $id (keys(%responses)) {
10017:        if ($correct_ids{$id}) {
10018:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10019:           $correct_count++;
10020:        } elsif ($clicker_ids{$id}) {
10021:           if ($clicker_ids{$id}=~/\,/) {
10022: # More than one user with the same clicker!
10023:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10024:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10025:                            "<select name='multi".$id."'>";
10026:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10027:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10028:              }
10029:              $result.='</select>';
10030:              $unknown_count++;
10031:           } else {
10032: # Good: found one and only one user with the right clicker
10033:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10034:              $student_count++;
10035:           }
10036:        } else {
10037:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10038:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10039:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10040:                    "\n".&mt("Domain").": ".
10041:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10042:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10043:           $unknown_count++;
10044:        }
10045:     }
10046:     $result.='<hr />'.
10047:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10048:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10049:        if ($correct_count==0) {
10050:           $errormsg.="Found no correct answers for grading!";
10051:        } elsif ($correct_count>1) {
10052:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10053:        }
10054:     }
10055:     if ($number<1) {
10056:        $errormsg.="Found no questions.";
10057:     }
10058:     if ($errormsg) {
10059:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10060:     } else {
10061:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10062:     }
10063:     $result.='</form></td></tr></table>'."\n".
10064:              '</td></tr></table><br /><br />'."\n";
10065:     return $result.&show_grading_menu_form($symb);
10066: }
10067: 
10068: sub iclicker_eval {
10069:     my ($questiontitles,$responses)=@_;
10070:     my $number=0;
10071:     my $errormsg='';
10072:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10073:         my %components=&Apache::loncommon::record_sep($line);
10074:         my @entries=map {$components{$_}} (sort(keys(%components)));
10075: 	if ($entries[0] eq 'Question') {
10076: 	    for (my $i=3;$i<$#entries;$i+=6) {
10077: 		$$questiontitles[$number]=$entries[$i];
10078: 		$number++;
10079: 	    }
10080: 	}
10081: 	if ($entries[0]=~/^\#/) {
10082: 	    my $id=$entries[0];
10083: 	    my @idresponses;
10084: 	    $id=~s/^[\#0]+//;
10085: 	    for (my $i=0;$i<$number;$i++) {
10086: 		my $idx=3+$i*6;
10087:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10088: 		push(@idresponses,$entries[$idx]);
10089: 	    }
10090: 	    $$responses{$id}=join(',',@idresponses);
10091: 	}
10092:     }
10093:     return ($errormsg,$number);
10094: }
10095: 
10096: sub interwrite_eval {
10097:     my ($questiontitles,$responses)=@_;
10098:     my $number=0;
10099:     my $errormsg='';
10100:     my $skipline=1;
10101:     my $questionnumber=0;
10102:     my %idresponses=();
10103:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10104:         my %components=&Apache::loncommon::record_sep($line);
10105:         my @entries=map {$components{$_}} (sort(keys(%components)));
10106:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10107:         if ($entries[1] eq 'Response') { $skipline=1; }
10108:         next if $skipline;
10109:         if ($entries[0]!=$questionnumber) {
10110:            $questionnumber=$entries[0];
10111:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10112:            $number++;
10113:         }
10114:         my $id=$entries[4];
10115:         $id=~s/^[\#0]+//;
10116:         $id=~s/^v\d*\://i;
10117:         $id=~s/[\-\:]//g;
10118:         $idresponses{$id}[$number]=$entries[6];
10119:     }
10120:     foreach my $id (keys(%idresponses)) {
10121:        $$responses{$id}=join(',',@{$idresponses{$id}});
10122:        $$responses{$id}=~s/^\s*\,//;
10123:     }
10124:     return ($errormsg,$number);
10125: }
10126: 
10127: sub turning_eval {
10128:     my ($questiontitles,$responses)=@_;
10129:     my $number=0;
10130:     my $errormsg='';
10131:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10132:         my %components=&Apache::loncommon::record_sep($line);
10133:         my @entries=map {$components{$_}} (sort(keys(%components)));
10134:         if ($#entries>$number) { $number=$#entries; }
10135:         my $id=$entries[0];
10136:         my @idresponses;
10137:         $id=~s/^[\#0]+//;
10138:         unless ($id) { next; }
10139:         for (my $idx=1;$idx<=$#entries;$idx++) {
10140:             $entries[$idx]=~s/\,/\;/g;
10141:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10142:             push(@idresponses,$entries[$idx]);
10143:         }
10144:         $$responses{$id}=join(',',@idresponses);
10145:     }
10146:     for (my $i=1; $i<=$number; $i++) {
10147:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10148:     }
10149:     return ($errormsg,$number);
10150: }
10151: 
10152: sub assign_clicker_grades {
10153:     my ($r)=@_;
10154:     my ($symb)=&get_symb($r);
10155:     if (!$symb) {return '';}
10156: # See which part we are saving to
10157:     my $res_error;
10158:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10159:     if ($res_error) {
10160:         return &navmap_errormsg();
10161:     }
10162: # FIXME: This should probably look for the first handgradeable part
10163:     my $part=$$partlist[0];
10164: # Start screen output
10165:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10166: 
10167:     $result .= '<br />'.
10168:                &Apache::loncommon::start_data_table().
10169:                &Apache::loncommon::start_data_table_header_row().
10170:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10171:                &Apache::loncommon::end_data_table_header_row().
10172:                &Apache::loncommon::start_data_table_row().'<td>';
10173: 
10174: # Get correct result
10175: # FIXME: Possibly need delimiter other than ":"
10176:     my @correct=();
10177:     my $gradingmechanism=$env{'form.gradingmechanism'};
10178:     my $number=$env{'form.number'};
10179:     if ($gradingmechanism ne 'attendance') {
10180:        foreach my $key (keys(%env)) {
10181:           if ($key=~/^form\.correct\:/) {
10182:              my @input=split(/\,/,$env{$key});
10183:              for (my $i=0;$i<=$#input;$i++) {
10184:                  if (($correct[$i]) && ($input[$i]) &&
10185:                      ($correct[$i] ne $input[$i])) {
10186:                     $result.='<br /><span class="LC_warning">'.
10187:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10188:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10189:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10190:                     $correct[$i]=$input[$i];
10191:                  }
10192:              }
10193:           }
10194:        }
10195:        for (my $i=0;$i<$number;$i++) {
10196:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10197:              $result.='<br /><span class="LC_error">'.
10198:                       &mt('No correct result given for question "[_1]"!',
10199:                           $env{'form.question:'.$i}).'</span>';
10200:           }
10201:        }
10202:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10203:     }
10204: # Start grading
10205:     my $pcorrect=$env{'form.pcorrect'};
10206:     my $pincorrect=$env{'form.pincorrect'};
10207:     my $storecount=0;
10208:     my %users=();
10209:     foreach my $key (keys(%env)) {
10210:        my $user='';
10211:        if ($key=~/^form\.student\:(.*)$/) {
10212:           $user=$1;
10213:        }
10214:        if ($key=~/^form\.unknown\:(.*)$/) {
10215:           my $id=$1;
10216:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10217:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10218:           } elsif ($env{'form.multi'.$id}) {
10219:              $user=$env{'form.multi'.$id};
10220:           }
10221:        }
10222:        if ($user) {
10223:           if ($users{$user}) {
10224:              $result.='<br /><span class="LC_warning">'.
10225:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10226:                       '</span><br />';
10227:           }
10228:           $users{$user}=1;
10229:           my @answer=split(/\,/,$env{$key});
10230:           my $sum=0;
10231:           my $realnumber=$number;
10232:           for (my $i=0;$i<$number;$i++) {
10233:              if  ($correct[$i] eq '-') {
10234:                 $realnumber--;
10235:              } elsif ($answer[$i]) {
10236:                 if ($gradingmechanism eq 'attendance') {
10237:                    $sum+=$pcorrect;
10238:                 } elsif ($correct[$i] eq '*') {
10239:                    $sum+=$pcorrect;
10240:                 } else {
10241: # We actually grade if correct or not
10242:                    my $increment=$pincorrect;
10243: # Special case: numerical answer "0"
10244:                    if ($correct[$i] eq '0') {
10245:                       if ($answer[$i]=~/^[0\.]+$/) {
10246:                          $increment=$pcorrect;
10247:                       }
10248: # General numerical answer, both evaluate to something non-zero
10249:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10250:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10251:                          $increment=$pcorrect;
10252:                       }
10253: # Must be just alphanumeric
10254:                    } elsif ($answer[$i] eq $correct[$i]) {
10255:                       $increment=$pcorrect;
10256:                    }
10257:                    $sum+=$increment;
10258:                 }
10259:              }
10260:           }
10261:           my $ave=$sum/(100*$realnumber);
10262: # Store
10263:           my ($username,$domain)=split(/\:/,$user);
10264:           my %grades=();
10265:           $grades{"resource.$part.solved"}='correct_by_override';
10266:           $grades{"resource.$part.awarded"}=$ave;
10267:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10268:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10269:                                                  $env{'request.course.id'},
10270:                                                  $domain,$username);
10271:           if ($returncode ne 'ok') {
10272:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10273:           } else {
10274:              $storecount++;
10275:           }
10276:        }
10277:     }
10278: # We are done
10279:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10280:              '</td>'.
10281:              &Apache::loncommon::end_data_table_row().
10282:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10283:     return $result.&show_grading_menu_form($symb);
10284: }
10285: 
10286: sub navmap_errormsg {
10287:     return '<div class="LC_error">'.
10288:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10289:            &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>').
10290:            '</div>';
10291: }
10292: 
10293: sub startpage {
10294:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10295:     if ($nomenu) {
10296:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10297:     } else {
10298:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10299:                                                  {'bread_crumbs' => $crumbs}));
10300:     }
10301:     unless ($nodisplayflag) {
10302:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10303:     }
10304: }
10305: 
10306: sub handler {
10307:     my $request=$_[0];
10308:     &reset_caches();
10309:     if ($request->header_only) {
10310:         &Apache::loncommon::content_type($request,'text/html');
10311:         $request->send_http_header;
10312:         return OK;
10313:     }
10314:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10315: 
10316:     my $symb=&get_symb($request,1);
10317:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10318:     my $command=$commands[0];
10319: 
10320:     if ($#commands > 0) {
10321: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10322:     }
10323: 
10324:     $ssi_error = 0;
10325:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10326:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10327:                                                     {'bread_crumbs' => $brcrum});
10328:     if ($symb eq '' && $command eq '') {
10329: 	if ($env{'user.adv'}) {
10330:             &Apache::loncommon::content_type($request,'text/html');
10331:             $request->send_http_header;
10332:             $request->print($start_page);
10333: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10334: 		($env{'form.codethree'})) {
10335: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10336: 		    $env{'form.codethree'};
10337: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10338: 		    &Apache::lonnet::checkin($token);
10339: 		if ($tsymb) {
10340: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10341: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10342: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10343: 					  ('grade_username' => $tuname,
10344: 					   'grade_domain' => $tudom,
10345: 					   'grade_courseid' => $tcrsid,
10346: 					   'grade_symb' => $tsymb)));
10347: 		    } else {
10348: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10349: 		    }
10350: 		} else {
10351: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10352: 		}
10353: 	    } else {
10354: 		$request->print(&Apache::lonxml::tokeninputfield());
10355: 	    }
10356:         } elsif ($env{'request.course.id'}) {
10357:             &init_perm(); 
10358:             if (!%perm) {
10359:                 $request->internal_redirect('/adm/quickgrades');
10360:                 return OK;
10361:             } else {
10362:                 &Apache::loncommon::content_type($request,'text/html');
10363:                 $request->send_http_header;
10364:                 $request->print($start_page);
10365:             }
10366:         }
10367:     } else {
10368:         &init_perm();
10369:         if (!$env{'request.course.id'}) {
10370:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10371:                     ($command =~ /^scantronupload/)) {
10372:                 # Not in a course.
10373:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10374:                 return HTTP_NOT_ACCEPTABLE;
10375:             }
10376:         } elsif (!%perm) {
10377:             $request->internal_redirect('/adm/quickgrades');
10378:         }
10379:         &Apache::loncommon::content_type($request,'text/html');
10380:         $request->send_http_header;
10381:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10382:             $request->print($start_page); 
10383:         }
10384: 	if ($command eq 'submission' && $perm{'vgr'}) {
10385:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10386:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10387:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10388:                     &choose_task_version_form($symb,$env{'form.student'},
10389:                                               $env{'form.userdom'});
10390:             }
10391:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10392:             if ($versionform) {
10393:                 $request->print($versionform);
10394:             }
10395:             $request->print('<br clear="all" />');
10396: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10397:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10398:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10399:                 &choose_task_version_form($symb,$env{'form.student'},
10400:                                           $env{'form.userdom'},
10401:                                           $env{'form.inhibitmenu'});
10402:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10403:             if ($versionform) {
10404:                 $request->print($versionform);
10405:             }
10406:             $request->print('<br clear="all" />');
10407:             $request->print(&show_previous_task_version($request,$symb));
10408: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10409: 	    &pickStudentPage($request);
10410: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10411: 	    &displayPage($request);
10412: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10413: 	    &updateGradeByPage($request);
10414: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10415: 	    &processGroup($request);
10416: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10417: 	    $request->print(&grading_menu($request));
10418: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10419: 	    $request->print(&submit_options($request));
10420: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10421: 	    $request->print(&viewgrades($request));
10422: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10423: 	    $request->print(&processHandGrade($request));
10424: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10425: 	    $request->print(&editgrades($request));
10426: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10427: 	    $request->print(&verifyreceipt($request));
10428:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10429:             $request->print(&process_clicker($request));
10430:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10431:             $request->print(&process_clicker_file($request));
10432:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10433:             $request->print(&assign_clicker_grades($request));
10434: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10435: 	    $request->print(&upcsvScores_form($request));
10436: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10437: 	    $request->print(&csvupload($request));
10438: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10439: 	    $request->print(&csvuploadmap($request));
10440: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10441: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10442: 		$request->print(&csvuploadoptions($request));
10443: 	    } else {
10444: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10445: 		    $env{'form.upfile_associate'} = 'reverse';
10446: 		} else {
10447: 		    $env{'form.upfile_associate'} = 'forward';
10448: 		}
10449: 		$request->print(&csvuploadmap($request));
10450: 	    }
10451: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10452: 	    $request->print(&csvuploadassign($request));
10453: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10454: 	    $request->print(&scantron_selectphase($request));
10455:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10456:  	    $request->print(&scantron_do_warning($request));
10457: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10458: 	    $request->print(&scantron_validate_file($request));
10459: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10460: 	    $request->print(&scantron_process_students($request));
10461:  	} elsif ($command eq 'scantronupload' && 
10462:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10463: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10464:  	    $request->print(&scantron_upload_scantron_data($request)); 
10465:  	} elsif ($command eq 'scantronupload_save' &&
10466:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10467: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10468:  	    $request->print(&scantron_upload_scantron_data_save($request));
10469:  	} elsif ($command eq 'scantron_download' &&
10470: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10471:  	    $request->print(&scantron_download_scantron_data($request));
10472:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10473:             $request->print(&checkscantron_results($request));     
10474: 	} elsif ($command) {
10475: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10476: 	}
10477:     }
10478:     if ($ssi_error) {
10479: 	&ssi_print_error($request);
10480:     }
10481:     $request->print(&Apache::loncommon::end_page());
10482:     &reset_caches();
10483:     return OK;
10484: }
10485: 
10486: 1;
10487: 
10488: __END__;
10489: 
10490: 
10491: =head1 NAME
10492: 
10493: Apache::grades
10494: 
10495: =head1 SYNOPSIS
10496: 
10497: Handles the viewing of grades.
10498: 
10499: This is part of the LearningOnline Network with CAPA project
10500: described at http://www.lon-capa.org.
10501: 
10502: =head1 OVERVIEW
10503: 
10504: Do an ssi with retries:
10505: While I'd love to factor out this with the vesrion in lonprintout,
10506: 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
10507: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10508: 
10509: At least the logic that drives this has been pulled out into loncommon.
10510: 
10511: 
10512: 
10513: ssi_with_retries - Does the server side include of a resource.
10514:                      if the ssi call returns an error we'll retry it up to
10515:                      the number of times requested by the caller.
10516:                      If we still have a proble, no text is appended to the
10517:                      output and we set some global variables.
10518:                      to indicate to the caller an SSI error occurred.  
10519:                      All of this is supposed to deal with the issues described
10520:                      in LonCAPA BZ 5631 see:
10521:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10522:                      by informing the user that this happened.
10523: 
10524: Parameters:
10525:   resource   - The resource to include.  This is passed directly, without
10526:                interpretation to lonnet::ssi.
10527:   form       - The form hash parameters that guide the interpretation of the resource
10528:                
10529:   retries    - Number of retries allowed before giving up completely.
10530: Returns:
10531:   On success, returns the rendered resource identified by the resource parameter.
10532: Side Effects:
10533:   The following global variables can be set:
10534:    ssi_error                - If an unrecoverable error occurred this becomes true.
10535:                               It is up to the caller to initialize this to false
10536:                               if desired.
10537:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10538:                               of the resource that could not be rendered by the ssi
10539:                               call.
10540:    ssi_error_message   - The error string fetched from the ssi response
10541:                               in the event of an error.
10542: 
10543: 
10544: =head1 HANDLER SUBROUTINE
10545: 
10546: ssi_with_retries()
10547: 
10548: =head1 SUBROUTINES
10549: 
10550: =over
10551: 
10552: =item scantron_get_correction() : 
10553: 
10554:    Builds the interface screen to interact with the operator to fix a
10555:    specific error condition in a specific scanline
10556: 
10557:  Arguments:
10558:     $r           - Apache request object
10559:     $i           - number of the current scanline
10560:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10561:     $scan_config - hash ref as returned from &get_scantron_config()
10562:     $line        - full contents of the current scanline
10563:     $error       - error condition, valid values are
10564:                    'incorrectCODE', 'duplicateCODE',
10565:                    'doublebubble', 'missingbubble',
10566:                    'duplicateID', 'incorrectID'
10567:     $arg         - extra information needed
10568:        For errors:
10569:          - duplicateID   - paper number that this studentID was seen before on
10570:          - duplicateCODE - array ref of the paper numbers this CODE was
10571:                            seen on before
10572:          - incorrectCODE - current incorrect CODE 
10573:          - doublebubble  - array ref of the bubble lines that have double
10574:                            bubble errors
10575:          - missingbubble - array ref of the bubble lines that have missing
10576:                            bubble errors
10577: 
10578:    $randomorder - True if exam folder has randomorder set
10579:    $randompick  - True if exam folder has randompick set
10580:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10581:                      for current line to question number used for same question
10582:                      in "Master Seqence" (as seen by Course Coordinator).
10583:    $startline   - Reference to hash where key is question number (0 is first)
10584:                   and value is number of first bubble line for current student
10585:                   or code-based randompick and/or randomorder.
10586: 
10587: 
10588: =item  scantron_get_maxbubble() : 
10589: 
10590:    Arguments:
10591:        $nav_error  - Reference to scalar which is a flag to indicate a
10592:                       failure to retrieve a navmap object.
10593:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10594:        calling routine should trap the error condition and display the warning
10595:        found in &navmap_errormsg().
10596: 
10597:        $scantron_config - Reference to bubblesheet format configuration hash.
10598: 
10599:    Returns the maximum number of bubble lines that are expected to
10600:    occur. Does this by walking the selected sequence rendering the
10601:    resource and then checking &Apache::lonxml::get_problem_counter()
10602:    for what the current value of the problem counter is.
10603: 
10604:    Caches the results to $env{'form.scantron_maxbubble'},
10605:    $env{'form.scantron.bubble_lines.n'}, 
10606:    $env{'form.scantron.first_bubble_line.n'} and
10607:    $env{"form.scantron.sub_bubblelines.n"}
10608:    which are the total number of bubble lines, the number of bubble
10609:    lines for response n and number of the first bubble line for response n,
10610:    and a comma separated list of numbers of bubble lines for sub-questions
10611:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10612: 
10613: 
10614: =item  scantron_validate_missingbubbles() : 
10615: 
10616:    Validates all scanlines in the selected file to not have any
10617:     answers that don't have bubbles that have not been verified
10618:     to be bubble free.
10619: 
10620: =item  scantron_process_students() : 
10621: 
10622:    Routine that does the actual grading of the bubblesheet information.
10623: 
10624:    The parsed scanline hash is added to %env 
10625: 
10626:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10627:    foreach resource , with the form data of
10628: 
10629: 	'submitted'     =>'scantron' 
10630: 	'grade_target'  =>'grade',
10631: 	'grade_username'=> username of student
10632: 	'grade_domain'  => domain of student
10633: 	'grade_courseid'=> of course
10634: 	'grade_symb'    => symb of resource to grade
10635: 
10636:     This triggers a grading pass. The problem grading code takes care
10637:     of converting the bubbled letter information (now in %env) into a
10638:     valid submission.
10639: 
10640: =item  scantron_upload_scantron_data() :
10641: 
10642:     Creates the screen for adding a new bubblesheet data file to a course.
10643: 
10644: =item  scantron_upload_scantron_data_save() : 
10645: 
10646:    Adds a provided bubble information data file to the course if user
10647:    has the correct privileges to do so. 
10648: 
10649: =item  valid_file() :
10650: 
10651:    Validates that the requested bubble data file exists in the course.
10652: 
10653: =item  scantron_download_scantron_data() : 
10654: 
10655:    Shows a list of the three internal files (original, corrected,
10656:    skipped) for a specific bubblesheet data file that exists in the
10657:    course.
10658: 
10659: =item  scantron_validate_ID() : 
10660: 
10661:    Validates all scanlines in the selected file to not have any
10662:    invalid or underspecified student/employee IDs
10663: 
10664: =item navmap_errormsg() :
10665: 
10666:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10667:    Should be called whenever the request to instantiate a navmap object fails.  
10668: 
10669: =back
10670: 
10671: =cut

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