File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.12: download - view: text, annotated - select for diffs
Tue Dec 18 18:05:48 2012 UTC (11 years, 4 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  - Backport 1.679, 1.680, 1.681, 1.682, 1.683.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.12 2012/12/18 18:05:48 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::bridgetask();
   47: use String::Similarity;
   48: use LONCAPA;
   49: 
   50: use POSIX qw(floor);
   51: 
   52: 
   53: 
   54: my %perm=();
   55: my %old_essays=();
   56: 
   57: #  These variables are used to recover from ssi errors
   58: 
   59: my $ssi_retries = 5;
   60: my $ssi_error;
   61: my $ssi_error_resource;
   62: my $ssi_error_message;
   63: 
   64: 
   65: sub ssi_with_retries {
   66:     my ($resource, $retries, %form) = @_;
   67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   68:     if ($response->is_error) {
   69: 	$ssi_error          = 1;
   70: 	$ssi_error_resource = $resource;
   71: 	$ssi_error_message  = $response->code . " " . $response->message;
   72:     }
   73: 
   74:     return $content;
   75: 
   76: }
   77: #
   78: #  Prodcuces an ssi retry failure error message to the user:
   79: #
   80: 
   81: sub ssi_print_error {
   82:     my ($r) = @_;
   83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   84:     $r->print('
   85: <br />
   86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   87: <p>
   88: '.&mt('Unable to retrieve a resource from a server:').'<br />
   89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   90: '.&mt('Error:').' '.$ssi_error_message.'
   91: </p>
   92: <p>'.
   93: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   95: '</p>');
   96:     return;
   97: }
   98: 
   99: #
  100: # --- Retrieve the parts from the metadata file.---
  101: sub getpartlist {
  102:     my ($symb,$errorref) = @_;
  103: 
  104:     my $navmap   = Apache::lonnavmaps::navmap->new();
  105:     unless (ref($navmap)) {
  106:         if (ref($errorref)) { 
  107:             $$errorref = 'navmap';
  108:             return;
  109:         }
  110:     }
  111:     my $res      = $navmap->getBySymb($symb);
  112:     my $partlist = $res->parts();
  113:     my $url      = $res->src();
  114:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  115: 
  116:     my @stores;
  117:     foreach my $part (@{ $partlist }) {
  118: 	foreach my $key (@metakeys) {
  119: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  120: 	}
  121:     }
  122:     return @stores;
  123: }
  124: 
  125: # --- Get the symbolic name of a problem and the url
  126: sub get_symb {
  127:     my ($request,$silent) = @_;
  128:     my $symb=$env{'form.symb'};
  129:     unless ($symb) {
  130:         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  131:         $symb = &Apache::lonnet::symbread($url);
  132:         if ($symb eq '') { 
  133: 	    if (!$silent) {
  134:                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  135: 	        return ();
  136: 	    }
  137:         }
  138:     }
  139:     &Apache::lonenc::check_decrypt(\$symb);
  140:     return ($symb);
  141: }
  142: 
  143: #--- Format fullname, username:domain if different for display
  144: #--- Use anywhere where the student names are listed
  145: sub nameUserString {
  146:     my ($type,$fullname,$uname,$udom) = @_;
  147:     if ($type eq 'header') {
  148: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  149:     } else {
  150: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  151: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  152:     }
  153: }
  154: 
  155: #--- Get the partlist and the response type for a given problem. ---
  156: #--- Indicate if a response type is coded handgraded or not. ---
  157: sub response_type {
  158:     my ($symb,$response_error) = @_;
  159: 
  160:     my $navmap = Apache::lonnavmaps::navmap->new();
  161:     unless (ref($navmap)) {
  162:         if (ref($response_error)) {
  163:             $$response_error = 1;
  164:         }
  165:         return;
  166:     }
  167:     my $res = $navmap->getBySymb($symb);
  168:     unless (ref($res)) {
  169:         $$response_error = 1;
  170:         return;
  171:     }
  172:     my $partlist = $res->parts();
  173:     my %vPart = 
  174: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  175:     my (%response_types,%handgrade);
  176:     foreach my $part (@{ $partlist }) {
  177: 	next if (%vPart && !exists($vPart{$part}));
  178: 
  179: 	my @types = $res->responseType($part);
  180: 	my @ids = $res->responseIds($part);
  181: 	for (my $i=0; $i < scalar(@ids); $i++) {
  182: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  183: 	    $handgrade{$part.'_'.$ids[$i]} = 
  184: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  185: 				     '.handgrade',$symb);
  186: 	}
  187:     }
  188:     return ($partlist,\%handgrade,\%response_types);
  189: }
  190: 
  191: sub flatten_responseType {
  192:     my ($responseType) = @_;
  193:     my @part_response_id =
  194: 	map { 
  195: 	    my $part = $_;
  196: 	    map {
  197: 		[$part,$_]
  198: 		} sort(keys(%{ $responseType->{$part} }));
  199: 	} sort(keys(%$responseType));
  200:     return @part_response_id;
  201: }
  202: 
  203: sub get_display_part {
  204:     my ($partID,$symb)=@_;
  205:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  206:     if (defined($display) and $display ne '') {
  207:         $display.= ' (<span class="LC_internal_info">'
  208:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  209:     } else {
  210: 	$display=$partID;
  211:     }
  212:     return $display;
  213: }
  214: 
  215: #--- Show resource title
  216: #--- and parts and response type
  217: sub showResourceInfo {
  218:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  219:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  220:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  221:     if (ref($res_error)) {
  222:         if ($$res_error) {
  223:             return;
  224:         }
  225:     }
  226:     $result.=&Apache::loncommon::start_data_table()
  227:             .&Apache::loncommon::start_data_table_header_row();
  228:     if ($checkboxes) {
  229:         $result.='<th>&nbsp;</th>';
  230:     }
  231:     $result.='<th>'.&mt('Problem Part').'</th>'
  232:             .'<th>'.&mt('Res. ID').'</th>'
  233:             .'<th>'.&mt('Type').'</th>'
  234:             .&Apache::loncommon::end_data_table_header_row();
  235:     my %resptype = ();
  236:     my $hdgrade='no';
  237:     my %partsseen;
  238:     foreach my $partID (sort(keys(%$responseType))) {
  239:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  240:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  241:             my $responsetype = $responseType->{$partID}->{$resID};
  242:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  243:             $result.=&Apache::loncommon::start_data_table_row();
  244:             if ($checkboxes) {
  245:                 if (exists($partsseen{$partID})) {
  246:                     $result.="<td>&nbsp;</td>";
  247:                 } else {
  248:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  249:                 }
  250:                 $partsseen{$partID}=1;
  251:             }
  252:             my $display_part=&get_display_part($partID,$symb);
  253:             $result.='<td>'.$display_part.'</td>'
  254:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  255:                     .'<td>'.&mt($responsetype).'</td>'
  256: #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
  257:                     .&Apache::loncommon::end_data_table_row();
  258:         }
  259:     }
  260:     $result.=&Apache::loncommon::end_data_table();
  261:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  262: }
  263: 
  264: sub reset_caches {
  265:     &reset_analyze_cache();
  266:     &reset_perm();
  267:     &reset_old_essays();
  268: }
  269: 
  270: {
  271:     my %analyze_cache;
  272:     my %analyze_cache_formkeys;
  273: 
  274:     sub reset_analyze_cache {
  275: 	undef(%analyze_cache);
  276:         undef(%analyze_cache_formkeys);
  277:     }
  278: 
  279:     sub get_analyze {
  280: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  281: 	my $key = "$symb\0$uname\0$udom";
  282:         if ($type eq 'randomizetry') {
  283:             if ($trial ne '') {
  284:                 $key .= "\0".$trial;
  285:             }
  286:         }
  287: 	if (exists($analyze_cache{$key})) {
  288:             my $getupdate = 0;
  289:             if (ref($add_to_hash) eq 'HASH') {
  290:                 foreach my $item (keys(%{$add_to_hash})) {
  291:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  292:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  293:                             $getupdate = 1;
  294:                             last;
  295:                         }
  296:                     } else {
  297:                         $getupdate = 1;
  298:                     }
  299:                 }
  300:             }
  301:             if (!$getupdate) {
  302:                 return $analyze_cache{$key};
  303:             }
  304:         }
  305: 
  306: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  307: 	$url=&Apache::lonnet::clutter($url);
  308:         my %form = ('grade_target'      => 'analyze',
  309:                     'grade_domain'      => $udom,
  310:                     'grade_symb'        => $symb,
  311:                     'grade_courseid'    =>  $env{'request.course.id'},
  312:                     'grade_username'    => $uname,
  313:                     'grade_noincrement' => $no_increment);
  314:         if ($bubbles_per_row ne '') {
  315:             $form{'bubbles_per_row'} = $bubbles_per_row;
  316:         }
  317:         if ($type eq 'randomizetry') {
  318:             $form{'grade_questiontype'} = $type;
  319:             if ($rndseed ne '') {
  320:                 $form{'grade_rndseed'} = $rndseed;
  321:             }
  322:         }
  323:         if (ref($add_to_hash)) {
  324:             %form = (%form,%{$add_to_hash});
  325:         }
  326: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  327: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  328: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  329:         if (ref($add_to_hash) eq 'HASH') {
  330:             $analyze_cache_formkeys{$key} = $add_to_hash;
  331:         } else {
  332:             $analyze_cache_formkeys{$key} = {};
  333:         }
  334: 	return $analyze_cache{$key} = \%analyze;
  335:     }
  336: 
  337:     sub get_order {
  338: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  339: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  340: 	return $analyze->{"$partid.$respid.shown"};
  341:     }
  342: 
  343:     sub get_radiobutton_correct_foil {
  344: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  345: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  346:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  347:         if (ref($foils) eq 'ARRAY') {
  348: 	    foreach my $foil (@{$foils}) {
  349: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  350: 		    return $foil;
  351: 	        }
  352: 	    }
  353: 	}
  354:     }
  355: 
  356:     sub scantron_partids_tograde {
  357:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  358:         my (%analysis,@parts);
  359:         if (ref($resource)) {
  360:             my $symb = $resource->symb();
  361:             my $add_to_form;
  362:             if ($check_for_randomlist) {
  363:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  364:             }
  365:             my $analyze =
  366:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  367:                              undef,undef,undef,$bubbles_per_row);
  368:             if (ref($analyze) eq 'HASH') {
  369:                 %analysis = %{$analyze};
  370:             }
  371:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  372:                 foreach my $part (@{$analysis{'parts'}}) {
  373:                     my ($id,$respid) = split(/\./,$part);
  374:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  375:                         push(@parts,$part);
  376:                     }
  377:                 }
  378:             }
  379:         }
  380:         return (\%analysis,\@parts);
  381:     }
  382: 
  383: }
  384: 
  385: #--- Clean response type for display
  386: #--- Currently filters option/rank/radiobutton/match/essay/Task
  387: #        response types only.
  388: sub cleanRecord {
  389:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  390: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  391:     my $grayFont = '<span class="LC_internal_info">';
  392:     if ($response =~ /^(option|rank)$/) {
  393: 	my %answer=&Apache::lonnet::str2hash($answer);
  394: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  395: 	my ($toprow,$bottomrow);
  396: 	foreach my $foil (@$order) {
  397: 	    if ($grading{$foil} == 1) {
  398: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  399: 	    } else {
  400: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  401: 	    }
  402: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  403: 	}
  404: 	return '<blockquote><table border="1">'.
  405: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  406: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  407: 	    $bottomrow.'</tr></table></blockquote>';
  408:     } elsif ($response eq 'match') {
  409: 	my %answer=&Apache::lonnet::str2hash($answer);
  410: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  411: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  412: 	my ($toprow,$middlerow,$bottomrow);
  413: 	foreach my $foil (@$order) {
  414: 	    my $item=shift(@items);
  415: 	    if ($grading{$foil} == 1) {
  416: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  417: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  418: 	    } else {
  419: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  420: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  421: 	    }
  422: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  423: 	}
  424: 	return '<blockquote><table border="1">'.
  425: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  426: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  427: 	    $middlerow.'</tr>'.
  428: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  429: 	    $bottomrow.'</tr></table></blockquote>';
  430:     } elsif ($response eq 'radiobutton') {
  431: 	my %answer=&Apache::lonnet::str2hash($answer);
  432: 	my ($toprow,$bottomrow);
  433: 	my $correct = 
  434: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  435: 	foreach my $foil (@$order) {
  436: 	    if (exists($answer{$foil})) {
  437: 		if ($foil eq $correct) {
  438: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  439: 		} else {
  440: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  441: 		}
  442: 	    } else {
  443: 		$toprow.='<td>'.&mt('false').'</td>';
  444: 	    }
  445: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  446: 	}
  447: 	return '<blockquote><table border="1">'.
  448: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  449: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  450: 	    $bottomrow.'</tr></table></blockquote>';
  451:     } elsif ($response eq 'essay') {
  452: 	if (! exists ($env{'form.'.$symb})) {
  453: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  454: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  455: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  456: 
  457: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  458: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  459: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  460: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  461: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  462: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  463: 	}
  464: 	$answer =~ s-\n-<br />-g;
  465: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  466:     } elsif ( $response eq 'organic') {
  467: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  468: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  469: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  470: 	return $result;
  471:     } elsif ( $response eq 'Task') {
  472: 	if ( $answer eq 'SUBMITTED') {
  473: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  474: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  475: 	    return $result;
  476: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  477: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  478: 			       keys(%{$record}));
  479: 	    return join('<br />',($version,@matches));
  480: 			       
  481: 			       
  482: 	} else {
  483: 	    my $result =
  484: 		'<p>'
  485: 		.&mt('Overall result: [_1]',
  486: 		     $record->{$version."resource.$respid.$partid.status"})
  487: 		.'</p>';
  488: 	    
  489: 	    $result .= '<ul>';
  490: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  491: 			     keys(%{$record}));
  492: 	    foreach my $grade (sort(@grade)) {
  493: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  494: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  495: 				     $dim, $record->{$grade}).
  496: 			  '</li>';
  497: 	    }
  498: 	    $result.='</ul>';
  499: 	    return $result;
  500: 	}
  501:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  502: 	$answer = 
  503: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  504: 							      $answer);
  505:     }
  506:     return $answer;
  507: }
  508: 
  509: #-- A couple of common js functions
  510: sub commonJSfunctions {
  511:     my $request = shift;
  512:     $request->print(<<COMMONJSFUNCTIONS);
  513: <script type="text/javascript" language="javascript">
  514:     function radioSelection(radioButton) {
  515: 	var selection=null;
  516: 	if (radioButton.length > 1) {
  517: 	    for (var i=0; i<radioButton.length; i++) {
  518: 		if (radioButton[i].checked) {
  519: 		    return radioButton[i].value;
  520: 		}
  521: 	    }
  522: 	} else {
  523: 	    if (radioButton.checked) return radioButton.value;
  524: 	}
  525: 	return selection;
  526:     }
  527: 
  528:     function pullDownSelection(selectOne) {
  529: 	var selection="";
  530: 	if (selectOne.length > 1) {
  531: 	    for (var i=0; i<selectOne.length; i++) {
  532: 		if (selectOne[i].selected) {
  533: 		    return selectOne[i].value;
  534: 		}
  535: 	    }
  536: 	} else {
  537:             // only one value it must be the selected one
  538: 	    return selectOne.value;
  539: 	}
  540:     }
  541: </script>
  542: COMMONJSFUNCTIONS
  543: }
  544: 
  545: #--- Dumps the class list with usernames,list of sections,
  546: #--- section, ids and fullnames for each user.
  547: sub getclasslist {
  548:     my ($getsec,$filterlist,$getgroup) = @_;
  549:     my @getsec;
  550:     my @getgroup;
  551:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  552:     if (!ref($getsec)) {
  553: 	if ($getsec ne '' && $getsec ne 'all') {
  554: 	    @getsec=($getsec);
  555: 	}
  556:     } else {
  557: 	@getsec=@{$getsec};
  558:     }
  559:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  560:     if (!ref($getgroup)) {
  561: 	if ($getgroup ne '' && $getgroup ne 'all') {
  562: 	    @getgroup=($getgroup);
  563: 	}
  564:     } else {
  565: 	@getgroup=@{$getgroup};
  566:     }
  567:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  568: 
  569:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  570:     # Bail out if we were unable to get the classlist
  571:     return if (! defined($classlist));
  572:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  573:     #
  574:     my %sections;
  575:     my %fullnames;
  576:     foreach my $student (keys(%$classlist)) {
  577:         my $end      = 
  578:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  579:         my $start    = 
  580:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  581:         my $id       = 
  582:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  583:         my $section  = 
  584:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  585:         my $fullname = 
  586:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  587:         my $status   = 
  588:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  589:         my $group   = 
  590:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  591: 	# filter students according to status selected
  592: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  593: 	    if (!($stu_status =~ $status)) {
  594: 		delete($classlist->{$student});
  595: 		next;
  596: 	    }
  597: 	}
  598: 	# filter students according to groups selected
  599: 	my @stu_groups = split(/,/,$group);
  600: 	if (@getgroup) {
  601: 	    my $exclude = 1;
  602: 	    foreach my $grp (@getgroup) {
  603: 	        foreach my $stu_group (@stu_groups) {
  604: 	            if ($stu_group eq $grp) {
  605: 	                $exclude = 0;
  606:     	            } 
  607: 	        }
  608:     	        if (($grp eq 'none') && !$group) {
  609:         	        $exclude = 0;
  610:         	}
  611: 	    }
  612: 	    if ($exclude) {
  613: 	        delete($classlist->{$student});
  614: 	    }
  615: 	}
  616: 	$section = ($section ne '' ? $section : 'none');
  617: 	if (&canview($section)) {
  618: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  619: 		$sections{$section}++;
  620: 		if ($classlist->{$student}) {
  621: 		    $fullnames{$student}=$fullname;
  622: 		}
  623: 	    } else {
  624: 		delete($classlist->{$student});
  625: 	    }
  626: 	} else {
  627: 	    delete($classlist->{$student});
  628: 	}
  629:     }
  630:     my %seen = ();
  631:     my @sections = sort(keys(%sections));
  632:     return ($classlist,\@sections,\%fullnames);
  633: }
  634: 
  635: sub canmodify {
  636:     my ($sec)=@_;
  637:     if ($perm{'mgr'}) {
  638: 	if (!defined($perm{'mgr_section'})) {
  639: 	    # can modify whole class
  640: 	    return 1;
  641: 	} else {
  642: 	    if ($sec eq $perm{'mgr_section'}) {
  643: 		#can modify the requested section
  644: 		return 1;
  645: 	    } else {
  646: 		# can't modify the request section
  647: 		return 0;
  648: 	    }
  649: 	}
  650:     }
  651:     #can't modify
  652:     return 0;
  653: }
  654: 
  655: sub canview {
  656:     my ($sec)=@_;
  657:     if ($perm{'vgr'}) {
  658: 	if (!defined($perm{'vgr_section'})) {
  659: 	    # can modify whole class
  660: 	    return 1;
  661: 	} else {
  662: 	    if ($sec eq $perm{'vgr_section'}) {
  663: 		#can modify the requested section
  664: 		return 1;
  665: 	    } else {
  666: 		# can't modify the request section
  667: 		return 0;
  668: 	    }
  669: 	}
  670:     }
  671:     #can't modify
  672:     return 0;
  673: }
  674: 
  675: #--- Retrieve the grade status of a student for all the parts
  676: sub student_gradeStatus {
  677:     my ($symb,$udom,$uname,$partlist) = @_;
  678:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  679:     my %partstatus = ();
  680:     foreach (@$partlist) {
  681: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  682: 	$status              = 'nothing' if ($status eq '');
  683: 	$partstatus{$_}      = $status;
  684: 	my $subkey           = "resource.$_.submitted_by";
  685: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  686:     }
  687:     return %partstatus;
  688: }
  689: 
  690: # hidden form and javascript that calls the form
  691: # Use by verifyscript and viewgrades
  692: # Shows a student's view of problem and submission
  693: sub jscriptNform {
  694:     my ($symb) = @_;
  695:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  696:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  697: 	'    function viewOneStudent(user,domain) {'."\n".
  698: 	'	document.onestudent.student.value = user;'."\n".
  699: 	'	document.onestudent.userdom.value = domain;'."\n".
  700: 	'	document.onestudent.submit();'."\n".
  701: 	'    }'."\n".
  702: 	'</script>'."\n";
  703:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  704: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  705: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  706: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  707: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  708: 	'<input type="hidden" name="command" value="submission" />'."\n".
  709: 	'<input type="hidden" name="student" value="" />'."\n".
  710: 	'<input type="hidden" name="userdom" value="" />'."\n".
  711: 	'</form>'."\n";
  712:     return $jscript;
  713: }
  714: 
  715: 
  716: 
  717: # Given the score (as a number [0-1] and the weight) what is the final
  718: # point value? This function will round to the nearest tenth, third,
  719: # or quarter if one of those is within the tolerance of .00001.
  720: sub compute_points {
  721:     my ($score, $weight) = @_;
  722:     
  723:     my $tolerance = .00001;
  724:     my $points = $score * $weight;
  725: 
  726:     # Check for nearness to 1/x.
  727:     my $check_for_nearness = sub {
  728:         my ($factor) = @_;
  729:         my $num = ($points * $factor) + $tolerance;
  730:         my $floored_num = floor($num);
  731:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  732:             return $floored_num / $factor;
  733:         }
  734:         return $points;
  735:     };
  736: 
  737:     $points = $check_for_nearness->(10);
  738:     $points = $check_for_nearness->(3);
  739:     $points = $check_for_nearness->(4);
  740:     
  741:     return $points;
  742: }
  743: 
  744: #------------------ End of general use routines --------------------
  745: 
  746: #
  747: # Find most similar essay
  748: #
  749: 
  750: sub most_similar {
  751:     my ($uname,$udom,$symb,$uessay)=@_;
  752: 
  753:     unless ($symb) { return ''; }
  754: 
  755:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  756: 
  757: # ignore spaces and punctuation
  758: 
  759:     $uessay=~s/\W+/ /gs;
  760: 
  761: # ignore empty submissions (occuring when only files are sent)
  762: 
  763:     unless ($uessay=~/\w+/s) { return ''; }
  764: 
  765: # these will be returned. Do not care if not at least 50 percent similar
  766:     my $limit=0.6;
  767:     my $sname='';
  768:     my $sdom='';
  769:     my $scrsid='';
  770:     my $sessay='';
  771: # go through all essays ...
  772:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  773: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  774: # ... except the same student
  775:         next if (($tname eq $uname) && ($tdom eq $udom));
  776: 	my $tessay=$old_essays{$symb}{$tkey};
  777: 	$tessay=~s/\W+/ /gs;
  778: # String similarity gives up if not even limit
  779: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  780: # Found one
  781: 	if ($tsimilar>$limit) {
  782: 	    $limit=$tsimilar;
  783: 	    $sname=$tname;
  784: 	    $sdom=$tdom;
  785: 	    $scrsid=$tcrsid;
  786: 	    $sessay=$old_essays{$symb}{$tkey};
  787: 	}
  788:     }
  789:     if ($limit>0.6) {
  790:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  791:     } else {
  792:        return ('','','','',0);
  793:     }
  794: }
  795: 
  796: #-------------------------------------------------------------------
  797: 
  798: #------------------------------------ Receipt Verification Routines
  799: #
  800: #--- Check whether a receipt number is valid.---
  801: sub verifyreceipt {
  802:     my $request  = shift;
  803: 
  804:     my $courseid = $env{'request.course.id'};
  805:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  806: 	$env{'form.receipt'};
  807:     $receipt     =~ s/[^\-\d]//g;
  808:     my ($symb)   = &get_symb($request);
  809: 
  810:     my $title.=
  811: 	'<h3><span class="LC_info">'.
  812: 	&mt('Verifying Receipt No. [_1]',$receipt).
  813: 	'</span></h3>'."\n".
  814: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  815: 	'</h4>'."\n";
  816: 
  817:     my ($string,$contents,$matches) = ('','',0);
  818:     my (undef,undef,$fullname) = &getclasslist('all','0');
  819:     
  820:     my $receiptparts=0;
  821:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  822: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  823:     my $parts=['0'];
  824:     if ($receiptparts) {
  825:         my $res_error; 
  826:         ($parts)=&response_type($symb,\$res_error);
  827:         if ($res_error) {
  828:             return &navmap_errormsg();
  829:         } 
  830:     }
  831:     
  832:     my $header = 
  833: 	&Apache::loncommon::start_data_table().
  834: 	&Apache::loncommon::start_data_table_header_row().
  835: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  836: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  837: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  838:     if ($receiptparts) {
  839: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  840:     }
  841:     $header.=
  842: 	&Apache::loncommon::end_data_table_header_row();
  843: 
  844:     foreach (sort 
  845: 	     {
  846: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  847: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  848: 		 }
  849: 		 return $a cmp $b;
  850: 	     } (keys(%$fullname))) {
  851: 	my ($uname,$udom)=split(/\:/);
  852: 	foreach my $part (@$parts) {
  853: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  854: 		$contents.=
  855: 		    &Apache::loncommon::start_data_table_row().
  856: 		    '<td>&nbsp;'."\n".
  857: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  858: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  859: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  860: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  861: 		if ($receiptparts) {
  862: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  863: 		}
  864: 		$contents.= 
  865: 		    &Apache::loncommon::end_data_table_row()."\n";
  866: 		
  867: 		$matches++;
  868: 	    }
  869: 	}
  870:     }
  871:     if ($matches == 0) {
  872:         $string = $title
  873:                  .'<p class="LC_warning">'
  874:                  .&mt('No match found for the above receipt number.')
  875:                  .'</p>';
  876:     } else {
  877: 	$string = &jscriptNform($symb).$title.
  878: 	    '<p>'.
  879: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  880: 	    '</p>'.
  881: 	    $header.
  882: 	    $contents.
  883: 	    &Apache::loncommon::end_data_table()."\n";
  884:     }
  885:     return $string.&show_grading_menu_form($symb);
  886: }
  887: 
  888: #--- This is called by a number of programs.
  889: #--- Called from the Grading Menu - View/Grade an individual student
  890: #--- Also called directly when one clicks on the subm button 
  891: #    on the problem page.
  892: sub listStudents {
  893:     my ($request) = shift;
  894: 
  895:     my ($symb) = &get_symb($request);
  896:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  897:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  898:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  899:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  900:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  901:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  902:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  903: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  904: 
  905:     my $result='<h3><span class="LC_info">&nbsp;'
  906: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  907: 	.'</span></h3>';
  908: 
  909:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  910: 
  911:     my %lt = &Apache::lonlocal::texthash (
  912: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  913: 		'single'   => 'Please select the student before clicking on the Next button.',
  914: 	     );
  915:     $request->print(<<LISTJAVASCRIPT);
  916: <script type="text/javascript" language="javascript">
  917:     function checkSelect(checkBox) {
  918: 	var ctr=0;
  919: 	var sense="";
  920: 	if (checkBox.length > 1) {
  921: 	    for (var i=0; i<checkBox.length; i++) {
  922: 		if (checkBox[i].checked) {
  923: 		    ctr++;
  924: 		}
  925: 	    }
  926: 	    sense = '$lt{'multiple'}';
  927: 	} else {
  928: 	    if (checkBox.checked) {
  929: 		ctr = 1;
  930: 	    }
  931: 	    sense = '$lt{'single'}';
  932: 	}
  933: 	if (ctr == 0) {
  934: 	    alert(sense);
  935: 	    return false;
  936: 	}
  937: 	document.gradesub.submit();
  938:     }
  939: 
  940:     function reLoadList(formname) {
  941: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  942: 	formname.command.value = 'submission';
  943: 	formname.submit();
  944:     }
  945: </script>
  946: LISTJAVASCRIPT
  947: 
  948:     &commonJSfunctions($request);
  949:     $request->print($result);
  950: 
  951:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  952:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  953:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  954: 	"\n".$table;
  955: 	
  956:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  957:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  958:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  959:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  960:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  961:                   .&Apache::lonhtmlcommon::row_closure();
  962:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  963:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  964:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  965:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  966:                   .&Apache::lonhtmlcommon::row_closure();
  967: 
  968:     my $submission_options;
  969:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  970: 	$submission_options.=
  971: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  972:     }
  973:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  974:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  975:     $env{'form.Status'} = $saveStatus;
  976:     $submission_options.=
  977:         '<span class="LC_nobreak">'.
  978:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  979:         &mt('last submission only').' </label></span>'."\n".
  980:         '<span class="LC_nobreak">'.
  981:         '<label><input type="radio" name="lastSub" value="last" /> '.
  982:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  983:         '<span class="LC_nobreak">'.
  984:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  985:         &mt('by dates and submissions').'</label></span>'."\n".
  986:         '<span class="LC_nobreak">'.
  987:         '<label><input type="radio" name="lastSub" value="all" /> '.
  988:         &mt('all details').'</label></span>';
  989:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  990:                   .$submission_options
  991:                   .&Apache::lonhtmlcommon::row_closure();
  992: 
  993:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  994:                   .'<select name="increment">'
  995:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  996:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  997:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  998:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  999:                   .'</select>'
 1000:                   .&Apache::lonhtmlcommon::row_closure();
 1001: 
 1002:     $gradeTable .= 
 1003:         &build_section_inputs().
 1004: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1005: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1006: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1007: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1008: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1009: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1010: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1011: 
 1012:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1013: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1014:     } else {
 1015:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1016:                       .&Apache::lonhtmlcommon::StatusOptions(
 1017:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1018:                       .&Apache::lonhtmlcommon::row_closure();
 1019:     }
 1020: 
 1021:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1022:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1023:                   .&Apache::lonhtmlcommon::row_closure(1)
 1024:                   .&Apache::lonhtmlcommon::end_pick_box();
 1025: 
 1026:     $gradeTable .= '<p>'
 1027:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
 1028:                   .'<input type="hidden" name="command" value="processGroup" />'
 1029:                   .'</p>';
 1030: 
 1031: # checkall buttons
 1032:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1033:     $gradeTable.='<input type="button" '."\n".
 1034:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1035:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1036:     $gradeTable.=&check_buttons();
 1037:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1038:     $gradeTable.= &Apache::loncommon::start_data_table().
 1039: 	&Apache::loncommon::start_data_table_header_row();
 1040:     my $loop = 0;
 1041:     while ($loop < 2) {
 1042: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1043: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1044: 	if ($env{'form.showgrading'} eq 'yes' 
 1045: 	    && $submitonly ne 'queued'
 1046: 	    && $submitonly ne 'all') {
 1047: 	    foreach my $part (sort(@$partlist)) {
 1048: 		my $display_part=
 1049: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1050: 		$gradeTable.=
 1051: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1052: 	    }
 1053: 	} elsif ($submitonly eq 'queued') {
 1054: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1055: 	}
 1056: 	$loop++;
 1057: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1058:     }
 1059:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1060: 
 1061:     my $ctr = 0;
 1062:     foreach my $student (sort 
 1063: 			 {
 1064: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1065: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1066: 			     }
 1067: 			     return $a cmp $b;
 1068: 			 }
 1069: 			 (keys(%$fullname))) {
 1070: 	my ($uname,$udom) = split(/:/,$student);
 1071: 
 1072: 	my %status = ();
 1073: 
 1074: 	if ($submitonly eq 'queued') {
 1075: 	    my %queue_status = 
 1076: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1077: 							$udom,$uname);
 1078: 	    next if (!defined($queue_status{'gradingqueue'}));
 1079: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1080: 	}
 1081: 
 1082: 	if ($env{'form.showgrading'} eq 'yes' 
 1083: 	    && $submitonly ne 'queued'
 1084: 	    && $submitonly ne 'all') {
 1085: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1086: 	    my $submitted = 0;
 1087: 	    my $graded = 0;
 1088: 	    my $incorrect = 0;
 1089: 	    foreach (keys(%status)) {
 1090: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1091: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1092: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1093: 		
 1094: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1095: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1096: 		    $submitted = 0;
 1097: 		    my ($part)=split(/\./,$partid);
 1098: 		    $gradeTable.='<input type="hidden" name="'.
 1099: 			$student.':'.$part.':submitted_by" value="'.
 1100: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1101: 		}
 1102: 	    }
 1103: 	    
 1104: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1105: 				     $submitonly eq 'incorrect' ||
 1106: 				     $submitonly eq 'graded'));
 1107: 	    next if (!$graded && ($submitonly eq 'graded'));
 1108: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1109: 	}
 1110: 
 1111: 	$ctr++;
 1112: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1113:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1114: 	if ( $perm{'vgr'} eq 'F' ) {
 1115: 	    if ($ctr%2 ==1) {
 1116: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1117: 	    }
 1118: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1119:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1120:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1121: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1122: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1123: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1124: 
 1125: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1126: 		foreach (sort(keys(%status))) {
 1127: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1128: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1129: 		}
 1130: 	    }
 1131: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1132: 	    if ($ctr%2 ==0) {
 1133: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1134: 	    }
 1135: 	}
 1136:     }
 1137:     if ($ctr%2 ==1) {
 1138: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1139: 	    if ($env{'form.showgrading'} eq 'yes' 
 1140: 		&& $submitonly ne 'queued'
 1141: 		&& $submitonly ne 'all') {
 1142: 		foreach (@$partlist) {
 1143: 		    $gradeTable.='<td>&nbsp;</td>';
 1144: 		}
 1145: 	    } elsif ($submitonly eq 'queued') {
 1146: 		$gradeTable.='<td>&nbsp;</td>';
 1147: 	    }
 1148: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1149:     }
 1150: 
 1151:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1152:         '<input type="button" '.
 1153:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1154:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1155:     if ($ctr == 0) {
 1156: 	my $num_students=(scalar(keys(%$fullname)));
 1157: 	if ($num_students eq 0) {
 1158: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1159: 	} else {
 1160: 	    my $submissions='submissions';
 1161: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1162: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1163: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1164: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1165: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1166: 		    $num_students).
 1167: 		'</span><br />';
 1168: 	}
 1169:     } elsif ($ctr == 1) {
 1170: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1171:     }
 1172:     $gradeTable.=&show_grading_menu_form($symb);
 1173:     $request->print($gradeTable);
 1174:     return '';
 1175: }
 1176: 
 1177: #---- Called from the listStudents routine
 1178: 
 1179: sub check_script {
 1180:     my ($form, $type)=@_;
 1181:     my $chkallscript='<script type="text/javascript">
 1182:     function checkall() {
 1183:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1184:             ele = document.forms.'.$form.'.elements[i];
 1185:             if (ele.name == "'.$type.'") {
 1186:             document.forms.'.$form.'.elements[i].checked=true;
 1187:                                        }
 1188:         }
 1189:     }
 1190: 
 1191:     function checksec() {
 1192:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1193:             ele = document.forms.'.$form.'.elements[i];
 1194:            string = document.forms.'.$form.'.chksec.value;
 1195:            if
 1196:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1197:               document.forms.'.$form.'.elements[i].checked=true;
 1198:             }
 1199:         }
 1200:     }
 1201: 
 1202: 
 1203:     function uncheckall() {
 1204:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1205:             ele = document.forms.'.$form.'.elements[i];
 1206:             if (ele.name == "'.$type.'") {
 1207:             document.forms.'.$form.'.elements[i].checked=false;
 1208:                                        }
 1209:         }
 1210:     }
 1211: 
 1212: </script>'."\n";
 1213:     return $chkallscript;
 1214: }
 1215: 
 1216: sub check_buttons {
 1217:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1218:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1219:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1220:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1221:     return $buttons;
 1222: }
 1223: 
 1224: #     Displays the submissions for one student or a group of students
 1225: sub processGroup {
 1226:     my ($request)  = shift;
 1227:     my $ctr        = 0;
 1228:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1229:     my $total      = scalar(@stuchecked)-1;
 1230: 
 1231:     foreach my $student (@stuchecked) {
 1232: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1233: 	$env{'form.student'}        = $uname;
 1234: 	$env{'form.userdom'}        = $udom;
 1235: 	$env{'form.fullname'}       = $fullname;
 1236: 	&submission($request,$ctr,$total);
 1237: 	$ctr++;
 1238:     }
 1239:     return '';
 1240: }
 1241: 
 1242: #------------------------------------------------------------------------------------
 1243: #
 1244: #-------------------------- Next few routines handles grading by student, essentially
 1245: #                           handles essay response type problem/part
 1246: #
 1247: #--- Javascript to handle the submission page functionality ---
 1248: sub sub_page_js {
 1249:     my $request = shift;
 1250: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1251:     $request->print(<<SUBJAVASCRIPT);
 1252: <script type="text/javascript" language="javascript">
 1253:     function updateRadio(formname,id,weight) {
 1254: 	var gradeBox = formname["GD_BOX"+id];
 1255: 	var radioButton = formname["RADVAL"+id];
 1256: 	var oldpts = formname["oldpts"+id].value;
 1257: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1258: 	gradeBox.value = pts;
 1259: 	var resetbox = false;
 1260: 	if (isNaN(pts) || pts < 0) {
 1261: 	    alert("$alertmsg"+pts);
 1262: 	    for (var i=0; i<radioButton.length; i++) {
 1263: 		if (radioButton[i].checked) {
 1264: 		    gradeBox.value = i;
 1265: 		    resetbox = true;
 1266: 		}
 1267: 	    }
 1268: 	    if (!resetbox) {
 1269: 		formtextbox.value = "";
 1270: 	    }
 1271: 	    return;
 1272: 	}
 1273: 
 1274: 	if (pts > weight) {
 1275: 	    var resp = confirm("You entered a value ("+pts+
 1276: 			       ") greater than the weight for the part. Accept?");
 1277: 	    if (resp == false) {
 1278: 		gradeBox.value = oldpts;
 1279: 		return;
 1280: 	    }
 1281: 	}
 1282: 
 1283: 	for (var i=0; i<radioButton.length; i++) {
 1284: 	    radioButton[i].checked=false;
 1285: 	    if (pts == i && pts != "") {
 1286: 		radioButton[i].checked=true;
 1287: 	    }
 1288: 	}
 1289: 	updateSelect(formname,id);
 1290: 	formname["stores"+id].value = "0";
 1291:     }
 1292: 
 1293:     function writeBox(formname,id,pts) {
 1294: 	var gradeBox = formname["GD_BOX"+id];
 1295: 	if (checkSolved(formname,id) == 'update') {
 1296: 	    gradeBox.value = pts;
 1297: 	} else {
 1298: 	    var oldpts = formname["oldpts"+id].value;
 1299: 	    gradeBox.value = oldpts;
 1300: 	    var radioButton = formname["RADVAL"+id];
 1301: 	    for (var i=0; i<radioButton.length; i++) {
 1302: 		radioButton[i].checked=false;
 1303: 		if (i == oldpts) {
 1304: 		    radioButton[i].checked=true;
 1305: 		}
 1306: 	    }
 1307: 	}
 1308: 	formname["stores"+id].value = "0";
 1309: 	updateSelect(formname,id);
 1310: 	return;
 1311:     }
 1312: 
 1313:     function clearRadBox(formname,id) {
 1314: 	if (checkSolved(formname,id) == 'noupdate') {
 1315: 	    updateSelect(formname,id);
 1316: 	    return;
 1317: 	}
 1318: 	gradeSelect = formname["GD_SEL"+id];
 1319: 	for (var i=0; i<gradeSelect.length; i++) {
 1320: 	    if (gradeSelect[i].selected) {
 1321: 		var selectx=i;
 1322: 	    }
 1323: 	}
 1324: 	var stores = formname["stores"+id];
 1325: 	if (selectx == stores.value) { return };
 1326: 	var gradeBox = formname["GD_BOX"+id];
 1327: 	gradeBox.value = "";
 1328: 	var radioButton = formname["RADVAL"+id];
 1329: 	for (var i=0; i<radioButton.length; i++) {
 1330: 	    radioButton[i].checked=false;
 1331: 	}
 1332: 	stores.value = selectx;
 1333:     }
 1334: 
 1335:     function checkSolved(formname,id) {
 1336: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1337: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1338: 	    if (!reply) {return "noupdate";}
 1339: 	    formname.overRideScore.value = 'yes';
 1340: 	}
 1341: 	return "update";
 1342:     }
 1343: 
 1344:     function updateSelect(formname,id) {
 1345: 	formname["GD_SEL"+id][0].selected = true;
 1346: 	return;
 1347:     }
 1348: 
 1349: //=========== Check that a point is assigned for all the parts  ============
 1350:     function checksubmit(formname,val,total,parttot) {
 1351: 	formname.gradeOpt.value = val;
 1352: 	if (val == "Save & Next") {
 1353: 	    for (i=0;i<=total;i++) {
 1354: 		for (j=0;j<parttot;j++) {
 1355: 		    var partid = formname["partid"+i+"_"+j].value;
 1356: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1357: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1358: 			if (points == "") {
 1359: 			    var name = formname["name"+i].value;
 1360: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1361: 			    var resp = confirm("You did not assign a score for "+studentID+
 1362: 					       ", part "+partid+". Continue?");
 1363: 			    if (resp == false) {
 1364: 				formname["GD_BOX"+i+"_"+partid].focus();
 1365: 				return false;
 1366: 			    }
 1367: 			}
 1368: 		    }
 1369: 		    
 1370: 		}
 1371: 	    }
 1372: 	    
 1373: 	}
 1374: 	if (val == "Grade Student") {
 1375: 	    formname.showgrading.value = "yes";
 1376: 	    if (formname.Status.value == "") {
 1377: 		formname.Status.value = "Active";
 1378: 	    }
 1379: 	    formname.studentNo.value = total;
 1380: 	}
 1381: 	formname.submit();
 1382:     }
 1383: 
 1384: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1385:     function checkSubmitPage(formname,total) {
 1386: 	noscore = new Array(100);
 1387: 	var ptr = 0;
 1388: 	for (i=1;i<total;i++) {
 1389: 	    var partid = formname["q_"+i].value;
 1390: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1391: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1392: 		var status = formname["solved"+i+"_"+partid].value;
 1393: 		if (points == "" && status != "correct_by_student") {
 1394: 		    noscore[ptr] = i;
 1395: 		    ptr++;
 1396: 		}
 1397: 	    }
 1398: 	}
 1399: 	if (ptr != 0) {
 1400: 	    var sense = ptr == 1 ? ": " : "s: ";
 1401: 	    var prolist = "";
 1402: 	    if (ptr == 1) {
 1403: 		prolist = noscore[0];
 1404: 	    } else {
 1405: 		var i = 0;
 1406: 		while (i < ptr-1) {
 1407: 		    prolist += noscore[i]+", ";
 1408: 		    i++;
 1409: 		}
 1410: 		prolist += "and "+noscore[i];
 1411: 	    }
 1412: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1413: 	    if (resp == false) {
 1414: 		return false;
 1415: 	    }
 1416: 	}
 1417: 
 1418: 	formname.submit();
 1419:     }
 1420: </script>
 1421: SUBJAVASCRIPT
 1422: }
 1423: 
 1424: #--- javascript for essay type problem --
 1425: sub sub_page_kw_js {
 1426:     my $request = shift;
 1427:     my $iconpath = $request->dir_config('lonIconsURL');
 1428:     &commonJSfunctions($request);
 1429: 
 1430:     my $inner_js_msg_central=<<INNERJS;
 1431:     <script text="text/javascript">
 1432:     function checkInput() {
 1433:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1434:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1435:       var usrctr = document.msgcenter.usrctr.value;
 1436:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1437:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1438: 
 1439:       var msgchk = "";
 1440:       if (document.msgcenter.subchk.checked) {
 1441:          msgchk = "msgsub,";
 1442:       }
 1443:       var includemsg = 0;
 1444:       for (var i=1; i<=nmsg; i++) {
 1445:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1446:           var frmmsg = document.msgcenter["msg"+i];
 1447:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1448:           var showflg = opener.document.SCORE["shownOnce"+i];
 1449:           showflg.value = "1";
 1450:           var chkbox = document.msgcenter["msgn"+i];
 1451:           if (chkbox.checked) {
 1452:              msgchk += "savemsg"+i+",";
 1453:              includemsg = 1;
 1454:           }
 1455:       }
 1456:       if (document.msgcenter.newmsgchk.checked) {
 1457:          msgchk += "newmsg"+usrctr;
 1458:          includemsg = 1;
 1459:       }
 1460:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1461:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1462:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1463:       includemsg.value = msgchk;
 1464: 
 1465:       self.close()
 1466: 
 1467:     }
 1468:     </script>
 1469: INNERJS
 1470: 
 1471:     my $inner_js_highlight_central=<<INNERJS;
 1472:  <script type="text/javascript">
 1473:     function updateChoice(flag) {
 1474:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1475:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1476:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1477:       opener.document.SCORE.refresh.value = "on";
 1478:       if (opener.document.SCORE.keywords.value!=""){
 1479:          opener.document.SCORE.submit();
 1480:       }
 1481:       self.close()
 1482:     }
 1483: </script>
 1484: INNERJS
 1485: 
 1486:     my $start_page_msg_central = 
 1487:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1488: 				       {'js_ready'  => 1,
 1489: 					'only_body' => 1,
 1490: 					'bgcolor'   =>'#FFFFFF',});
 1491:     my $end_page_msg_central = 
 1492: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1493: 
 1494: 
 1495:     my $start_page_highlight_central = 
 1496:         &Apache::loncommon::start_page('Highlight Central',
 1497: 				       $inner_js_highlight_central,
 1498: 				       {'js_ready'  => 1,
 1499: 					'only_body' => 1,
 1500: 					'bgcolor'   =>'#FFFFFF',});
 1501:     my $end_page_highlight_central = 
 1502: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1503: 
 1504:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1505:     $docopen=~s/^document\.//;
 1506:     my %lt = &Apache::lonlocal::texthash(
 1507:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1508:                 plse => 'Please select a word or group of words from document and then click this link.',
 1509:                 adds => 'Add selection to keyword list? Edit if desired.',
 1510:                 comp => 'Compose Message for: ',
 1511:                 incl => 'Include',
 1512:                 type => 'Type',
 1513:                 subj => 'Subject',
 1514:                 mesa => 'Message',
 1515:                 new  => 'New',
 1516:                 save => 'Save',
 1517:                 canc => 'Cancel',
 1518:                 kehi => 'Keyword Highlight Options',
 1519:                 txtc => 'Text Color',
 1520:                 font => 'Font Size',
 1521:                 fnst => 'Font Style',
 1522:              );
 1523:     $request->print(<<SUBJAVASCRIPT);
 1524: <script type="text/javascript" language="javascript">
 1525: 
 1526: //===================== Show list of keywords ====================
 1527:   function keywords(formname) {
 1528:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1529:     if (nret==null) return;
 1530:     formname.keywords.value = nret;
 1531: 
 1532:     if (formname.keywords.value != "") {
 1533: 	formname.refresh.value = "on";
 1534: 	formname.submit();
 1535:     }
 1536:     return;
 1537:   }
 1538: 
 1539: //===================== Script to view submitted by ==================
 1540:   function viewSubmitter(submitter) {
 1541:     document.SCORE.refresh.value = "on";
 1542:     document.SCORE.NCT.value = "1";
 1543:     document.SCORE.unamedom0.value = submitter;
 1544:     document.SCORE.submit();
 1545:     return;
 1546:   }
 1547: 
 1548: //===================== Script to add keyword(s) ==================
 1549:   function getSel() {
 1550:     if (document.getSelection) txt = document.getSelection();
 1551:     else if (document.selection) txt = document.selection.createRange().text;
 1552:     else return;
 1553:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1554:     if (cleantxt=="") {
 1555: 	alert("$lt{'plse'}");
 1556: 	return;
 1557:     }
 1558:     var nret = prompt("$lt{'adds'}",cleantxt);
 1559:     if (nret==null) return;
 1560:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1561:     if (document.SCORE.keywords.value != "") {
 1562: 	document.SCORE.refresh.value = "on";
 1563: 	document.SCORE.submit();
 1564:     }
 1565:     return;
 1566:   }
 1567: 
 1568: //====================== Script for composing message ==============
 1569:    // preload images
 1570:    img1 = new Image();
 1571:    img1.src = "$iconpath/mailbkgrd.gif";
 1572:    img2 = new Image();
 1573:    img2.src = "$iconpath/mailto.gif";
 1574: 
 1575:   function msgCenter(msgform,usrctr,fullname) {
 1576:     var Nmsg  = msgform.savemsgN.value;
 1577:     savedMsgHeader(Nmsg,usrctr,fullname);
 1578:     var subject = msgform.msgsub.value;
 1579:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1580:     re = /msgsub/;
 1581:     var shwsel = "";
 1582:     if (re.test(msgchk)) { shwsel = "checked" }
 1583:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1584:     displaySubject(checkEntities(subject),shwsel);
 1585:     for (var i=1; i<=Nmsg; i++) {
 1586: 	var testmsg = "savemsg"+i+",";
 1587: 	re = new RegExp(testmsg,"g");
 1588: 	shwsel = "";
 1589: 	if (re.test(msgchk)) { shwsel = "checked" }
 1590: 	var message = document.SCORE["savemsg"+i].value;
 1591: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1592: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1593: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1594:     }
 1595:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1596:     shwsel = "";
 1597:     re = /newmsg/;
 1598:     if (re.test(msgchk)) { shwsel = "checked" }
 1599:     newMsg(newmsg,shwsel);
 1600:     msgTail(); 
 1601:     return;
 1602:   }
 1603: 
 1604:   function checkEntities(strx) {
 1605:     if (strx.length == 0) return strx;
 1606:     var orgStr = ["&", "<", ">", '"']; 
 1607:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1608:     var counter = 0;
 1609:     while (counter < 4) {
 1610: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1611: 	counter++;
 1612:     }
 1613:     return strx;
 1614:   }
 1615: 
 1616:   function strReplace(strx, orgStr, newStr) {
 1617:     return strx.split(orgStr).join(newStr);
 1618:   }
 1619: 
 1620:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1621:     var height = 70*Nmsg+250;
 1622:     if (height > 600) {
 1623: 	height = 600;
 1624:     }
 1625:     var xpos = (screen.width-600)/2;
 1626:     xpos = (xpos < 0) ? '0' : xpos;
 1627:     var ypos = (screen.height-height)/2-30;
 1628:     ypos = (ypos < 0) ? '0' : ypos;
 1629: 
 1630:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1631:     pWin.focus();
 1632:     pDoc = pWin.document;
 1633:     pDoc.$docopen;
 1634:     pDoc.write('$start_page_msg_central');
 1635: 
 1636:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1637:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1638:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1639: 
 1640:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1641:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1642:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1643: }
 1644:     function displaySubject(msg,shwsel) {
 1645:     pDoc = pWin.document;
 1646:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1647:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1648:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1649:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1650: }
 1651: 
 1652:   function displaySavedMsg(ctr,msg,shwsel) {
 1653:     pDoc = pWin.document;
 1654:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1655:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1656:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1657:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1658: }
 1659: 
 1660:   function newMsg(newmsg,shwsel) {
 1661:     pDoc = pWin.document;
 1662:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1663:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1664:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1665:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1666: }
 1667: 
 1668:   function msgTail() {
 1669:     pDoc = pWin.document;
 1670:     pDoc.write("<\\/table>");
 1671:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1672:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1673:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1674:     pDoc.write("<\\/form>");
 1675:     pDoc.write('$end_page_msg_central');
 1676:     pDoc.close();
 1677: }
 1678: 
 1679: //====================== Script for keyword highlight options ==============
 1680:   function kwhighlight() {
 1681:     var kwclr    = document.SCORE.kwclr.value;
 1682:     var kwsize   = document.SCORE.kwsize.value;
 1683:     var kwstyle  = document.SCORE.kwstyle.value;
 1684:     var redsel = "";
 1685:     var grnsel = "";
 1686:     var blusel = "";
 1687:     if (kwclr=="red")   {var redsel="checked"};
 1688:     if (kwclr=="green") {var grnsel="checked"};
 1689:     if (kwclr=="blue")  {var blusel="checked"};
 1690:     var sznsel = "";
 1691:     var sz1sel = "";
 1692:     var sz2sel = "";
 1693:     if (kwsize=="0")  {var sznsel="checked"};
 1694:     if (kwsize=="+1") {var sz1sel="checked"};
 1695:     if (kwsize=="+2") {var sz2sel="checked"};
 1696:     var synsel = "";
 1697:     var syisel = "";
 1698:     var sybsel = "";
 1699:     if (kwstyle=="")    {var synsel="checked"};
 1700:     if (kwstyle=="<i>") {var syisel="checked"};
 1701:     if (kwstyle=="<b>") {var sybsel="checked"};
 1702:     highlightCentral();
 1703:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1704:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1705:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1706:     highlightend();
 1707:     return;
 1708:   }
 1709: 
 1710:   function highlightCentral() {
 1711: //    if (window.hwdWin) window.hwdWin.close();
 1712:     var xpos = (screen.width-400)/2;
 1713:     xpos = (xpos < 0) ? '0' : xpos;
 1714:     var ypos = (screen.height-330)/2-30;
 1715:     ypos = (ypos < 0) ? '0' : ypos;
 1716: 
 1717:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1718:     hwdWin.focus();
 1719:     var hDoc = hwdWin.document;
 1720:     hDoc.$docopen;
 1721:     hDoc.write('$start_page_highlight_central');
 1722:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1723:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1724: 
 1725:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1726:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1727:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
 1728:   }
 1729: 
 1730:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1731:     var hDoc = hwdWin.document;
 1732:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1733:     hDoc.write("<td align=\\"left\\">");
 1734:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1735:     hDoc.write("<td align=\\"left\\">");
 1736:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1737:     hDoc.write("<td align=\\"left\\">");
 1738:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1739:     hDoc.write("<\\/tr>");
 1740:   }
 1741: 
 1742:   function highlightend() { 
 1743:     var hDoc = hwdWin.document;
 1744:     hDoc.write("<\\/table>");
 1745:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1746:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1747:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1748:     hDoc.write("<\\/form>");
 1749:     hDoc.write('$end_page_highlight_central');
 1750:     hDoc.close();
 1751:   }
 1752: 
 1753: </script>
 1754: SUBJAVASCRIPT
 1755: }
 1756: 
 1757: sub get_increment {
 1758:     my $increment = $env{'form.increment'};
 1759:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1760:         $increment != .1) {
 1761:         $increment = 1;
 1762:     }
 1763:     return $increment;
 1764: }
 1765: 
 1766: sub gradeBox_start {
 1767:     return (
 1768:         &Apache::loncommon::start_data_table()
 1769:        .&Apache::loncommon::start_data_table_header_row()
 1770:        .'<th>'.&mt('Part').'</th>'
 1771:        .'<th>'.&mt('Points').'</th>'
 1772:        .'<th>&nbsp;</th>'
 1773:        .'<th>'.&mt('Assign Grade').'</th>'
 1774:        .'<th>'.&mt('Weight').'</th>'
 1775:        .'<th>'.&mt('Grade Status').'</th>'
 1776:        .&Apache::loncommon::end_data_table_header_row()
 1777:     );
 1778: }
 1779: 
 1780: sub gradeBox_end {
 1781:     return (
 1782:         &Apache::loncommon::end_data_table()
 1783:     );
 1784: }
 1785: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1786: sub gradeBox {
 1787:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1788:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1789: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1790:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1791:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1792:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1793:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1794:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1795: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1796:     my $result='<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:     $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>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1842:     $result.=&Apache::loncommon::end_data_table_row();
 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:     if ($res_error) {
 1854:         return &navmap_errormsg();
 1855:     }
 1856:     return $result;
 1857: }
 1858: 
 1859: sub handback_box {
 1860:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1861:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1862:     my (@respids);
 1863:     my @part_response_id = &flatten_responseType($responseType);
 1864:     foreach my $part_response_id (@part_response_id) {
 1865:     	my ($part,$resp) = @{ $part_response_id };
 1866:         if ($part eq $partid) {
 1867:             push(@respids,$resp);
 1868:         }
 1869:     }
 1870:     my $result;
 1871:     foreach my $respid (@respids) {
 1872: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1873: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1874: 	next if (!@$files);
 1875: 	my $file_counter = 0;
 1876: 	foreach my $file (@$files) {
 1877: 	    if ($file =~ /\/portfolio\//) {
 1878:                 $file_counter++;
 1879:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1880:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1881:     	        $file_disp = "$name.$ext";
 1882:     	        $file = $file_path.$file_disp;
 1883:     	        $result.=&mt('Return commented version of [_1] to student.',
 1884:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1885:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1886:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1887: 	    }
 1888: 	}
 1889:         if ($file_counter) {
 1890:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1891:                        '<span class="LC_info">'.
 1892:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1893:         }
 1894:     }
 1895:     return $result;    
 1896: }
 1897: 
 1898: sub show_problem {
 1899:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1900:     my $rendered;
 1901:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1902:     &Apache::lonxml::remember_problem_counter();
 1903:     if ($mode eq 'both' or $mode eq 'text') {
 1904: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1905: 						       $env{'request.course.id'},
 1906: 						       undef,\%form);
 1907:     }
 1908:     if ($removeform) {
 1909: 	$rendered=~s|<form(.*?)>||g;
 1910: 	$rendered=~s|</form>||g;
 1911: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1912:     }
 1913:     my $companswer;
 1914:     if ($mode eq 'both' or $mode eq 'answer') {
 1915: 	&Apache::lonxml::restore_problem_counter();
 1916: 	$companswer=
 1917: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1918: 						    $env{'request.course.id'},
 1919: 						    %form);
 1920:     }
 1921:     if ($removeform) {
 1922: 	$companswer=~s|<form(.*?)>||g;
 1923: 	$companswer=~s|</form>||g;
 1924: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1925:     }
 1926:     my $renderheading = &mt('View of the problem');
 1927:     my $answerheading = &mt('Correct answer');
 1928:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1929:         my $stu_fullname = $env{'form.fullname'};
 1930:         if ($stu_fullname eq '') {
 1931:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1932:         }
 1933:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1934:         if ($forwhom ne '') {
 1935:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1936:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1937:         }
 1938:     }
 1939:     $rendered=
 1940:         '<div class="LC_Box">'
 1941:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1942:        .$rendered
 1943:        .'</div>';
 1944:     $companswer=
 1945:         '<div class="LC_Box">'
 1946:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1947:        .$companswer
 1948:        .'</div>';
 1949:     my $result;
 1950:     if ($mode eq 'both') {
 1951:         $result=$rendered.$companswer;
 1952:     } elsif ($mode eq 'text') {
 1953:         $result=$rendered;
 1954:     } elsif ($mode eq 'answer') {
 1955:         $result=$companswer;
 1956:     }
 1957:     return $result;
 1958: }
 1959: 
 1960: sub files_exist {
 1961:     my ($r, $symb) = @_;
 1962:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1963: 
 1964:     foreach my $student (@students) {
 1965:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1966:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1967: 					      $udom,$uname);
 1968:         my ($string,$timestamp)= &get_last_submission(\%record);
 1969:         foreach my $submission (@$string) {
 1970:             my ($partid,$respid) =
 1971: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1972:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1973: 					   \%record);
 1974:             return 1 if (@$files);
 1975:         }
 1976:     }
 1977:     return 0;
 1978: }
 1979: 
 1980: sub download_all_link {
 1981:     my ($r,$symb) = @_;
 1982:     my $all_students = 
 1983: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1984: 
 1985:     my $parts =
 1986: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1987: 
 1988:     my $identifier = &Apache::loncommon::get_cgi_id();
 1989:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1990:                              'cgi.'.$identifier.'.symb' => $symb,
 1991:                              'cgi.'.$identifier.'.parts' => $parts,});
 1992:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1993: 	      &mt('Download All Submitted Documents').'</a>');
 1994:     return
 1995: }
 1996: 
 1997: sub build_section_inputs {
 1998:     my $section_inputs;
 1999:     if ($env{'form.section'} eq '') {
 2000:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2001:     } else {
 2002:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2003:         foreach my $section (@sections) {
 2004:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2005:         }
 2006:     }
 2007:     return $section_inputs;
 2008: }
 2009: 
 2010: # --------------------------- show submissions of a student, option to grade 
 2011: sub submission {
 2012:     my ($request,$counter,$total) = @_;
 2013:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2014:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2015:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2016:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2017:     my ($symb) = &get_symb($request); 
 2018:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2019: 
 2020:     if (!&canview($usec)) {
 2021: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 2022: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 2023: 			$env{'request.course.id'}.')</span>');
 2024: 	$request->print(&show_grading_menu_form($symb));
 2025: 	return;
 2026:     }
 2027: 
 2028:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2029:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2030:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2031:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2032:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2033: 	'" src="'.$request->dir_config('lonIconsURL').
 2034: 	'/check.gif" height="16" border="0" />';
 2035: 
 2036:     # header info
 2037:     if ($counter == 0) {
 2038: 	&sub_page_js($request);
 2039: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2040: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2041: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2042: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2043: 	    &download_all_link($request, $symb);
 2044: 	}
 2045: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2046: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 2047: 
 2048: 	# option to display problem, only once else it cause problems 
 2049:         # with the form later since the problem has a form.
 2050: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2051: 	    my $mode;
 2052: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2053: 		$mode='both';
 2054: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2055: 		$mode='text';
 2056: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2057: 		$mode='answer';
 2058: 	    }
 2059: 	    &Apache::lonxml::clear_problem_counter();
 2060: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2061: 	}
 2062: 
 2063: 	# kwclr is the only variable that is guaranteed to be non blank 
 2064:         # if this subroutine has been called once.
 2065: 	my %keyhash = ();
 2066: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2067: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2068: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2069: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2070: 
 2071: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2072: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2073: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2074: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2075: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2076: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2077: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2078: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2079: 	}
 2080: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2081: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2082: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2083: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2084: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2085: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2086: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2087: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2088: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2089: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2090: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2091: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2092: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2093: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2094: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2095: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2096: 			&build_section_inputs().
 2097: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2098: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2099: 			'<input type="hidden" name="NCT"'.
 2100: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2101: 	if ($env{'form.handgrade'} eq 'yes') {
 2102: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2103: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2104: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2105: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2106: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2107: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2108: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2109: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2110: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2111: 	    }
 2112: 	}
 2113: 	
 2114: 	my ($cts,$prnmsg) = (1,'');
 2115: 	while ($cts <= $env{'form.savemsgN'}) {
 2116: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2117: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2118: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2119: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2120: 		'" />'."\n".
 2121: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2122: 	    $cts++;
 2123: 	}
 2124: 	$request->print($prnmsg);
 2125: 
 2126: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2127: 
 2128:             my %lt = &Apache::lonlocal::texthash(
 2129:                           keyw => 'Keyword Options',
 2130:                           list => 'List',
 2131:                           past => 'Paste Selection to List',
 2132:                           high => 'Highlight Attribute',
 2133:                      );
 2134: #
 2135: # Print out the keyword options line
 2136: #
 2137: 	    $request->print(<<KEYWORDS);
 2138: &nbsp;<b>$lt{'keyw'}:</b>&nbsp;
 2139: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2140: <a href="#" onmousedown="javascript:getSel(); return false"
 2141:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
 2142: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2143: KEYWORDS
 2144: #
 2145: # Load the other essays for similarity check
 2146: #
 2147:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2148: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2149: 	    $apath=&escape($apath);
 2150: 	    $apath=~s/\W/\_/gs;
 2151:             &init_old_essays($symb,$apath,$adom,$aname);
 2152:         }
 2153:     }
 2154: 
 2155: # This is where output for one specific student would start
 2156:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2157:     $request->print(
 2158:         "\n\n"
 2159:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2160:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2161:        ."\n"
 2162:     );
 2163: 
 2164:     # Show additional functions if allowed
 2165:     if ($perm{'vgr'}) {
 2166:         $request->print(
 2167:             &Apache::loncommon::track_student_link(
 2168:                 &mt('View recent activity'),
 2169:                 $uname,$udom,'check')
 2170:            .' '
 2171:         );
 2172:     }
 2173:     if ($perm{'opa'}) {
 2174:         $request->print(
 2175:             &Apache::loncommon::pprmlink(
 2176:                 &mt('Set/Change parameters'),
 2177:                 $uname,$udom,$symb,'check'));
 2178:     }
 2179: 
 2180:     # Show Problem
 2181:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2182: 	my $mode;
 2183: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2184: 	    $mode='both';
 2185: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2186: 	    $mode='text';
 2187: 	} elsif ($env{'form.vAns'} eq 'all') {
 2188: 	    $mode='answer';
 2189: 	}
 2190: 	&Apache::lonxml::clear_problem_counter();
 2191: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2192:     }
 2193: 
 2194:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2195:     my $res_error;
 2196:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2197:     if ($res_error) {
 2198:         $request->print(&navmap_errormsg());
 2199:         return;
 2200:     }
 2201: 
 2202:     # Display student info
 2203:     $request->print(($counter == 0 ? '' : '<br />'));
 2204: 
 2205:     my $result='<div class="LC_Box">'
 2206:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2207:     $result.='<input type="hidden" name="name'.$counter.
 2208:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2209:     if ($env{'form.handgrade'} eq 'no') {
 2210:         $result.='<p class="LC_info">'
 2211:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2212:                 ."</p>\n";
 2213:     }
 2214: 
 2215:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2216:     my $fullname;
 2217:     my $col_fullnames = [];
 2218:     if ($env{'form.handgrade'} eq 'yes') {
 2219: 	(my $sub_result,$fullname,$col_fullnames)=
 2220: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2221: 				 $counter);
 2222: 	$result.=$sub_result;
 2223:     }
 2224:     $request->print($result."\n");
 2225: 
 2226:     # print student answer/submission
 2227:     # Options are (1) Handgraded submission only
 2228:     #             (2) Last submission, includes submission that is not handgraded 
 2229:     #                  (for multi-response type part)
 2230:     #             (3) Last submission plus the parts info
 2231:     #             (4) The whole record for this student
 2232:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2233: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2234: 	
 2235: 	my $lastsubonly;
 2236: 
 2237:         if ($$timestamp eq '') {
 2238:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2239:         } else {
 2240:             $lastsubonly =
 2241:                 '<div class="LC_grade_submissions_body">'
 2242:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2243: 
 2244: 	    my %seenparts;
 2245: 	    my @part_response_id = &flatten_responseType($responseType);
 2246: 	    foreach my $part (@part_response_id) {
 2247: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2248: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2249: 
 2250: 		my ($partid,$respid) = @{ $part };
 2251: 		my $display_part=&get_display_part($partid,$symb);
 2252: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2253: 		    if (exists($seenparts{$partid})) { next; }
 2254: 		    $seenparts{$partid}=1;
 2255: 		    my $submitby='<b>Part:</b> '.$display_part.
 2256: 			' <b>Collaborative submission by:</b> '.
 2257: 			'<a href="javascript:viewSubmitter(\''.
 2258: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2259: 			'\');" target="_self">'.
 2260: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2261: 		    $request->print($submitby);
 2262: 		    next;
 2263: 		}
 2264: 		my $responsetype = $responseType->{$partid}->{$respid};
 2265: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2266:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2267:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2268:                         ' <span class="LC_internal_info">'.
 2269:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2270:                         '</span>&nbsp; &nbsp;'.
 2271: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2272: 		    next;
 2273: 		}
 2274: 		foreach my $submission (@$string) {
 2275: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2276: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2277: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2278: 		    # Similarity check
 2279: 		    my $similar='';
 2280:                     my ($type,$trial,$rndseed);
 2281:                     if ($hide eq 'rand') {
 2282:                         $type = 'randomizetry';
 2283:                         $trial = $record{"resource.$partid.tries"};
 2284:                         $rndseed = $record{"resource.$partid.rndseed"};
 2285:                     }
 2286: 		    if($env{'form.checkPlag'}){
 2287: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2288: 			    &most_similar($uname,$udom,$symb,$subval);
 2289: 			if ($osim) {
 2290: 			    $osim=int($osim*100.0);
 2291: 			    my %old_course_desc = 
 2292: 				&Apache::lonnet::coursedescription($ocrsid,
 2293: 								   {'one_time' => 1});
 2294: 
 2295:                             if ($hide eq 'anon') {
 2296:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2297:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2298:                             } else {
 2299: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2300: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2301: 				        $osim,
 2302: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2303: 				        $old_course_desc{'description'},
 2304: 				        $old_course_desc{'num'},
 2305: 				        $old_course_desc{'domain'}).
 2306: 				    '</span></h3><blockquote><i>'.
 2307: 				    &keywords_highlight($oessay).
 2308: 				    '</i></blockquote><hr />';
 2309:                             }
 2310: 			}
 2311: 		    }
 2312: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2313:                                          undef,$type,$trial,$rndseed);
 2314: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2315: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2316: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2317: 			my $display_part=&get_display_part($partid,$symb);
 2318:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2319:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2320:                             ' <span class="LC_internal_info">'.
 2321:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2322:                             '</span>&nbsp; &nbsp;';
 2323: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2324: 			if (@$files) {
 2325:                             if ($hide eq 'anon') {
 2326:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2327:                             } else {
 2328:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2329:                                 foreach my $file (@$files) {
 2330:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2331:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2332:                                 }
 2333:                             }
 2334: 			    $lastsubonly.='<br />';
 2335: 			}
 2336:                         if ($hide eq 'anon') {
 2337:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2338:                         } else {
 2339: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2340: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2341: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2342:                         }
 2343: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2344: 			$lastsubonly.='</div>';
 2345: 		    }
 2346: 		}
 2347: 	    }
 2348: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2349: 	}
 2350: 	$request->print($lastsubonly);
 2351:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2352: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2353: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2354:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2355: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2356: 								 $env{'request.course.id'},
 2357: 								 $last,'.submission',
 2358: 								 'Apache::grades::keywords_highlight'));
 2359:     }
 2360: 
 2361:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2362: 	.$udom.'" />'."\n");
 2363:     # return if view submission with no grading option
 2364:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2365: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2366: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2367: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2368: 	$toGrade.='</div>'."\n";
 2369: 	if (($env{'form.command'} eq 'submission') || 
 2370: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2371: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2372: 	}
 2373: 	$request->print($toGrade);
 2374: 	return;
 2375:     } else {
 2376: 	$request->print('</div>'."\n");
 2377:     }
 2378: 
 2379:     # essay grading message center
 2380:     if ($env{'form.handgrade'} eq 'yes') {
 2381: 	my $result='<div class="LC_grade_message_center">';
 2382:     
 2383: 	$result.='<div class="LC_grade_message_center_header">'.
 2384: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2385: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2386: 	my $msgfor = $givenn.' '.$lastname;
 2387: 	if (scalar(@$col_fullnames) > 0) {
 2388: 	    my $lastone = pop(@$col_fullnames);
 2389: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2390: 	}
 2391: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2392: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2393: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2394: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2395: 	    ',\''.$msgfor.'\');" target="_self">'.
 2396: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2397: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2398: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2399: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2400: 	    '<br />&nbsp;('.
 2401: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2402: 	$result.='</div></div>';
 2403: 	$request->print($result);
 2404:     }
 2405: 
 2406:     my %seen = ();
 2407:     my @partlist;
 2408:     my @gradePartRespid;
 2409:     my @part_response_id = &flatten_responseType($responseType);
 2410:     $request->print(
 2411:         '<div class="LC_Box">'
 2412:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2413:     );
 2414:     $request->print(&gradeBox_start());
 2415:     foreach my $part_response_id (@part_response_id) {
 2416:     	my ($partid,$respid) = @{ $part_response_id };
 2417: 	my $part_resp = join('_',@{ $part_response_id });
 2418: 	next if ($seen{$partid} > 0);
 2419: 	$seen{$partid}++;
 2420: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2421: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2422: 	push(@partlist,$partid);
 2423: 	push(@gradePartRespid,$partid.'.'.$respid);
 2424: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2425:     }
 2426:     $request->print(&gradeBox_end()); # </div>
 2427:     $request->print('</div>');
 2428: 
 2429:     $request->print('<div class="LC_grade_info_links">');
 2430:     $request->print('</div>');
 2431: 
 2432:     $result='<input type="hidden" name="partlist'.$counter.
 2433: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2434:     $result.='<input type="hidden" name="gradePartRespid'.
 2435: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2436:     my $ctr = 0;
 2437:     while ($ctr < scalar(@partlist)) {
 2438: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2439: 	    $partlist[$ctr].'" />'."\n";
 2440: 	$ctr++;
 2441:     }
 2442:     $request->print($result.''."\n");
 2443: 
 2444: # Done with printing info for one student
 2445: 
 2446:     $request->print('</div>');#LC_grade_show_user
 2447: 
 2448: 
 2449:     # print end of form
 2450:     if ($counter == $total) {
 2451:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2452: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2453: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2454: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2455: 	my $ntstu ='<select name="NTSTU">'.
 2456: 	    '<option>1</option><option>2</option>'.
 2457: 	    '<option>3</option><option>5</option>'.
 2458: 	    '<option>7</option><option>10</option></select>'."\n";
 2459: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2460: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2461:         $endform.=&mt('[_1]student(s)',$ntstu);
 2462: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2463: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2464: 	    '<input type="button" value="'.&mt('Next').'" '.
 2465: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2466:         $endform.='<span class="LC_warning">'.
 2467:                   &mt('(Next and Previous (student) do not save the scores.)').
 2468:                   '</span>'."\n" ;
 2469:         $endform.="<input type='hidden' value='".&get_increment().
 2470:             "' name='increment' />";
 2471: 	$endform.='</td></tr></table></form>';
 2472: 	$endform.=&show_grading_menu_form($symb);
 2473: 	$request->print($endform);
 2474:     }
 2475:     return '';
 2476: }
 2477: 
 2478: sub check_collaborators {
 2479:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2480:     my ($result,@col_fullnames);
 2481:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2482:     foreach my $part (keys(%$handgrade)) {
 2483: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2484: 					'.maxcollaborators',
 2485: 					$symb,$udom,$uname);
 2486: 	next if ($ncol <= 0);
 2487: 	$part =~ s/\_/\./g;
 2488: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2489: 	my (@good_collaborators, @bad_collaborators);
 2490: 	foreach my $possible_collaborator
 2491: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2492: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2493: 	    next if ($possible_collaborator eq '');
 2494: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2495: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2496: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2497: 	    # Doing this grep allows 'fuzzy' specification
 2498: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2499: 			       keys(%$classlist));
 2500: 	    if (! scalar(@matches)) {
 2501: 		push(@bad_collaborators, $possible_collaborator);
 2502: 	    } else {
 2503: 		push(@good_collaborators, @matches);
 2504: 	    }
 2505: 	}
 2506: 	if (scalar(@good_collaborators) != 0) {
 2507: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2508: 	    foreach my $name (@good_collaborators) {
 2509: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2510: 		push(@col_fullnames, $givenn.' '.$lastname);
 2511: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2512: 	    }
 2513: 	    $result.='</ol><br />'."\n";
 2514: 	    my ($part)=split(/\./,$part);
 2515: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2516: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2517: 		"\n";
 2518: 	}
 2519: 	if (scalar(@bad_collaborators) > 0) {
 2520: 	    $result.='<div class="LC_warning">';
 2521: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2522: 	    $result .= '</div>';
 2523: 	}         
 2524: 	if (scalar(@bad_collaborators > $ncol)) {
 2525: 	    $result .= '<div class="LC_warning">';
 2526: 	    $result .= &mt('This student has submitted too many '.
 2527: 		'collaborators.  Maximum is [_1].',$ncol);
 2528: 	    $result .= '</div>';
 2529: 	}
 2530:     }
 2531:     return ($result,$fullname,\@col_fullnames);
 2532: }
 2533: 
 2534: #--- Retrieve the last submission for all the parts
 2535: sub get_last_submission {
 2536:     my ($returnhash)=@_;
 2537:     my (@string,$timestamp,%lasthidden);
 2538:     if ($$returnhash{'version'}) {
 2539: 	my %lasthash=();
 2540: 	my ($version);
 2541: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2542: 	    foreach my $key (sort(split(/\:/,
 2543: 					$$returnhash{$version.':keys'}))) {
 2544: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2545: 		$timestamp = 
 2546: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2547: 	    }
 2548: 	}
 2549:         my (%typeparts,%randombytry);
 2550:         my $showsurv = 
 2551:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2552:         foreach my $key (sort(keys(%lasthash))) {
 2553:             if ($key =~ /\.type$/) {
 2554:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2555:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2556:                     ($lasthash{$key} eq 'randomizetry')) {
 2557:                     my ($ign,@parts) = split(/\./,$key);
 2558:                     pop(@parts);
 2559:                     my $id = join('.',@parts);
 2560:                     if ($lasthash{$key} eq 'randomizetry') {
 2561:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2562:                     } else {
 2563:                         unless ($showsurv) {
 2564:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2565:                         }
 2566:                     }
 2567:                     delete($lasthash{$key});
 2568:                 }
 2569:             }
 2570:         }
 2571:         my @hidden = keys(%typeparts);
 2572:         my @randomize = keys(%randombytry);
 2573: 	foreach my $key (keys(%lasthash)) {
 2574: 	    next if ($key !~ /\.submission$/);
 2575:             my $hide;
 2576:             if (@hidden) {
 2577:                 foreach my $id (@hidden) {
 2578:                     if ($key =~ /^\Q$id\E/) {
 2579:                         $hide = 'anon';
 2580:                         last;
 2581:                     }
 2582:                 }
 2583:             }
 2584:             unless ($hide) {
 2585:                 if (@randomize) {
 2586:                     foreach my $id (@hidden) {
 2587:                         if ($key =~ /^\Q$id\E/) {
 2588:                             $hide = 'rand';
 2589:                             last;
 2590:                         }
 2591:                     }
 2592:                 }
 2593:             }
 2594: 	    my ($partid,$foo) = split(/submission$/,$key);
 2595: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2596: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2597: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2598: 	}
 2599:     }
 2600:     if (!@string) {
 2601: 	$string[0] =
 2602: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2603:     }
 2604:     return (\@string,\$timestamp);
 2605: }
 2606: 
 2607: #--- High light keywords, with style choosen by user.
 2608: sub keywords_highlight {
 2609:     my $string    = shift;
 2610:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2611:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2612:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2613:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2614:     foreach my $keyword (@keylist) {
 2615: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2616:     }
 2617:     return $string;
 2618: }
 2619: 
 2620: # For Tasks provide a mechanism to display previous version for one specific student
 2621: 
 2622: sub show_previous_task_version {
 2623:     my ($request,$symb) = @_;
 2624:     if ($symb eq '') {
 2625:         $request->print("Unable to handle ambiguous references.");
 2626: 
 2627:         return '';
 2628:     }
 2629:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2630:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2631:     if (!&canview($usec)) {
 2632:         $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
 2633:                         $uname.':'.$udom.' in section '.$usec.' in course id '.
 2634:                         $env{'request.course.id'}.')</span>');
 2635:         return;
 2636:     }
 2637:     my $mode = 'both';
 2638:     my $isTask = ($symb =~/\.task$/);
 2639:     if ($isTask) {
 2640:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2641:             if ($env{'form.fullname'} eq '') {
 2642:                 $env{'form.fullname'} =
 2643:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2644:             }
 2645:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2646:             $request->print("\n\n".
 2647:                             '<div class="LC_grade_show_user">'.
 2648:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2649:                             '</h2>'."\n");
 2650:             &Apache::lonxml::clear_problem_counter();
 2651:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2652:                             {'previousversion' => $env{'form.previousversion'} }));
 2653:             $request->print("\n</div>");
 2654:         }
 2655:     }
 2656:     return;
 2657: }
 2658: 
 2659: sub choose_task_version_form {
 2660:     my ($symb,$uname,$udom,$nomenu) = @_;
 2661:     my $isTask = ($symb =~/\.task$/);
 2662:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2663:     if ($isTask) {
 2664:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2665:                                               $udom,$uname);
 2666:         if (($record{'resource.0.version'} eq '') ||
 2667:             ($record{'resource.0.version'} < 2)) {
 2668:             return ($record{'resource.0.version'},
 2669:                     $record{'resource.0.version'},$result,$js);
 2670:         } else {
 2671:             $current = $record{'resource.0.version'};
 2672:         }
 2673:         if ($env{'form.previousversion'}) {
 2674:             $displayed = $env{'form.previousversion'};
 2675:             $rowtitle = &mt('Choose another version:')
 2676:         } else {
 2677:             $displayed = $current;
 2678:             $rowtitle = &mt('Show earlier version:');
 2679:         }
 2680:         $result = '<div class="LC_left_float">';
 2681:         my $list;
 2682:         my $numversions = 0;
 2683:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2684:             if ($i == $current) {
 2685:                 if (!$env{'form.previousversion'} || $nomenu) {
 2686:                     next;
 2687:                 } else {
 2688:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2689:                     $numversions ++;
 2690:                 }
 2691:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2692:                 unless ($i == $env{'form.previousversion'}) {
 2693:                     $numversions ++;
 2694:                 }
 2695:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2696:             }
 2697:         }
 2698:         if ($numversions) {
 2699:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2700:             $result .=
 2701:                 '<form name="getprev" method="post" action=""'.
 2702:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2703:                 &Apache::loncommon::start_data_table().
 2704:                 &Apache::loncommon::start_data_table_row().
 2705:                 '<th align="left">'.$rowtitle.'</th>'.
 2706:                 '<td><select name="version">'.
 2707:                 '<option>'.&mt('Select').'</option>'.
 2708:                 $list.
 2709:                 '</select></td>'.
 2710:                 &Apache::loncommon::end_data_table_row();
 2711:             unless ($nomenu) {
 2712:                 $result .= &Apache::loncommon::start_data_table_row().
 2713:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2714:                 '<td><span class="LC_nobreak">'.
 2715:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2716:                 &mt('Yes').'</label>'.
 2717:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2718:                 '</span></td>'.
 2719:                 &Apache::loncommon::end_data_table_row();
 2720:             }
 2721:             $result .=
 2722:                 &Apache::loncommon::start_data_table_row().
 2723:                 '<th align="left">&nbsp;</th>'.
 2724:                 '<td>'.
 2725:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2726:                 '</td>'.
 2727:                 &Apache::loncommon::end_data_table_row().
 2728:                 &Apache::loncommon::end_data_table().
 2729:                 '</form>';
 2730:             $js = &previous_display_javascript($nomenu,$current);
 2731:         } elsif ($displayed && $nomenu) {
 2732:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2733:         } else {
 2734:             $result .= &mt('No previous versions to show for this student');
 2735:         }
 2736:         $result .= '</div>';
 2737:     }
 2738:     return ($current,$displayed,$result,$js);
 2739: }
 2740: 
 2741: sub previous_display_javascript {
 2742:     my ($nomenu,$current) = @_;
 2743:     my $js = <<"JSONE";
 2744: <script type="text/javascript">
 2745: // <![CDATA[
 2746: function previousVersion(uname,udom,symb) {
 2747:     var current = '$current';
 2748:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2749:     var prevstr = new RegExp("^\\\\d+\$");
 2750:     if (!prevstr.test(version)) {
 2751:         return false;
 2752:     }
 2753:     var url = '';
 2754:     if (version == current) {
 2755:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2756:     } else {
 2757:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2758:     }
 2759: JSONE
 2760:     if ($nomenu) {
 2761:         $js .= <<"JSTWO";
 2762:     document.location.href = url;
 2763: JSTWO
 2764:     } else {
 2765:         $js .= <<"JSTHREE";
 2766:     var newwin = 0;
 2767:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2768:         if (document.getprev.prevwin[i].checked == true) {
 2769:             newwin = document.getprev.prevwin[i].value;
 2770:         }
 2771:     }
 2772:     if (newwin == 1) {
 2773:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2774:         url = url+'&inhibitmenu=yes';
 2775:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2776:             previousWin = window.open(url,'',options,1);
 2777:         } else {
 2778:             previousWin.location.href = url;
 2779:         }
 2780:         previousWin.focus();
 2781:         return false;
 2782:     } else {
 2783:         document.location.href = url;
 2784:         return false;
 2785:     }
 2786: JSTHREE
 2787:     }
 2788:     $js .= <<"ENDJS";
 2789:     return false;
 2790: }
 2791: // ]]>
 2792: </script>
 2793: ENDJS
 2794: 
 2795: }
 2796: 
 2797: #--- Called from submission routine
 2798: sub processHandGrade {
 2799:     my ($request) = shift;
 2800:     my ($symb)   = &get_symb($request);
 2801:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2802:     my $button = $env{'form.gradeOpt'};
 2803:     my $ngrade = $env{'form.NCT'};
 2804:     my $ntstu  = $env{'form.NTSTU'};
 2805:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2806:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2807: 
 2808:     if ($button eq 'Save & Next') {
 2809: 	my $ctr = 0;
 2810: 	while ($ctr < $ngrade) {
 2811: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2812: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2813: 	    if ($errorflag eq 'no_score') {
 2814: 		$ctr++;
 2815: 		next;
 2816: 	    }
 2817: 	    if ($errorflag eq 'not_allowed') {
 2818: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2819: 		$ctr++;
 2820: 		next;
 2821: 	    }
 2822: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2823: 	    my ($subject,$message,$msgstatus) = ('','','');
 2824: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2825:             my ($feedurl,$showsymb) =
 2826: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2827: 	    my $messagetail;
 2828: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2829: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2830: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2831: 		$subject.=' ['.$restitle.']';
 2832: 		my (@msgnum) = split(/,/,$includemsg);
 2833: 		foreach (@msgnum) {
 2834: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2835: 		}
 2836: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2837: 		if ($env{'form.withgrades'.$ctr}) {
 2838: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2839: 		    $messagetail = " for <a href=\"".
 2840: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2841: 		}
 2842: 		$msgstatus = 
 2843:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2844: 						     $message.$messagetail,
 2845:                                                      undef,$feedurl,undef,
 2846:                                                      undef,undef,$showsymb,
 2847:                                                      $restitle);
 2848: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2849: 				$msgstatus.'<br />');
 2850: 	    }
 2851: 	    if ($env{'form.collaborator'.$ctr}) {
 2852: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2853: 		foreach my $collabstr (@collabstrs) {
 2854: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2855: 		    foreach my $collaborator (@collaborators) {
 2856: 			my ($errorflag,$pts,$wgt) = 
 2857: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2858: 					   $env{'form.unamedom'.$ctr},$part);
 2859: 			if ($errorflag eq 'not_allowed') {
 2860: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2861: 			    next;
 2862: 			} elsif ($message ne '') {
 2863: 			    my ($baseurl,$showsymb) = 
 2864: 				&get_feedurl_and_symb($symb,$collaborator,
 2865: 						      $udom);
 2866: 			    if ($env{'form.withgrades'.$ctr}) {
 2867: 				$messagetail = " for <a href=\"".
 2868:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2869: 			    }
 2870: 			    $msgstatus = 
 2871: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2872: 			}
 2873: 		    }
 2874: 		}
 2875: 	    }
 2876: 	    $ctr++;
 2877: 	}
 2878:     }
 2879: 
 2880:     if ($env{'form.handgrade'} eq 'yes') {
 2881: 	# Keywords sorted in alphabatical order
 2882: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2883: 	my %keyhash = ();
 2884: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2885: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2886: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2887: 	$env{'form.keywords'} = join(' ',@keywords);
 2888: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2889: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2890: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2891: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2892: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2893: 
 2894: 	# message center - Order of message gets changed. Blank line is eliminated.
 2895: 	# New messages are saved in env for the next student.
 2896: 	# All messages are saved in nohist_handgrade.db
 2897: 	my ($ctr,$idx) = (1,1);
 2898: 	while ($ctr <= $env{'form.savemsgN'}) {
 2899: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2900: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2901: 		$idx++;
 2902: 	    }
 2903: 	    $ctr++;
 2904: 	}
 2905: 	$ctr = 0;
 2906: 	while ($ctr < $ngrade) {
 2907: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2908: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2909: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2910: 		$idx++;
 2911: 	    }
 2912: 	    $ctr++;
 2913: 	}
 2914: 	$env{'form.savemsgN'} = --$idx;
 2915: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2916: 	my $putresult = &Apache::lonnet::put
 2917: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2918:     }
 2919:     # Called by Save & Refresh from Highlight Attribute Window
 2920:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2921:     if ($env{'form.refresh'} eq 'on') {
 2922: 	my ($ctr,$total) = (0,0);
 2923: 	while ($ctr < $ngrade) {
 2924: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2925: 	    $ctr++;
 2926: 	}
 2927: 	$env{'form.NTSTU'}=$ngrade;
 2928: 	$ctr = 0;
 2929: 	while ($ctr < $total) {
 2930: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2931: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2932: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2933: 	    &submission($request,$ctr,$total-1);
 2934: 	    $ctr++;
 2935: 	}
 2936: 	return '';
 2937:     }
 2938: 
 2939: # Go directly to grade student - from submission or link from chart page
 2940:     if ($button eq 'Grade Student') {
 2941: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2942: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2943: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2944: 	$env{'form.fullname'} = $$fullname{$processUser};
 2945: 	&submission($request,0,0);
 2946: 	return '';
 2947:     }
 2948: 
 2949:     # Get the next/previous one or group of students
 2950:     my $firststu = $env{'form.unamedom0'};
 2951:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2952:     my $ctr = 2;
 2953:     while ($laststu eq '') {
 2954: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2955: 	$ctr++;
 2956: 	$laststu = $firststu if ($ctr > $ngrade);
 2957:     }
 2958: 
 2959:     my (@parsedlist,@nextlist);
 2960:     my ($nextflg) = 0;
 2961:     foreach my $item (sort 
 2962: 	     {
 2963: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2964: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2965: 		 }
 2966: 		 return $a cmp $b;
 2967: 	     } (keys(%$fullname))) {
 2968: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2969: 	    push(@parsedlist,$item);
 2970: 	}
 2971: 	$nextflg = 1 if ($item eq $laststu);
 2972: 	if ($button eq 'Previous') {
 2973: 	    last if ($item eq $firststu);
 2974: 	    push(@parsedlist,$item);
 2975: 	}
 2976:     }
 2977:     $ctr = 0;
 2978:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2979:     my $res_error;
 2980:     my ($partlist) = &response_type($symb,\$res_error);
 2981:     if ($res_error) {
 2982:         $request->print(&navmap_errormsg());
 2983:         return;
 2984:     }
 2985:     foreach my $student (@parsedlist) {
 2986: 	my $submitonly=$env{'form.submitonly'};
 2987: 	my ($uname,$udom) = split(/:/,$student);
 2988: 	
 2989: 	if ($submitonly eq 'queued') {
 2990: 	    my %queue_status = 
 2991: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2992: 							$udom,$uname);
 2993: 	    next if (!defined($queue_status{'gradingqueue'}));
 2994: 	}
 2995: 
 2996: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2997: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2998: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2999: 	    my $submitted = 0;
 3000: 	    my $ungraded = 0;
 3001: 	    my $incorrect = 0;
 3002: 	    foreach my $item (keys(%status)) {
 3003: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3004: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3005: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3006: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3007: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3008: 		    $submitted = 0;
 3009: 		}
 3010: 	    }
 3011: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3012: 				     $submitonly eq 'incorrect' ||
 3013: 				     $submitonly eq 'graded'));
 3014: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3015: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3016: 	}
 3017: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3018: 	last if ($ctr == $ntstu);
 3019: 	$ctr++;
 3020:     }
 3021: 
 3022:     $ctr = 0;
 3023:     my $total = scalar(@nextlist)-1;
 3024: 
 3025:     foreach (sort(@nextlist)) {
 3026: 	my ($uname,$udom,$submitter) = split(/:/);
 3027: 	$env{'form.student'}  = $uname;
 3028: 	$env{'form.userdom'}  = $udom;
 3029: 	$env{'form.fullname'} = $$fullname{$_};
 3030: 	&submission($request,$ctr,$total);
 3031: 	$ctr++;
 3032:     }
 3033:     if ($total < 0) {
 3034: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3035: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3036: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3037: 	$the_end.=&show_grading_menu_form($symb);
 3038: 	$request->print($the_end);
 3039:     }
 3040:     return '';
 3041: }
 3042: 
 3043: #---- Save the score and award for each student, if changed
 3044: sub saveHandGrade {
 3045:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3046:     my @version_parts;
 3047:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3048: 					   $env{'request.course.id'});
 3049:     if (!&canmodify($usec)) { return('not_allowed'); }
 3050:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3051:     my @parts_graded;
 3052:     my %newrecord  = ();
 3053:     my ($pts,$wgt) = ('','');
 3054:     my %aggregate = ();
 3055:     my $aggregateflag = 0;
 3056:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3057:     foreach my $new_part (@parts) {
 3058: 	#collaborator ($submi may vary for different parts
 3059: 	if ($submitter && $new_part ne $part) { next; }
 3060: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3061: 	if ($dropMenu eq 'excused') {
 3062: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3063: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3064: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3065: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3066: 		}
 3067: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3068: 	    }
 3069: 	} elsif ($dropMenu eq 'reset status'
 3070: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3071: 	    foreach my $key (keys(%record)) {
 3072: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3073: 	    }
 3074: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3075: 		"$env{'user.name'}:$env{'user.domain'}";
 3076:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3077: 
 3078:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3079: 					       [$new_part]);
 3080:             my $aggtries =$totaltries;
 3081:             if ($last_resets{$new_part}) {
 3082:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3083: 					   $new_part);
 3084:             }
 3085: 
 3086:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3087:             if ($aggtries > 0) {
 3088:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3089:                 $aggregateflag = 1;
 3090:             }
 3091: 	} elsif ($dropMenu eq '') {
 3092: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3093: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3094: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3095: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3096: 		next;
 3097: 	    }
 3098: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3099: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3100: 	    my $partial= $pts/$wgt;
 3101: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3102: 		#do not update score for part if not changed.
 3103:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3104: 		next;
 3105: 	    } else {
 3106: 	        push(@parts_graded,$new_part);
 3107: 	    }
 3108: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3109: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3110: 	    }
 3111: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3112: 	    if ($partial == 0) {
 3113: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3114: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3115: 		}
 3116: 	    } else {
 3117: 		if ($record{$reckey} ne 'correct_by_override') {
 3118: 		    $newrecord{$reckey} = 'correct_by_override';
 3119: 		}
 3120: 	    }	    
 3121: 	    if ($submitter && 
 3122: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3123: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3124: 	    }
 3125: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3126: 		"$env{'user.name'}:$env{'user.domain'}";
 3127: 	}
 3128: 	# unless problem has been graded, set flag to version the submitted files
 3129: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3130: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3131: 	        $dropMenu eq 'reset status')
 3132: 	   {
 3133: 	    push(@version_parts,$new_part);
 3134: 	}
 3135:     }
 3136:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3137:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3138: 
 3139:     if (%newrecord) {
 3140:         if (@version_parts) {
 3141:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3142:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3143: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3144: 	    foreach my $new_part (@version_parts) {
 3145: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3146: 				$new_part,\%newrecord);
 3147: 	    }
 3148:         }
 3149: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3150: 				$env{'request.course.id'},$domain,$stuname);
 3151: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3152: 				     $cdom,$cnum,$domain,$stuname);
 3153:     }
 3154:     if ($aggregateflag) {
 3155:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3156: 			      $cdom,$cnum);
 3157:     }
 3158:     return ('',$pts,$wgt);
 3159: }
 3160: 
 3161: sub check_and_remove_from_queue {
 3162:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3163:     my @ungraded_parts;
 3164:     foreach my $part (@{$parts}) {
 3165: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3166: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3167: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3168: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3169: 		) {
 3170: 	    push(@ungraded_parts, $part);
 3171: 	}
 3172:     }
 3173:     if ( !@ungraded_parts ) {
 3174: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3175: 					       $cnum,$domain,$stuname);
 3176:     }
 3177: }
 3178: 
 3179: sub handback_files {
 3180:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3181:     my $portfolio_root = '/userfiles/portfolio';
 3182:     my $res_error;
 3183:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3184:     if ($res_error) {
 3185:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3186:         return;
 3187:     }
 3188:     my @handedback;
 3189:     my $file_msg;
 3190:     my @part_response_id = &flatten_responseType($responseType);
 3191:     foreach my $part_response_id (@part_response_id) {
 3192:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3193: 	my $part_resp = join('_',@{ $part_response_id });
 3194:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3195:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3196:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3197: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3198:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3199:                     my ($directory,$answer_file) = 
 3200:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3201:                     my ($answer_name,$answer_ver,$answer_ext) =
 3202: 		        &file_name_version_ext($answer_file);
 3203: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3204:                     my $getpropath = 1;
 3205:                     my ($dir_list,$listerror) =
 3206:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3207:                                                  $domain,$stuname,$getpropath);
 3208: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3209:                     # fix file name
 3210:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3211:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3212:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3213:             	                                $save_file_name);
 3214:                     if ($result !~ m|^/uploaded/|) {
 3215:                         $request->print('<br /><span class="LC_error">'.
 3216:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3217:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3218:                                         '</span>');
 3219:                     } else {
 3220:                         # mark the file as read only
 3221:                         push(@handedback,$save_file_name);
 3222: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3223: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3224: 			}
 3225:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3226: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3227: 
 3228:                     }
 3229:                     $request->print('<br />'.&mt('[_1] will be the uploaded file name [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 3230:                 }
 3231:             }
 3232:         }
 3233:     }
 3234:     if (@handedback > 0) {
 3235:         $request->print('<br />');
 3236:         my @what = ($symb,$env{'request.course.id'},'handback');
 3237:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3238:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3239:         my ($subject,$message);
 3240:         if (scalar(@handedback) == 1) {
 3241:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3242:         } else {
 3243:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3244:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3245:         }
 3246:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3247:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3248:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3249:         my ($feedurl,$showsymb) =
 3250:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3251:         my $restitle = &Apache::lonnet::gettitle($symb);
 3252:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3253:         my $msgstatus =
 3254:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3255:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3256:                  $restitle);
 3257:         if ($msgstatus) {
 3258:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3259:         }
 3260:     }
 3261:     return;
 3262: }
 3263: 
 3264: sub get_feedurl_and_symb {
 3265:     my ($symb,$uname,$udom) = @_;
 3266:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3267:     $url = &Apache::lonnet::clutter($url);
 3268:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3269: 					$symb,$udom,$uname);
 3270:     if ($encrypturl =~ /^yes$/i) {
 3271: 	&Apache::lonenc::encrypted(\$url,1);
 3272: 	&Apache::lonenc::encrypted(\$symb,1);
 3273:     }
 3274:     return ($url,$symb);
 3275: }
 3276: 
 3277: sub get_submitted_files {
 3278:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3279:     my @files;
 3280:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3281:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3282:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3283:     	    push(@files,$file_url.$file);
 3284:         }
 3285:     }
 3286:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3287:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3288:     }
 3289:     return (\@files);
 3290: }
 3291: 
 3292: # ----------- Provides number of tries since last reset.
 3293: sub get_num_tries {
 3294:     my ($record,$last_reset,$part) = @_;
 3295:     my $timestamp = '';
 3296:     my $num_tries = 0;
 3297:     if ($$record{'version'}) {
 3298:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3299:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3300:                 $timestamp = $$record{$version.':timestamp'};
 3301:                 if ($timestamp > $last_reset) {
 3302:                     $num_tries ++;
 3303:                 } else {
 3304:                     last;
 3305:                 }
 3306:             }
 3307:         }
 3308:     }
 3309:     return $num_tries;
 3310: }
 3311: 
 3312: # ----------- Determine decrements required in aggregate totals 
 3313: sub decrement_aggs {
 3314:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3315:     my %decrement = (
 3316:                         attempts => 0,
 3317:                         users => 0,
 3318:                         correct => 0
 3319:                     );
 3320:     $decrement{'attempts'} = $aggtries;
 3321:     if ($solvedstatus =~ /^correct/) {
 3322:         $decrement{'correct'} = 1;
 3323:     }
 3324:     if ($aggtries == $totaltries) {
 3325:         $decrement{'users'} = 1;
 3326:     }
 3327:     foreach my $type (keys(%decrement)) {
 3328:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3329:     }
 3330:     return;
 3331: }
 3332: 
 3333: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3334: sub get_last_resets {
 3335:     my ($symb,$courseid,$partids) =@_;
 3336:     my %last_resets;
 3337:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3338:     my $cname = $env{'course.'.$courseid.'.num'};
 3339:     my @keys;
 3340:     foreach my $part (@{$partids}) {
 3341: 	push(@keys,"$symb\0$part\0resettime");
 3342:     }
 3343:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3344: 				     $cdom,$cname);
 3345:     foreach my $part (@{$partids}) {
 3346: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3347:     }
 3348:     return %last_resets;
 3349: }
 3350: 
 3351: # ----------- Handles creating versions for portfolio files as answers
 3352: sub version_portfiles {
 3353:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3354:     my $version_parts = join('|',@$v_flag);
 3355:     my @returned_keys;
 3356:     my $parts = join('|', @$parts_graded);
 3357:     my $portfolio_root = '/userfiles/portfolio';
 3358:     foreach my $key (keys(%$record)) {
 3359:         my $new_portfiles;
 3360:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3361:             my @versioned_portfiles;
 3362:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3363:             foreach my $file (@portfiles) {
 3364:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3365:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3366: 		my ($answer_name,$answer_ver,$answer_ext) =
 3367: 		    &file_name_version_ext($answer_file);
 3368:                 my $getpropath = 1;
 3369:                 my ($dir_list,$listerror) =
 3370:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3371:                                              $stu_name,$getpropath);
 3372:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3373:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3374:                 if ($new_answer ne 'problem getting file') {
 3375:                     push(@versioned_portfiles, $directory.$new_answer);
 3376:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3377:                         [$directory.$new_answer],
 3378:                         [$symb,$env{'request.course.id'},'graded']);
 3379:                 }
 3380:             }
 3381:             $$record{$key} = join(',',@versioned_portfiles);
 3382:             push(@returned_keys,$key);
 3383:         }
 3384:     } 
 3385:     return (@returned_keys);   
 3386: }
 3387: 
 3388: sub get_next_version {
 3389:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3390:     my $version;
 3391:     if (ref($dir_list) eq 'ARRAY') {
 3392:         foreach my $row (@{$dir_list}) {
 3393:             my ($file) = split(/\&/,$row,2);
 3394:             my ($file_name,$file_version,$file_ext) =
 3395: 	        &file_name_version_ext($file);
 3396:             if (($file_name eq $answer_name) && 
 3397: 	        ($file_ext eq $answer_ext)) {
 3398:                 # gets here if filename and extension match, 
 3399:                 # regardless of version
 3400:                 if ($file_version ne '') {
 3401:                     # a versioned file is found  so save it for later
 3402:                     if ($file_version > $version) {
 3403: 		        $version = $file_version;
 3404:                     }
 3405: 	        }
 3406:             }
 3407:         }
 3408:     }
 3409:     $version ++;
 3410:     return($version);
 3411: }
 3412: 
 3413: sub version_selected_portfile {
 3414:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3415:     my ($answer_name,$answer_ver,$answer_ext) =
 3416:         &file_name_version_ext($file_name);
 3417:     my $new_answer;
 3418:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3419:     if($env{'form.copy'} eq '-1') {
 3420:         $new_answer = 'problem getting file';
 3421:     } else {
 3422:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3423:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3424:                             $stu_name,$domain,'copy',
 3425: 		        '/portfolio'.$directory.$new_answer);
 3426:     }    
 3427:     return ($new_answer);
 3428: }
 3429: 
 3430: sub file_name_version_ext {
 3431:     my ($file)=@_;
 3432:     my @file_parts = split(/\./, $file);
 3433:     my ($name,$version,$ext);
 3434:     if (@file_parts > 1) {
 3435: 	$ext=pop(@file_parts);
 3436: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3437: 	    $version=pop(@file_parts);
 3438: 	}
 3439: 	$name=join('.',@file_parts);
 3440:     } else {
 3441: 	$name=join('.',@file_parts);
 3442:     }
 3443:     return($name,$version,$ext);
 3444: }
 3445: 
 3446: #--------------------------------------------------------------------------------------
 3447: #
 3448: #-------------------------- Next few routines handles grading by section or whole class
 3449: #
 3450: #--- Javascript to handle grading by section or whole class
 3451: sub viewgrades_js {
 3452:     my ($request) = shift;
 3453: 
 3454:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3455:     $request->print(<<VIEWJAVASCRIPT);
 3456: <script type="text/javascript" language="javascript">
 3457:    function writePoint(partid,weight,point) {
 3458: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3459: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3460: 	if (point == "textval") {
 3461: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3462: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3463: 		alert("$alertmsg"+parseFloat(point));
 3464: 		var resetbox = false;
 3465: 		for (var i=0; i<radioButton.length; i++) {
 3466: 		    if (radioButton[i].checked) {
 3467: 			textbox.value = i;
 3468: 			resetbox = true;
 3469: 		    }
 3470: 		}
 3471: 		if (!resetbox) {
 3472: 		    textbox.value = "";
 3473: 		}
 3474: 		return;
 3475: 	    }
 3476: 	    if (parseFloat(point) > parseFloat(weight)) {
 3477: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3478: 				   ") greater than the weight for the part. Accept?");
 3479: 		if (resp == false) {
 3480: 		    textbox.value = "";
 3481: 		    return;
 3482: 		}
 3483: 	    }
 3484: 	    for (var i=0; i<radioButton.length; i++) {
 3485: 		radioButton[i].checked=false;
 3486: 		if (parseFloat(point) == i) {
 3487: 		    radioButton[i].checked=true;
 3488: 		}
 3489: 	    }
 3490: 
 3491: 	} else {
 3492: 	    textbox.value = parseFloat(point);
 3493: 	}
 3494: 	for (i=0;i<document.classgrade.total.value;i++) {
 3495: 	    var user = document.classgrade["ctr"+i].value;
 3496: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3497: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3498: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3499: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3500: 	    if (saveval != "correct") {
 3501: 		scorename.value = point;
 3502: 		if (selname[0].selected != true) {
 3503: 		    selname[0].selected = true;
 3504: 		}
 3505: 	    }
 3506: 	}
 3507: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3508:     }
 3509: 
 3510:     function writeRadText(partid,weight) {
 3511: 	var selval   = document.classgrade["SELVAL_"+partid];
 3512: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3513:         var override = document.classgrade["FORCE_"+partid].checked;
 3514: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3515: 	if (selval[1].selected || selval[2].selected) {
 3516: 	    for (var i=0; i<radioButton.length; i++) {
 3517: 		radioButton[i].checked=false;
 3518: 
 3519: 	    }
 3520: 	    textbox.value = "";
 3521: 
 3522: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3523: 		var user = document.classgrade["ctr"+i].value;
 3524: 		user = user.replace(new RegExp(':', 'g'),"_");
 3525: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3526: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3527: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3528: 		if ((saveval != "correct") || override) {
 3529: 		    scorename.value = "";
 3530: 		    if (selval[1].selected) {
 3531: 			selname[1].selected = true;
 3532: 		    } else {
 3533: 			selname[2].selected = true;
 3534: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3535: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3536: 		    }
 3537: 		}
 3538: 	    }
 3539: 	} else {
 3540: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3541: 		var user = document.classgrade["ctr"+i].value;
 3542: 		user = user.replace(new RegExp(':', 'g'),"_");
 3543: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3544: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3545: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3546: 		if ((saveval != "correct") || override) {
 3547: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3548: 		    selname[0].selected = true;
 3549: 		}
 3550: 	    }
 3551: 	}	    
 3552:     }
 3553: 
 3554:     function changeSelect(partid,user) {
 3555: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3556: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3557: 	var point  = textbox.value;
 3558: 	var weight = document.classgrade["weight_"+partid].value;
 3559: 
 3560: 	if (isNaN(point) || parseFloat(point) < 0) {
 3561: 	    alert("$alertmsg"+parseFloat(point));
 3562: 	    textbox.value = "";
 3563: 	    return;
 3564: 	}
 3565: 	if (parseFloat(point) > parseFloat(weight)) {
 3566: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3567: 			       ") greater than the weight of the part. Accept?");
 3568: 	    if (resp == false) {
 3569: 		textbox.value = "";
 3570: 		return;
 3571: 	    }
 3572: 	}
 3573: 	selval[0].selected = true;
 3574:     }
 3575: 
 3576:     function changeOneScore(partid,user) {
 3577: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3578: 	if (selval[1].selected || selval[2].selected) {
 3579: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3580: 	    if (selval[2].selected) {
 3581: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3582: 	    }
 3583:         }
 3584:     }
 3585: 
 3586:     function resetEntry(numpart) {
 3587: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3588: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3589: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3590: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3591: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3592: 	    for (var i=0; i<radioButton.length; i++) {
 3593: 		radioButton[i].checked=false;
 3594: 
 3595: 	    }
 3596: 	    textbox.value = "";
 3597: 	    selval[0].selected = true;
 3598: 
 3599: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3600: 		var user = document.classgrade["ctr"+i].value;
 3601: 		user = user.replace(new RegExp(':', 'g'),"_");
 3602: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3603: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3604: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3605: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3606: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3607: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3608: 		if (saveselval == "excused") {
 3609: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3610: 		} else {
 3611: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3612: 		}
 3613: 	    }
 3614: 	}
 3615:     }
 3616: 
 3617: </script>
 3618: VIEWJAVASCRIPT
 3619: }
 3620: 
 3621: #--- show scores for a section or whole class w/ option to change/update a score
 3622: sub viewgrades {
 3623:     my ($request) = shift;
 3624:     &viewgrades_js($request);
 3625: 
 3626:     my ($symb) = &get_symb($request);
 3627:     #need to make sure we have the correct data for later EXT calls, 
 3628:     #thus invalidate the cache
 3629:     &Apache::lonnet::devalidatecourseresdata(
 3630:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3631:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3632:     &Apache::lonnet::clear_EXT_cache_status();
 3633: 
 3634:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3635:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3636: 
 3637:     #view individual student submission form - called using Javascript viewOneStudent
 3638:     $result.=&jscriptNform($symb);
 3639: 
 3640:     #beginning of class grading form
 3641:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3642:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3643: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3644: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3645: 	&build_section_inputs().
 3646: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3647: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3648: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3649: 
 3650:     my ($common_header,$specific_header);
 3651:     if ($env{'form.section'} eq 'all') {
 3652: 	$common_header = &mt('Assign Common Grade to Class');
 3653:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3654:     } elsif ($env{'form.section'} eq 'none') {
 3655:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3656: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3657:     } else {
 3658:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3659:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3660: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3661:     }
 3662:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3663:     #radio buttons/text box for assigning points for a section or class.
 3664:     #handles different parts of a problem
 3665:     my $res_error;
 3666:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3667:     if ($res_error) {
 3668:         return &navmap_errormsg();
 3669:     }
 3670:     my %weight = ();
 3671:     my $ctsparts = 0;
 3672:     my %seen = ();
 3673:     my @part_response_id = &flatten_responseType($responseType);
 3674:     foreach my $part_response_id (@part_response_id) {
 3675:     	my ($partid,$respid) = @{ $part_response_id };
 3676: 	my $part_resp = join('_',@{ $part_response_id });
 3677: 	next if $seen{$partid};
 3678: 	$seen{$partid}++;
 3679: 	my $handgrade=$$handgrade{$part_resp};
 3680: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3681: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3682: 
 3683: 	my $display_part=&get_display_part($partid,$symb);
 3684: 	my $radio.='<table border="0"><tr>';  
 3685: 	my $ctr = 0;
 3686: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3687: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3688: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3689: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3690: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3691: 	    $ctr++;
 3692: 	}
 3693: 	$radio.='</tr></table>';
 3694: 	my $line = '<input type="text" name="TEXTVAL_'.
 3695: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3696: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3697: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3698: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3699: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3700: 		$weight{$partid}.')"> '.
 3701: 	    '<option selected="selected"> </option>'.
 3702: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3703: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3704: 	    '</select></td>'.
 3705:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3706: 	$line.='<input type="hidden" name="partid_'.
 3707: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3708: 	$line.='<input type="hidden" name="weight_'.
 3709: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3710: 
 3711: 	$result.=
 3712: 	    &Apache::loncommon::start_data_table_row()."\n".
 3713: 	    '<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>'.
 3714: 	    &Apache::loncommon::end_data_table_row()."\n";
 3715: 	$ctsparts++;
 3716:     }
 3717:     $result.=&Apache::loncommon::end_data_table()."\n".
 3718: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3719:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3720: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3721: 
 3722:     #table listing all the students in a section/class
 3723:     #header of table
 3724:     $result.= '<h3>'.$specific_header.'</h3>'.
 3725:               &Apache::loncommon::start_data_table().
 3726: 	      &Apache::loncommon::start_data_table_header_row().
 3727: 	      '<th>'.&mt('No.').'</th>'.
 3728: 	      '<th>'.&nameUserString('header')."</th>\n";
 3729:     my $partserror;
 3730:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3731:     if ($partserror) {
 3732:         return &navmap_errormsg();
 3733:     }
 3734:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3735:     my @partids = ();
 3736:     foreach my $part (@parts) {
 3737: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3738:         my $narrowtext = &mt('Tries');
 3739: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3740: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3741: 	my ($partid) = &split_part_type($part);
 3742:         push(@partids,$partid);
 3743: 	my $display_part=&get_display_part($partid,$symb);
 3744: 	if ($display =~ /^Partial Credit Factor/) {
 3745: 	    $result.='<th>'.
 3746: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3747: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3748: 	    next;
 3749: 	    
 3750: 	} else {
 3751: 	    if ($display =~ /Problem Status/) {
 3752: 		my $grade_status_mt = &mt('Grade Status');
 3753: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3754: 	    }
 3755: 	    my $part_mt = &mt('Part:');
 3756: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3757: 	}
 3758: 
 3759: 	$result.='<th>'.$display.'</th>'."\n";
 3760:     }
 3761:     $result.=&Apache::loncommon::end_data_table_header_row();
 3762: 
 3763:     my %last_resets = 
 3764: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3765: 
 3766:     #get info for each student
 3767:     #list all the students - with points and grade status
 3768:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3769:     my $ctr = 0;
 3770:     foreach (sort 
 3771: 	     {
 3772: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3773: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3774: 		 }
 3775: 		 return $a cmp $b;
 3776: 	     } (keys(%$fullname))) {
 3777: 	$ctr++;
 3778: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3779: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3780:     }
 3781:     $result.=&Apache::loncommon::end_data_table();
 3782:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3783:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3784: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3785:     if (scalar(%$fullname) eq 0) {
 3786: 	my $colspan=3+scalar(@parts);
 3787: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3788:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3789: 	$result='<span class="LC_warning">'.
 3790: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3791: 	        $section_display, $stu_status).
 3792: 	    '</span>';
 3793:     }
 3794:     $result.=&show_grading_menu_form($symb);
 3795:     return $result;
 3796: }
 3797: 
 3798: #--- call by previous routine to display each student
 3799: sub viewstudentgrade {
 3800:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3801:     my ($uname,$udom) = split(/:/,$student);
 3802:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3803:     my %aggregates = (); 
 3804:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3805: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3806: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3807: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3808: 	'\');" target="_self">'.$fullname.'</a> '.
 3809: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3810:     $student=~s/:/_/; # colon doen't work in javascript for names
 3811:     foreach my $apart (@$parts) {
 3812: 	my ($part,$type) = &split_part_type($apart);
 3813: 	my $score=$record{"resource.$part.$type"};
 3814:         $result.='<td align="center">';
 3815:         my ($aggtries,$totaltries);
 3816:         unless (exists($aggregates{$part})) {
 3817: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3818: 
 3819: 	    $aggtries = $totaltries;
 3820:             if ($$last_resets{$part}) {  
 3821:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3822: 					   $part);
 3823:             }
 3824:             $result.='<input type="hidden" name="'.
 3825:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3826:             $result.='<input type="hidden" name="'.
 3827:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3828:             $aggregates{$part} = 1;
 3829:         }
 3830: 	if ($type eq 'awarded') {
 3831: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3832: 	    $result.='<input type="hidden" name="'.
 3833: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3834: 	    $result.='<input type="text" name="'.
 3835: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3836:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3837: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3838: 	} elsif ($type eq 'solved') {
 3839: 	    my ($status,$foo)=split(/_/,$score,2);
 3840: 	    $status = 'nothing' if ($status eq '');
 3841: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3842: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3843: 	    $result.='&nbsp;<select name="'.
 3844: 		'GD_'.$student.'_'.$part.'_solved" '.
 3845:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3846: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3847: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3848: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3849: 	    $result.="</select>&nbsp;</td>\n";
 3850: 	} else {
 3851: 	    $result.='<input type="hidden" name="'.
 3852: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3853: 		    "\n";
 3854: 	    $result.='<input type="text" name="'.
 3855: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3856: 		'value="'.$score.'" size="4" /></td>'."\n";
 3857: 	}
 3858:     }
 3859:     $result.=&Apache::loncommon::end_data_table_row();
 3860:     return $result;
 3861: }
 3862: 
 3863: #--- change scores for all the students in a section/class
 3864: #    record does not get update if unchanged
 3865: sub editgrades {
 3866:     my ($request) = @_;
 3867: 
 3868:     my ($symb)=&get_symb($request);
 3869:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3870:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3871:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3872:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3873: 
 3874:     my $result= &Apache::loncommon::start_data_table().
 3875: 	&Apache::loncommon::start_data_table_header_row().
 3876: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3877: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3878:     my %scoreptr = (
 3879: 		    'correct'  =>'correct_by_override',
 3880: 		    'incorrect'=>'incorrect_by_override',
 3881: 		    'excused'  =>'excused',
 3882: 		    'ungraded' =>'ungraded_attempted',
 3883:                     'credited' =>'credit_attempted',
 3884: 		    'nothing'  => '',
 3885: 		    );
 3886:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3887: 
 3888:     my (@partid);
 3889:     my %weight = ();
 3890:     my %columns = ();
 3891:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3892: 
 3893:     my $partserror;
 3894:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3895:     if ($partserror) {
 3896:         return &navmap_errormsg();
 3897:     }
 3898:     my $header;
 3899:     while ($ctr < $env{'form.totalparts'}) {
 3900: 	my $partid = $env{'form.partid_'.$ctr};
 3901: 	push(@partid,$partid);
 3902: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3903: 	$ctr++;
 3904:     }
 3905:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3906:     foreach my $partid (@partid) {
 3907: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3908: 	    '<th align="center">'.&mt('New Score').'</th>';
 3909: 	$columns{$partid}=2;
 3910: 	foreach my $stores (@parts) {
 3911: 	    my ($part,$type) = &split_part_type($stores);
 3912: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3913: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3914: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3915: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3916:             my $narrowtext = &mt('Tries');
 3917: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3918: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3919: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3920: 	    $columns{$partid}+=2;
 3921: 	}
 3922:     }
 3923:     foreach my $partid (@partid) {
 3924: 	my $display_part=&get_display_part($partid,$symb);
 3925: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3926: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3927: 	    '</th>';
 3928: 
 3929:     }
 3930:     $result .= &Apache::loncommon::end_data_table_header_row().
 3931: 	&Apache::loncommon::start_data_table_header_row().
 3932: 	$header.
 3933: 	&Apache::loncommon::end_data_table_header_row();
 3934:     my @noupdate;
 3935:     my ($updateCtr,$noupdateCtr) = (1,1);
 3936:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3937: 	my $line;
 3938: 	my $user = $env{'form.ctr'.$i};
 3939: 	my ($uname,$udom)=split(/:/,$user);
 3940: 	my %newrecord;
 3941: 	my $updateflag = 0;
 3942: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3943: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3944: 	if (!&canmodify($usec)) {
 3945: 	    my $numcols=scalar(@partid)*4+2;
 3946: 	    push(@noupdate,
 3947: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3948: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3949: 	    next;
 3950: 	}
 3951:         my %aggregate = ();
 3952:         my $aggregateflag = 0;
 3953: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3954: 	foreach (@partid) {
 3955: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3956: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3957: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3958: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3959: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3960: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3961: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3962: 	    my $score;
 3963: 	    if ($partial eq '') {
 3964: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3965: 	    } elsif ($partial > 0) {
 3966: 		$score = 'correct_by_override';
 3967: 	    } elsif ($partial == 0) {
 3968: 		$score = 'incorrect_by_override';
 3969: 	    }
 3970: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3971: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3972: 
 3973: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3974: 		"$env{'user.name'}:$env{'user.domain'}";
 3975: 	    if ($dropMenu eq 'reset status' &&
 3976: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3977: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3978: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3979: 		$newrecord{'resource.'.$_.'.award'} = '';
 3980: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3981: 		$updateflag = 1;
 3982:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3983:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3984:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3985:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3986:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3987:                     $aggregateflag = 1;
 3988:                 }
 3989: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3990: 		$updateflag = 1;
 3991: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3992: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3993: 		$rec_update++;
 3994: 	    }
 3995: 
 3996: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3997: 		'<td align="center">'.$awarded.
 3998: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3999: 
 4000: 
 4001: 	    my $partid=$_;
 4002: 	    foreach my $stores (@parts) {
 4003: 		my ($part,$type) = &split_part_type($stores);
 4004: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4005: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4006: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4007: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4008: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4009: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4010: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4011: 		    $updateflag=1;
 4012: 		}
 4013: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4014: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4015: 	    }
 4016: 	}
 4017: 	$line.="\n";
 4018: 
 4019: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4020: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4021: 
 4022: 	if ($updateflag) {
 4023: 	    $count++;
 4024: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4025: 				    $udom,$uname);
 4026: 
 4027: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4028: 					      $cnum,$udom,$uname)) {
 4029: 		# need to figure out if should be in queue.
 4030: 		my %record =  
 4031: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4032: 					     $udom,$uname);
 4033: 		my $all_graded = 1;
 4034: 		my $none_graded = 1;
 4035: 		foreach my $part (@parts) {
 4036: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4037: 			$all_graded = 0;
 4038: 		    } else {
 4039: 			$none_graded = 0;
 4040: 		    }
 4041: 		}
 4042: 
 4043: 		if ($all_graded || $none_graded) {
 4044: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4045: 							   $symb,$cdom,$cnum,
 4046: 							   $udom,$uname);
 4047: 		}
 4048: 	    }
 4049: 
 4050: 	    $result.=&Apache::loncommon::start_data_table_row().
 4051: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4052: 		&Apache::loncommon::end_data_table_row();
 4053: 	    $updateCtr++;
 4054: 	} else {
 4055: 	    push(@noupdate,
 4056: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4057: 	    $noupdateCtr++;
 4058: 	}
 4059:         if ($aggregateflag) {
 4060:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4061: 				  $cdom,$cnum);
 4062:         }
 4063:     }
 4064:     if (@noupdate) {
 4065: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4066: 	my $numcols=scalar(@partid)*4+2;
 4067: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4068: 	    '<td align="center" colspan="'.$numcols.'">'.
 4069: 	    &mt('No Changes Occurred For the Students Below').
 4070: 	    '</td>'.
 4071: 	    &Apache::loncommon::end_data_table_row();
 4072: 	foreach my $line (@noupdate) {
 4073: 	    $result.=
 4074: 		&Apache::loncommon::start_data_table_row().
 4075: 		$line.
 4076: 		&Apache::loncommon::end_data_table_row();
 4077: 	}
 4078:     }
 4079:     $result .= &Apache::loncommon::end_data_table().
 4080: 	&show_grading_menu_form($symb);
 4081:     my $msg = '<p><b>'.
 4082: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4083: 	    $rec_update,$count).'</b><br />'.
 4084: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4085: 	'</b></p>';
 4086:     return $title.$msg.$result;
 4087: }
 4088: 
 4089: sub split_part_type {
 4090:     my ($partstr) = @_;
 4091:     my ($temp,@allparts)=split(/_/,$partstr);
 4092:     my $type=pop(@allparts);
 4093:     my $part=join('_',@allparts);
 4094:     return ($part,$type);
 4095: }
 4096: 
 4097: #------------- end of section for handling grading by section/class ---------
 4098: #
 4099: #----------------------------------------------------------------------------
 4100: 
 4101: 
 4102: #----------------------------------------------------------------------------
 4103: #
 4104: #-------------------------- Next few routines handles grading by csv upload
 4105: #
 4106: #--- Javascript to handle csv upload
 4107: sub csvupload_javascript_reverse_associate {
 4108:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4109:     my $error2=&mt('You need to specify at least one grading field');
 4110:   return(<<ENDPICK);
 4111:   function verify(vf) {
 4112:     var foundsomething=0;
 4113:     var founduname=0;
 4114:     var foundID=0;
 4115:     for (i=0;i<=vf.nfields.value;i++) {
 4116:       tw=eval('vf.f'+i+'.selectedIndex');
 4117:       if (i==0 && tw!=0) { foundID=1; }
 4118:       if (i==1 && tw!=0) { founduname=1; }
 4119:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4120:     }
 4121:     if (founduname==0 && foundID==0) {
 4122: 	alert('$error1');
 4123: 	return;
 4124:     }
 4125:     if (foundsomething==0) {
 4126: 	alert('$error2');
 4127: 	return;
 4128:     }
 4129:     vf.submit();
 4130:   }
 4131:   function flip(vf,tf) {
 4132:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4133:     var i;
 4134:     for (i=0;i<=vf.nfields.value;i++) {
 4135:       //can not pick the same destination field for both name and domain
 4136:       if (((i ==0)||(i ==1)) && 
 4137:           ((tf==0)||(tf==1)) && 
 4138:           (i!=tf) &&
 4139:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4140:         eval('vf.f'+i+'.selectedIndex=0;')
 4141:       }
 4142:     }
 4143:   }
 4144: ENDPICK
 4145: }
 4146: 
 4147: sub csvupload_javascript_forward_associate {
 4148:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4149:     my $error2=&mt('You need to specify at least one grading field');
 4150:   return(<<ENDPICK);
 4151:   function verify(vf) {
 4152:     var foundsomething=0;
 4153:     var founduname=0;
 4154:     var foundID=0;
 4155:     for (i=0;i<=vf.nfields.value;i++) {
 4156:       tw=eval('vf.f'+i+'.selectedIndex');
 4157:       if (tw==1) { foundID=1; }
 4158:       if (tw==2) { founduname=1; }
 4159:       if (tw>3) { foundsomething=1; }
 4160:     }
 4161:     if (founduname==0 && foundID==0) {
 4162: 	alert('$error1');
 4163: 	return;
 4164:     }
 4165:     if (foundsomething==0) {
 4166: 	alert('$error2');
 4167: 	return;
 4168:     }
 4169:     vf.submit();
 4170:   }
 4171:   function flip(vf,tf) {
 4172:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4173:     var i;
 4174:     //can not pick the same destination field twice
 4175:     for (i=0;i<=vf.nfields.value;i++) {
 4176:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4177:         eval('vf.f'+i+'.selectedIndex=0;')
 4178:       }
 4179:     }
 4180:   }
 4181: ENDPICK
 4182: }
 4183: 
 4184: sub csvuploadmap_header {
 4185:     my ($request,$symb,$datatoken,$distotal)= @_;
 4186:     my $javascript;
 4187:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4188: 	$javascript=&csvupload_javascript_reverse_associate();
 4189:     } else {
 4190: 	$javascript=&csvupload_javascript_forward_associate();
 4191:     }
 4192: 
 4193:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4194:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4195:     my $ignore=&mt('Ignore First Line');
 4196:     $symb = &Apache::lonenc::check_encrypt($symb);
 4197:     $request->print(<<ENDPICK);
 4198: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4199: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4200: $result
 4201: <hr />
 4202: <h3>Identify fields</h3>
 4203: Total number of records found in file: $distotal <hr />
 4204: Enter as many fields as you can. The system will inform you and bring you back
 4205: to this page if the data selected is insufficient to run your class.<hr />
 4206: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4207: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4208: <input type="hidden" name="associate"  value="" />
 4209: <input type="hidden" name="phase"      value="three" />
 4210: <input type="hidden" name="datatoken"  value="$datatoken" />
 4211: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4212: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4213: <input type="hidden" name="upfile_associate" 
 4214:                                        value="$env{'form.upfile_associate'}" />
 4215: <input type="hidden" name="symb"       value="$symb" />
 4216: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4217: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4218: <input type="hidden" name="command"    value="csvuploadoptions" />
 4219: <hr />
 4220: <script type="text/javascript" language="Javascript">
 4221: $javascript
 4222: </script>
 4223: ENDPICK
 4224:     return '';
 4225: 
 4226: }
 4227: 
 4228: sub csvupload_fields {
 4229:     my ($symb,$errorref) = @_;
 4230:     my (@parts) = &getpartlist($symb,$errorref);
 4231:     if (ref($errorref)) {
 4232:         if ($$errorref) {
 4233:             return;
 4234:         }
 4235:     }
 4236: 
 4237:     my @fields=(['ID','Student/Employee ID'],
 4238: 		['username','Student Username'],
 4239: 		['domain','Student Domain']);
 4240:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4241:     foreach my $part (sort(@parts)) {
 4242: 	my @datum;
 4243: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4244: 	my $name=$part;
 4245: 	if  (!$display) { $display = $name; }
 4246: 	@datum=($name,$display);
 4247: 	if ($name=~/^stores_(.*)_awarded/) {
 4248: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4249: 	}
 4250: 	push(@fields,\@datum);
 4251:     }
 4252:     return (@fields);
 4253: }
 4254: 
 4255: sub csvuploadmap_footer {
 4256:     my ($request,$i,$keyfields) =@_;
 4257:     $request->print(<<ENDPICK);
 4258: </table>
 4259: <input type="hidden" name="nfields" value="$i" />
 4260: <input type="hidden" name="keyfields" value="$keyfields" />
 4261: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 4262: </form>
 4263: ENDPICK
 4264: }
 4265: 
 4266: sub checkforfile_js {
 4267:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4268:     my $result =<<CSVFORMJS;
 4269: <script type="text/javascript" language="javascript">
 4270:     function checkUpload(formname) {
 4271: 	if (formname.upfile.value == "") {
 4272: 	    alert("$alertmsg");
 4273: 	    return false;
 4274: 	}
 4275: 	formname.submit();
 4276:     }
 4277:     </script>
 4278: CSVFORMJS
 4279:     return $result;
 4280: }
 4281: 
 4282: sub upcsvScores_form {
 4283:     my ($request) = shift;
 4284:     my ($symb)=&get_symb($request);
 4285:     if (!$symb) {return '';}
 4286:     my $result=&checkforfile_js();
 4287:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4288:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4289:     $result.=$table;
 4290:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4291:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4292:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4293: 	'</b></td></tr>'."\n";
 4294:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4295:     my $upload=&mt("Upload Scores");
 4296:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4297:     my $ignore=&mt('Ignore First Line');
 4298:     $symb = &Apache::lonenc::check_encrypt($symb);
 4299:     $result.=<<ENDUPFORM;
 4300: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4301: <input type="hidden" name="symb" value="$symb" />
 4302: <input type="hidden" name="command" value="csvuploadmap" />
 4303: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4304: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4305: $upfile_select
 4306: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4307: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4308: </form>
 4309: ENDUPFORM
 4310:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4311:                            &mt("How do I create a CSV file from a spreadsheet"))
 4312:     .'</td></tr></table>'."\n";
 4313:     $result.='</td></tr></table><br /><br />'."\n";
 4314:     $result.=&show_grading_menu_form($symb);
 4315:     return $result;
 4316: }
 4317: 
 4318: 
 4319: sub csvuploadmap {
 4320:     my ($request)= @_;
 4321:     my ($symb)=&get_symb($request);
 4322:     if (!$symb) {return '';}
 4323: 
 4324:     my $datatoken;
 4325:     if (!$env{'form.datatoken'}) {
 4326: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4327:     } else {
 4328: 	$datatoken=$env{'form.datatoken'};
 4329: 	&Apache::loncommon::load_tmp_file($request);
 4330:     }
 4331:     my @records=&Apache::loncommon::upfile_record_sep();
 4332:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4333:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4334:     my ($i,$keyfields);
 4335:     if (@records) {
 4336:         my $fieldserror;
 4337: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4338:         if ($fieldserror) {
 4339:             $request->print(&navmap_errormsg());
 4340:             return;
 4341:         }
 4342: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4343: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4344: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4345: 							  \@fields);
 4346: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4347: 	    chop($keyfields);
 4348: 	} else {
 4349: 	    unshift(@fields,['none','']);
 4350: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4351: 							    \@fields);
 4352:             foreach my $rec (@records) {
 4353:                 my %temp = &Apache::loncommon::record_sep($rec);
 4354:                 if (%temp) {
 4355:                     $keyfields=join(',',sort(keys(%temp)));
 4356:                     last;
 4357:                 }
 4358:             }
 4359: 	}
 4360:     }
 4361:     &csvuploadmap_footer($request,$i,$keyfields);
 4362:     $request->print(&show_grading_menu_form($symb));
 4363: 
 4364:     return '';
 4365: }
 4366: 
 4367: sub csvuploadoptions {
 4368:     my ($request)= @_;
 4369:     my ($symb)=&get_symb($request);
 4370:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4371:     my $ignore=&mt('Ignore First Line');
 4372:     $request->print(<<ENDPICK);
 4373: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4374: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4375: <input type="hidden" name="command"    value="csvuploadassign" />
 4376: <!--
 4377: <p>
 4378: <label>
 4379:    <input type="checkbox" name="show_full_results" />
 4380:    Show a table of all changes
 4381: </label>
 4382: </p>
 4383: -->
 4384: <p>
 4385: <label>
 4386:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4387:    Overwrite any existing score
 4388: </label>
 4389: </p>
 4390: ENDPICK
 4391:     my %fields=&get_fields();
 4392:     if (!defined($fields{'domain'})) {
 4393: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4394: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4395:     }
 4396:     foreach my $key (sort(keys(%env))) {
 4397: 	if ($key !~ /^form\.(.*)$/) { next; }
 4398: 	my $cleankey=$1;
 4399: 	if ($cleankey eq 'command') { next; }
 4400: 	$request->print('<input type="hidden" name="'.$cleankey.
 4401: 			'"  value="'.$env{$key}.'" />'."\n");
 4402:     }
 4403:     # FIXME do a check for any duplicated user ids...
 4404:     # FIXME do a check for any invalid user ids?...
 4405:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4406: <hr /></form>'."\n");
 4407:     $request->print(&show_grading_menu_form($symb));
 4408:     return '';
 4409: }
 4410: 
 4411: sub get_fields {
 4412:     my %fields;
 4413:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4414:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4415: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4416: 	    if ($env{'form.f'.$i} ne 'none') {
 4417: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4418: 	    }
 4419: 	} else {
 4420: 	    if ($env{'form.f'.$i} ne 'none') {
 4421: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4422: 	    }
 4423: 	}
 4424:     }
 4425:     return %fields;
 4426: }
 4427: 
 4428: sub csvuploadassign {
 4429:     my ($request)= @_;
 4430:     my ($symb)=&get_symb($request);
 4431:     if (!$symb) {return '';}
 4432:     my $error_msg = '';
 4433:     &Apache::loncommon::load_tmp_file($request);
 4434:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4435:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4436:     my %fields=&get_fields();
 4437:     $request->print('<h3>Assigning Grades</h3>');
 4438:     my $courseid=$env{'request.course.id'};
 4439:     my ($classlist) = &getclasslist('all',0);
 4440:     my @notallowed;
 4441:     my @skipped;
 4442:     my @warnings;
 4443:     my $countdone=0;
 4444:     foreach my $grade (@gradedata) {
 4445: 	my %entries=&Apache::loncommon::record_sep($grade);
 4446: 	my $domain;
 4447: 	if ($entries{$fields{'domain'}}) {
 4448: 	    $domain=$entries{$fields{'domain'}};
 4449: 	} else {
 4450: 	    $domain=$env{'form.default_domain'};
 4451: 	}
 4452: 	$domain=~s/\s//g;
 4453: 	my $username=$entries{$fields{'username'}};
 4454: 	$username=~s/\s//g;
 4455: 	if (!$username) {
 4456: 	    my $id=$entries{$fields{'ID'}};
 4457: 	    $id=~s/\s//g;
 4458: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4459: 	    $username=$ids{$id};
 4460: 	}
 4461: 	if (!exists($$classlist{"$username:$domain"})) {
 4462: 	    my $id=$entries{$fields{'ID'}};
 4463: 	    $id=~s/\s//g;
 4464: 	    if ($id) {
 4465: 		push(@skipped,"$id:$domain");
 4466: 	    } else {
 4467: 		push(@skipped,"$username:$domain");
 4468: 	    }
 4469: 	    next;
 4470: 	}
 4471: 	my $usec=$classlist->{"$username:$domain"}[5];
 4472: 	if (!&canmodify($usec)) {
 4473: 	    push(@notallowed,"$username:$domain");
 4474: 	    next;
 4475: 	}
 4476: 	my %points;
 4477: 	my %grades;
 4478: 	foreach my $dest (keys(%fields)) {
 4479: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4480: 		$dest eq 'domain') { next; }
 4481: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4482: 	    if ($dest=~/stores_(.*)_points/) {
 4483: 		my $part=$1;
 4484: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4485: 					      $symb,$domain,$username);
 4486:                 if ($wgt) {
 4487:                     $entries{$fields{$dest}}=~s/\s//g;
 4488:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4489:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4490:                                           : 'correct_by_override';
 4491:                     if ($pcr>1) {
 4492:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4493:                     }
 4494:                     $grades{"resource.$part.awarded"}=$pcr;
 4495:                     $grades{"resource.$part.solved"}=$award;
 4496:                     $points{$part}=1;
 4497:                 } else {
 4498:                     $error_msg = "<br />" .
 4499:                         &mt("Some point values were assigned"
 4500:                             ." for problems with a weight "
 4501:                             ."of zero. These values were "
 4502:                             ."ignored.");
 4503:                 }
 4504: 	    } else {
 4505: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4506: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4507: 		my $store_key=$dest;
 4508: 		$store_key=~s/^stores/resource/;
 4509: 		$store_key=~s/_/\./g;
 4510: 		$grades{$store_key}=$entries{$fields{$dest}};
 4511: 	    }
 4512: 	}
 4513: 	if (! %grades) { 
 4514:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4515:         } else {
 4516: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4517: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4518: 					   $env{'request.course.id'},
 4519: 					   $domain,$username);
 4520: 	   if ($result eq 'ok') {
 4521: 	      $request->print('.');
 4522: # Remove from grading queue
 4523:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4524:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4525:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4526:                                              $domain,$username);
 4527: 	   } else {
 4528: 	      $request->print("<p><span class=\"LC_error\">".
 4529:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4530:                                   "$username:$domain",$result)."</span></p>");
 4531: 	   }
 4532: 	   $request->rflush();
 4533: 	   $countdone++;
 4534:         }
 4535:     }
 4536:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4537:     if (@warnings) {
 4538:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4539:         $request->print(join(', ',@warnings));
 4540:     }
 4541:     if (@skipped) {
 4542: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4543:         $request->print(join(', ',@skipped));
 4544:     }
 4545:     if (@notallowed) {
 4546: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4547: 	$request->print(join(', ',@notallowed));
 4548:     }
 4549:     $request->print("<br />\n");
 4550:     $request->print(&show_grading_menu_form($symb));
 4551:     return $error_msg;
 4552: }
 4553: #------------- end of section for handling csv file upload ---------
 4554: #
 4555: #-------------------------------------------------------------------
 4556: #
 4557: #-------------- Next few routines handle grading by page/sequence
 4558: #
 4559: #--- Select a page/sequence and a student to grade
 4560: sub pickStudentPage {
 4561:     my ($request) = shift;
 4562: 
 4563:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4564:     $request->print(<<LISTJAVASCRIPT);
 4565: <script type="text/javascript" language="javascript">
 4566: 
 4567: function checkPickOne(formname) {
 4568:     if (radioSelection(formname.student) == null) {
 4569: 	alert("$alertmsg");
 4570: 	return;
 4571:     }
 4572:     ptr = pullDownSelection(formname.selectpage);
 4573:     formname.page.value = formname["page"+ptr].value;
 4574:     formname.title.value = formname["title"+ptr].value;
 4575:     formname.submit();
 4576: }
 4577: 
 4578: </script>
 4579: LISTJAVASCRIPT
 4580:     &commonJSfunctions($request);
 4581:     my ($symb) = &get_symb($request);
 4582:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4583:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4584:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4585: 
 4586:     my $result='<h3><span class="LC_info">&nbsp;'.
 4587: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4588: 
 4589:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4590:     my $map_error;
 4591:     my ($titles,$symbx) = &getSymbMap($map_error);
 4592:     if ($map_error) {
 4593:         $request->print(&navmap_errormsg());
 4594:         return; 
 4595:     }
 4596:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4597: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4598: #    my $type=($curpage =~ /\.(page|sequence)/);
 4599:     my $select = '<select name="selectpage">'."\n";
 4600:     my $ctr=0;
 4601:     foreach (@$titles) {
 4602: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4603: 	$select.='<option value="'.$ctr.'" '.
 4604: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4605: 	    '>'.$showtitle.'</option>'."\n";
 4606: 	$ctr++;
 4607:     }
 4608:     $select.= '</select>';
 4609:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4610: 
 4611:     $ctr=0;
 4612:     foreach (@$titles) {
 4613: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4614: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4615: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4616: 	$ctr++;
 4617:     }
 4618:     $result.='<input type="hidden" name="page" />'."\n".
 4619: 	'<input type="hidden" name="title" />'."\n";
 4620: 
 4621:     my $options =
 4622: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4623: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4624:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4625: 
 4626:     $options =
 4627: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4628: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4629: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4630:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4631:     
 4632:     $result.=&build_section_inputs();
 4633:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4634:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4635: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4636: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4637: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4638: 
 4639:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4640: 
 4641:     $result.='&nbsp;<input type="button" '.
 4642:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4643: 
 4644:     $request->print($result);
 4645: 
 4646:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4647: 	&Apache::loncommon::start_data_table().
 4648: 	&Apache::loncommon::start_data_table_header_row().
 4649: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4650: 	'<th>'.&nameUserString('header').'</th>'.
 4651: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4652: 	'<th>'.&nameUserString('header').'</th>'.
 4653: 	&Apache::loncommon::end_data_table_header_row();
 4654:  
 4655:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4656:     my $ptr = 1;
 4657:     foreach my $student (sort 
 4658: 			 {
 4659: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4660: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4661: 			     }
 4662: 			     return $a cmp $b;
 4663: 			 } (keys(%$fullname))) {
 4664: 	my ($uname,$udom) = split(/:/,$student);
 4665: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4666:                                   : '</td>');
 4667: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4668: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4669: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4670: 	$studentTable.=
 4671: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4672:                          : '');
 4673: 	$ptr++;
 4674:     }
 4675:     if ($ptr%2 == 0) {
 4676: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4677: 	    &Apache::loncommon::end_data_table_row();
 4678:     }
 4679:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4680:     $studentTable.='<input type="button" '.
 4681:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4682: 
 4683:     $studentTable.=&show_grading_menu_form($symb);
 4684:     $request->print($studentTable);
 4685: 
 4686:     return '';
 4687: }
 4688: 
 4689: sub getSymbMap {
 4690:     my ($map_error) = @_;
 4691:     my $navmap = Apache::lonnavmaps::navmap->new();
 4692:     unless (ref($navmap)) {
 4693:         if (ref($map_error)) {
 4694:             $$map_error = 'navmap';
 4695:         }
 4696:         return;
 4697:     }
 4698:     my %symbx = ();
 4699:     my @titles = ();
 4700:     my $minder = 0;
 4701: 
 4702:     # Gather every sequence that has problems.
 4703:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4704: 					       1,0,1);
 4705:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4706: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4707: 	    my $title = $minder.'.'.
 4708: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4709: 	    push(@titles, $title); # minder in case two titles are identical
 4710: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4711: 	    $minder++;
 4712: 	}
 4713:     }
 4714:     return \@titles,\%symbx;
 4715: }
 4716: 
 4717: #
 4718: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4719: sub displayPage {
 4720:     my ($request) = shift;
 4721: 
 4722:     my ($symb) = &get_symb($request);
 4723:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4724:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4725:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4726:     my $pageTitle = $env{'form.page'};
 4727:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4728:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4729:     my $usec=$classlist->{$env{'form.student'}}[5];
 4730: 
 4731:     #need to make sure we have the correct data for later EXT calls, 
 4732:     #thus invalidate the cache
 4733:     &Apache::lonnet::devalidatecourseresdata(
 4734:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4735:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4736:     &Apache::lonnet::clear_EXT_cache_status();
 4737: 
 4738:     if (!&canview($usec)) {
 4739: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4740: 	$request->print(&show_grading_menu_form($symb));
 4741: 	return;
 4742:     }
 4743:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4744:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4745: 	'</h3>'."\n";
 4746:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4747:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4748: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4749:     } else {
 4750: 	delete($env{'form.CODE'});
 4751:     }
 4752:     &sub_page_js($request);
 4753:     $request->print($result);
 4754: 
 4755:     my $navmap = Apache::lonnavmaps::navmap->new();
 4756:     unless (ref($navmap)) {
 4757:         $request->print(&navmap_errormsg());
 4758:         $request->print(&show_grading_menu_form($symb));
 4759:         return;
 4760:     }
 4761:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4762:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4763:     if (!$map) {
 4764: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4765: 	$request->print(&show_grading_menu_form($symb));
 4766: 	return; 
 4767:     }
 4768:     my $iterator = $navmap->getIterator($map->map_start(),
 4769: 					$map->map_finish());
 4770: 
 4771:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4772: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4773: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4774: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4775: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4776: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4777: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4778: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4779: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4780: 
 4781:     if (defined($env{'form.CODE'})) {
 4782: 	$studentTable.=
 4783: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4784:     }
 4785:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4786: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4787: 
 4788:     $studentTable.='&nbsp;<span class="LC_info">'.
 4789:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4790:         '</span>'."\n".
 4791: 	&Apache::loncommon::start_data_table().
 4792: 	&Apache::loncommon::start_data_table_header_row().
 4793: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4794: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4795: 	&Apache::loncommon::end_data_table_header_row();
 4796: 
 4797:     &Apache::lonxml::clear_problem_counter();
 4798:     my ($depth,$question,$prob) = (1,1,1);
 4799:     $iterator->next(); # skip the first BEGIN_MAP
 4800:     my $curRes = $iterator->next(); # for "current resource"
 4801:     while ($depth > 0) {
 4802:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4803:         if($curRes == $iterator->END_MAP) { $depth--; }
 4804: 
 4805:         if (ref($curRes) && $curRes->is_problem()) {
 4806: 	    my $parts = $curRes->parts();
 4807:             my $title = $curRes->compTitle();
 4808: 	    my $symbx = $curRes->symb();
 4809: 	    $studentTable.=
 4810: 		&Apache::loncommon::start_data_table_row().
 4811: 		'<td align="center" valign="top" >'.$prob.
 4812: 		(scalar(@{$parts}) == 1 ? '' 
 4813: 		                        : '<br />('.&mt('[_1]parts',
 4814: 							scalar(@{$parts}).'&nbsp;').')'
 4815: 		 ).
 4816: 		 '</td>';
 4817: 	    $studentTable.='<td valign="top">';
 4818: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4819: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4820: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4821: 					     undef,'both',\%form);
 4822: 	    } else {
 4823: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4824: 		$companswer =~ s|<form(.*?)>||g;
 4825: 		$companswer =~ s|</form>||g;
 4826: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4827: #		    $companswer =~ s/$1/ /ms;
 4828: #		    $request->print('match='.$1."<br />\n");
 4829: #		}
 4830: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4831: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4832: 	    }
 4833: 
 4834: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4835: 
 4836: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4837: 		if ($record{'version'} eq '') {
 4838: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4839: 		} else {
 4840: 		    my %responseType = ();
 4841: 		    foreach my $partid (@{$parts}) {
 4842: 			my @responseIds =$curRes->responseIds($partid);
 4843: 			my @responseType =$curRes->responseType($partid);
 4844: 			my %responseIds;
 4845: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4846: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4847: 			}
 4848: 			$responseType{$partid} = \%responseIds;
 4849: 		    }
 4850: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4851: 
 4852: 		}
 4853: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4854: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4855: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4856: 									$env{'request.course.id'},
 4857: 									'','.submission');
 4858:  
 4859: 	    }
 4860: 	    if (&canmodify($usec)) {
 4861:             $studentTable.=&gradeBox_start();
 4862: 		foreach my $partid (@{$parts}) {
 4863: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4864: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4865: 		    $question++;
 4866: 		}
 4867:             $studentTable.=&gradeBox_end();
 4868: 		$prob++;
 4869: 	    }
 4870: 	    $studentTable.='</td></tr>';
 4871: 
 4872: 	}
 4873:         $curRes = $iterator->next();
 4874:     }
 4875: 
 4876:     $studentTable.=
 4877:         '</table>'."\n".
 4878:         '<input type="button" value="'.&mt('Save').'" '.
 4879:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4880:         '</form>'."\n";
 4881:     $studentTable.=&show_grading_menu_form($symb);
 4882:     $request->print($studentTable);
 4883: 
 4884:     return '';
 4885: }
 4886: 
 4887: sub displaySubByDates {
 4888:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4889:     my $isCODE=0;
 4890:     my $isTask = ($symb =~/\.task$/);
 4891:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4892:     my $studentTable=&Apache::loncommon::start_data_table().
 4893: 	&Apache::loncommon::start_data_table_header_row().
 4894: 	'<th>'.&mt('Date/Time').'</th>'.
 4895: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4896:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4897: 	'<th>'.&mt('Submission').'</th>'.
 4898: 	'<th>'.&mt('Status').'</th>'.
 4899: 	&Apache::loncommon::end_data_table_header_row();
 4900:     my ($version);
 4901:     my %mark;
 4902:     my %orders;
 4903:     $mark{'correct_by_student'} = $checkIcon;
 4904:     if (!exists($$record{'1:timestamp'})) {
 4905: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4906:     }
 4907: 
 4908:     my $interaction;
 4909:     my $no_increment = 1;
 4910:     my %lastrndseed;
 4911:     for ($version=1;$version<=$$record{'version'};$version++) {
 4912: 	my $timestamp = 
 4913: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4914: 	if (exists($$record{$version.':resource.0.version'})) {
 4915: 	    $interaction = $$record{$version.':resource.0.version'};
 4916: 	}
 4917:         if ($isTask && $env{'form.previousversion'}) {
 4918:             next unless ($interaction == $env{'form.previousversion'});
 4919:         }
 4920: 	my $where = ($isTask ? "$version:resource.$interaction"
 4921: 		             : "$version:resource");
 4922: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4923: 	    '<td>'.$timestamp.'</td>';
 4924: 	if ($isCODE) {
 4925: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4926: 	}
 4927:         if ($isTask) {
 4928:             $studentTable.='<td>'.$interaction.'</td>';
 4929:         }
 4930: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4931: 	my @displaySub = ();
 4932: 	foreach my $partid (@{$parts}) {
 4933:             my ($hidden,$type);
 4934:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4935:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4936:                 $hidden = 1;
 4937:             }
 4938: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4939: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4940: 	    
 4941: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4942: 	    my $display_part=&get_display_part($partid,$symb);
 4943: 	    foreach my $matchKey (@matchKey) {
 4944: 		if (exists($$record{$version.':'.$matchKey}) &&
 4945: 		    $$record{$version.':'.$matchKey} ne '') {
 4946:                     
 4947: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4948: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4949:                     $displaySub[0].='<span class="LC_nobreak">';
 4950:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4951:                                    .' <span class="LC_internal_info">'
 4952:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4953:                                    .'</span>'
 4954:                                    .' <b>';
 4955:                     if ($hidden) {
 4956:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4957:                     } else {
 4958:                         my ($trial,$rndseed,$newvariation);
 4959:                         if ($type eq 'randomizetry') {
 4960:                             $trial = $$record{"$where.$partid.tries"};
 4961:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4962:                         }
 4963: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4964: 			    $displaySub[0].=&mt('Trial not counted');
 4965: 		        } else {
 4966: 			    $displaySub[0].=&mt('Trial: [_1]',
 4967: 					    $$record{"$where.$partid.tries"});
 4968:                             if ($rndseed || $lastrndseed{$partid}) {
 4969:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4970:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4971:                                 }
 4972:                             }
 4973: 		        }
 4974: 		        my $responseType=($isTask ? 'Task'
 4975:                                               : $responseType->{$partid}->{$responseId});
 4976: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4977: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4978: 			    $orders{$partid}->{$responseId}=
 4979: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4980:                                            $no_increment,$type,$trial,$rndseed);
 4981: 		        }
 4982: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4983: 		        $displaySub[0].='&nbsp; '.
 4984: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4985:                     }
 4986: 		}
 4987: 	    }
 4988: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4989: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4990: 				    $$record{"$where.$partid.checkedin"},
 4991: 				    $$record{"$where.$partid.checkedin.slot"}).
 4992: 					'<br />';
 4993: 	    }
 4994: 	    if (exists $$record{"$where.$partid.award"}) {
 4995: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4996: 		    lc($$record{"$where.$partid.award"}).' '.
 4997: 		    $mark{$$record{"$where.$partid.solved"}}.
 4998: 		    '<br />';
 4999: 	    }
 5000: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5001: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5002: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5003: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5004: 		$displaySub[2].=
 5005: 		    $$record{"$version:resource.$partid.regrader"}.
 5006: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5007: 	    }
 5008: 	}
 5009: 	# needed because old essay regrader has not parts info
 5010: 	if (exists $$record{"$version:resource.regrader"}) {
 5011: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5012: 	}
 5013: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5014: 	if ($displaySub[2]) {
 5015: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5016: 	}
 5017: 	$studentTable.='&nbsp;</td>'.
 5018: 	    &Apache::loncommon::end_data_table_row();
 5019:     }
 5020:     $studentTable.=&Apache::loncommon::end_data_table();
 5021:     return $studentTable;
 5022: }
 5023: 
 5024: sub updateGradeByPage {
 5025:     my ($request) = shift;
 5026: 
 5027:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5028:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5029:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5030:     my $pageTitle = $env{'form.page'};
 5031:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5032:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5033:     my $usec=$classlist->{$env{'form.student'}}[5];
 5034:     if (!&canmodify($usec)) {
 5035: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5036: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5037: 	return;
 5038:     }
 5039:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5040:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5041: 	'</h3>'."\n";
 5042: 
 5043:     $request->print($result);
 5044: 
 5045: 
 5046:     my $navmap = Apache::lonnavmaps::navmap->new();
 5047:     unless (ref($navmap)) {
 5048:         $request->print(&navmap_errormsg());
 5049:         return;
 5050:     }
 5051:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5052:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5053:     if (!$map) {
 5054: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5055: 	my ($symb)=&get_symb($request);
 5056: 	$request->print(&show_grading_menu_form($symb));
 5057: 	return; 
 5058:     }
 5059:     my $iterator = $navmap->getIterator($map->map_start(),
 5060: 					$map->map_finish());
 5061: 
 5062:     my $studentTable=
 5063: 	&Apache::loncommon::start_data_table().
 5064: 	&Apache::loncommon::start_data_table_header_row().
 5065: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5066: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5067: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5068: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5069: 	&Apache::loncommon::end_data_table_header_row();
 5070: 
 5071:     $iterator->next(); # skip the first BEGIN_MAP
 5072:     my $curRes = $iterator->next(); # for "current resource"
 5073:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 5074:     while ($depth > 0) {
 5075:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5076:         if($curRes == $iterator->END_MAP) { $depth--; }
 5077: 
 5078:         if (ref($curRes) && $curRes->is_problem()) {
 5079: 	    my $parts = $curRes->parts();
 5080:             my $title = $curRes->compTitle();
 5081: 	    my $symbx = $curRes->symb();
 5082: 	    $studentTable.=
 5083: 		&Apache::loncommon::start_data_table_row().
 5084: 		'<td align="center" valign="top" >'.$prob.
 5085: 		(scalar(@{$parts}) == 1 ? '' 
 5086:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5087: 		.')').'</td>';
 5088: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5089: 
 5090: 	    my %newrecord=();
 5091: 	    my @displayPts=();
 5092:             my %aggregate = ();
 5093:             my $aggregateflag = 0;
 5094: 	    foreach my $partid (@{$parts}) {
 5095: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5096: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5097: 
 5098: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5099: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5100: 		my $partial = $newpts/$wgt;
 5101: 		my $score;
 5102: 		if ($partial > 0) {
 5103: 		    $score = 'correct_by_override';
 5104: 		} elsif ($newpts ne '') { #empty is taken as 0
 5105: 		    $score = 'incorrect_by_override';
 5106: 		}
 5107: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5108: 		if ($dropMenu eq 'excused') {
 5109: 		    $partial = '';
 5110: 		    $score = 'excused';
 5111: 		} elsif ($dropMenu eq 'reset status'
 5112: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5113: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5114: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5115: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5116: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5117: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5118: 		    $changeflag++;
 5119: 		    $newpts = '';
 5120:                     
 5121:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5122:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5123:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5124:                     if ($aggtries > 0) {
 5125:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5126:                         $aggregateflag = 1;
 5127:                     }
 5128: 		}
 5129: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5130: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5131: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5132: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5133: 		    '&nbsp;<br />';
 5134: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5135: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5136: 		    '&nbsp;<br />';
 5137: 		$question++;
 5138: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5139: 
 5140: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5141: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5142: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5143: 		    if (scalar(keys(%newrecord)) > 0);
 5144: 
 5145: 		$changeflag++;
 5146: 	    }
 5147: 	    if (scalar(keys(%newrecord)) > 0) {
 5148: 		my %record = 
 5149: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5150: 					     $udom,$uname);
 5151: 
 5152: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5153: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5154: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5155: 		    $newrecord{'resource.CODE'} = '';
 5156: 		}
 5157: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5158: 					$udom,$uname);
 5159: 		%record = &Apache::lonnet::restore($symbx,
 5160: 						   $env{'request.course.id'},
 5161: 						   $udom,$uname);
 5162: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5163: 					     $cdom,$cnum,$udom,$uname);
 5164: 	    }
 5165: 	    
 5166:             if ($aggregateflag) {
 5167:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5168:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5169:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5170:             }
 5171: 
 5172: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5173: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5174: 		&Apache::loncommon::end_data_table_row();
 5175: 
 5176: 	    $prob++;
 5177: 	}
 5178:         $curRes = $iterator->next();
 5179:     }
 5180: 
 5181:     $studentTable.=&Apache::loncommon::end_data_table();
 5182:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5183:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5184: 		  &mt('The scores were changed for [quant,_1,problem].',
 5185: 		  $changeflag));
 5186:     $request->print($grademsg.$studentTable);
 5187: 
 5188:     return '';
 5189: }
 5190: 
 5191: #-------- end of section for handling grading by page/sequence ---------
 5192: #
 5193: #-------------------------------------------------------------------
 5194: 
 5195: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5196: #
 5197: #------ start of section for handling grading by page/sequence ---------
 5198: 
 5199: =pod
 5200: 
 5201: =head1 Bubble sheet grading routines
 5202: 
 5203:   For this documentation:
 5204: 
 5205:    'scanline' refers to the full line of characters
 5206:    from the file that we are parsing that represents one entire sheet
 5207: 
 5208:    'bubble line' refers to the data
 5209:    representing the line of bubbles that are on the physical bubblesheet
 5210: 
 5211: 
 5212: The overall process is that a scanned in bubblesheet data is uploaded
 5213: into a course. When a user wants to grade, they select a
 5214: sequence/folder of resources, a file of bubblesheet info, and pick
 5215: one of the predefined configurations for what each scanline looks
 5216: like.
 5217: 
 5218: Next each scanline is checked for any errors of either 'missing
 5219: bubbles' (it's an error because it may have been mis-scanned
 5220: because too light bubbling), 'double bubble' (each bubble line should
 5221: have no more that one letter picked), invalid or duplicated CODE,
 5222: invalid student/employee ID
 5223: 
 5224: If the CODE option is used that determines the randomization of the
 5225: homework problems, either way the student/employee ID is looked up into a
 5226: username:domain.
 5227: 
 5228: During the validation phase the instructor can choose to skip scanlines. 
 5229: 
 5230: After the validation phase, there are now 3 bubblesheet files
 5231: 
 5232:   scantron_original_filename (unmodified original file)
 5233:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5234:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5235: 
 5236: Also there is a separate hash nohist_scantrondata that contains extra
 5237: correction information that isn't representable in the bubblesheet
 5238: file (see &scantron_getfile() for more information)
 5239: 
 5240: After all scanlines are either valid, marked as valid or skipped, then
 5241: foreach line foreach problem in the picked sequence, an ssi request is
 5242: made that simulates a user submitting their selected letter(s) against
 5243: the homework problem.
 5244: 
 5245: =over 4
 5246: 
 5247: 
 5248: 
 5249: =item defaultFormData
 5250: 
 5251:   Returns html hidden inputs used to hold context/default values.
 5252: 
 5253:  Arguments:
 5254:   $symb - $symb of the current resource 
 5255: 
 5256: =cut
 5257: 
 5258: sub defaultFormData {
 5259:     my ($symb)=@_;
 5260:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5261:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5262:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5263: }
 5264: 
 5265: 
 5266: =pod 
 5267: 
 5268: =item getSequenceDropDown
 5269: 
 5270:    Return html dropdown of possible sequences to grade
 5271:  
 5272:  Arguments:
 5273:    $symb - $symb of the current resource
 5274:    $map_error - ref to scalar which will container error if
 5275:                 $navmap object is unavailable in &getSymbMap().
 5276: 
 5277: =cut
 5278: 
 5279: sub getSequenceDropDown {
 5280:     my ($symb,$map_error)=@_;
 5281:     my $result='<select name="selectpage">'."\n";
 5282:     my ($titles,$symbx) = &getSymbMap($map_error);
 5283:     if (ref($map_error)) {
 5284:         return if ($$map_error);
 5285:     }
 5286:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5287:     my $ctr=0;
 5288:     foreach (@$titles) {
 5289: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5290: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5291: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5292: 	    '>'.$showtitle.'</option>'."\n";
 5293: 	$ctr++;
 5294:     }
 5295:     $result.= '</select>';
 5296:     return $result;
 5297: }
 5298: 
 5299: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5300:                                    # key is zero-based index - 0, 1, 2 ...
 5301: 
 5302: my %first_bubble_line;             # First bubble line no. for each bubble.
 5303: 
 5304: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5305:                                    # matchresponse or rankresponse, where 
 5306:                                    # an individual response can have multiple 
 5307:                                    # lines
 5308: 
 5309: my %responsetype_per_response;     # responsetype for each response
 5310: 
 5311: # Save and restore the bubble lines array to the form env.
 5312: 
 5313: 
 5314: sub save_bubble_lines {
 5315:     foreach my $line (keys(%bubble_lines_per_response)) {
 5316: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5317: 	$env{"form.scantron.first_bubble_line.$line"} =
 5318: 	    $first_bubble_line{$line};
 5319:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5320:             $subdivided_bubble_lines{$line};
 5321:         $env{"form.scantron.responsetype.$line"} =
 5322:             $responsetype_per_response{$line};
 5323:     }
 5324: }
 5325: 
 5326: 
 5327: sub restore_bubble_lines {
 5328:     my $line = 0;
 5329:     %bubble_lines_per_response = ();
 5330:     while ($env{"form.scantron.bubblelines.$line"}) {
 5331: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5332: 	$bubble_lines_per_response{$line} = $value;
 5333: 	$first_bubble_line{$line}  =
 5334: 	    $env{"form.scantron.first_bubble_line.$line"};
 5335:         $subdivided_bubble_lines{$line} =
 5336:             $env{"form.scantron.sub_bubblelines.$line"};
 5337:         $responsetype_per_response{$line} =
 5338:             $env{"form.scantron.responsetype.$line"};
 5339: 	$line++;
 5340:     }
 5341: }
 5342: 
 5343: #  Given the parsed scanline, get the response for 
 5344: #  'answer' number n:
 5345: 
 5346: sub get_response_bubbles {
 5347:     my ($parsed_line, $response)  = @_;
 5348: 
 5349:     my $bubble_line = $first_bubble_line{$response-1} +1;
 5350:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 5351:     
 5352:     my $selected = "";
 5353: 
 5354:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 5355: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 5356: 	$bubble_line++;
 5357:     }
 5358:     return $selected;
 5359: }
 5360: 
 5361: =pod 
 5362: 
 5363: =item scantron_filenames
 5364: 
 5365:    Returns a list of the scantron files in the current course 
 5366: 
 5367: =cut
 5368: 
 5369: sub scantron_filenames {
 5370:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5371:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5372:     my $getpropath = 1;
 5373:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5374:                                                         $cname,$getpropath);
 5375:     my @possiblenames;
 5376:     if (ref($dirlist) eq 'ARRAY') {
 5377:         foreach my $filename (sort(@{$dirlist})) {
 5378: 	    ($filename)=split(/&/,$filename);
 5379: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5380: 	    $filename=~s/^scantron_orig_//;
 5381: 	    push(@possiblenames,$filename);
 5382:         }
 5383:     }
 5384:     return @possiblenames;
 5385: }
 5386: 
 5387: =pod 
 5388: 
 5389: =item scantron_uploads
 5390: 
 5391:    Returns  html drop-down list of scantron files in current course.
 5392: 
 5393:  Arguments:
 5394:    $file2grade - filename to set as selected in the dropdown
 5395: 
 5396: =cut
 5397: 
 5398: sub scantron_uploads {
 5399:     my ($file2grade) = @_;
 5400:     my $result=	'<select name="scantron_selectfile">';
 5401:     $result.="<option></option>";
 5402:     foreach my $filename (sort(&scantron_filenames())) {
 5403: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5404:     }
 5405:     $result.="</select>";
 5406:     return $result;
 5407: }
 5408: 
 5409: =pod 
 5410: 
 5411: =item scantron_scantab
 5412: 
 5413:   Returns html drop down of the scantron formats in the scantronformat.tab
 5414:   file.
 5415: 
 5416: =cut
 5417: 
 5418: sub scantron_scantab {
 5419:     my $result='<select name="scantron_format">'."\n";
 5420:     $result.='<option></option>'."\n";
 5421:     my @lines = &get_scantronformat_file();
 5422:     if (@lines > 0) {
 5423:         foreach my $line (@lines) {
 5424:             next if (($line =~ /^\#/) || ($line eq ''));
 5425: 	    my ($name,$descrip)=split(/:/,$line);
 5426: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5427:         }
 5428:     }
 5429:     $result.='</select>'."\n";
 5430:     return $result;
 5431: }
 5432: 
 5433: =pod
 5434: 
 5435: =item get_scantronformat_file
 5436: 
 5437:   Returns an array containing lines from the scantron format file for
 5438:   the domain of the course.
 5439: 
 5440:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5441:   lines are from this file.
 5442: 
 5443:   Otherwise, if a default.tab has been published in RES space by the 
 5444:   domainconfig user, lines are from this file.
 5445: 
 5446:   Otherwise, fall back to getting lines from the legacy file on the
 5447:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5448: 
 5449: =cut
 5450: 
 5451: sub get_scantronformat_file {
 5452:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5453:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5454:     my $gottab = 0;
 5455:     my @lines;
 5456:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5457:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5458:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5459:             if ($formatfile ne '-1') {
 5460:                 @lines = split("\n",$formatfile,-1);
 5461:                 $gottab = 1;
 5462:             }
 5463:         }
 5464:     }
 5465:     if (!$gottab) {
 5466:         my $confname = $cdom.'-domainconfig';
 5467:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5468:         my $formatfile =  &Apache::lonnet::getfile($default);
 5469:         if ($formatfile ne '-1') {
 5470:             @lines = split("\n",$formatfile,-1);
 5471:             $gottab = 1;
 5472:         }
 5473:     }
 5474:     if (!$gottab) {
 5475:         my @domains = &Apache::lonnet::current_machine_domains();
 5476:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5477:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5478:             @lines = <$fh>;
 5479:             close($fh);
 5480:         } else {
 5481:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5482:             @lines = <$fh>;
 5483:             close($fh);
 5484:         }
 5485:     }
 5486:     return @lines;
 5487: }
 5488: 
 5489: =pod 
 5490: 
 5491: =item scantron_CODElist
 5492: 
 5493:   Returns html drop down of the saved CODE lists from current course,
 5494:   generated from earlier printings.
 5495: 
 5496: =cut
 5497: 
 5498: sub scantron_CODElist {
 5499:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5500:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5501:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5502:     my $namechoice='<option></option>';
 5503:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5504: 	if ($name =~ /^error: 2 /) { next; }
 5505: 	if ($name =~ /^type\0/) { next; }
 5506: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5507:     }
 5508:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5509:     return $namechoice;
 5510: }
 5511: 
 5512: =pod 
 5513: 
 5514: =item scantron_CODEunique
 5515: 
 5516:   Returns the html for "Each CODE to be used once" radio.
 5517: 
 5518: =cut
 5519: 
 5520: sub scantron_CODEunique {
 5521:     my $result='<span class="LC_nobreak">
 5522:                  <label><input type="radio" name="scantron_CODEunique"
 5523:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5524:                 </span>
 5525:                 <span class="LC_nobreak">
 5526:                  <label><input type="radio" name="scantron_CODEunique"
 5527:                         value="no" />'.&mt('No').' </label>
 5528:                 </span>';
 5529:     return $result;
 5530: }
 5531: 
 5532: =pod 
 5533: 
 5534: =item scantron_selectphase
 5535: 
 5536:   Generates the initial screen to start the bubblesheet process.
 5537:   Allows for - starting a grading run.
 5538:              - downloading existing scan data (original, corrected
 5539:                                                 or skipped info)
 5540: 
 5541:              - uploading new scan data
 5542: 
 5543:  Arguments:
 5544:   $r          - The Apache request object
 5545:   $file2grade - name of the file that contain the scanned data to score
 5546: 
 5547: =cut
 5548: 
 5549: sub scantron_selectphase {
 5550:     my ($r,$file2grade) = @_;
 5551:     my ($symb)=&get_symb($r);
 5552:     if (!$symb) {return '';}
 5553:     my $map_error;
 5554:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5555:     if ($map_error) {
 5556:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5557:         return;
 5558:     }
 5559:     my $default_form_data=&defaultFormData($symb);
 5560:     my $grading_menu_button=&show_grading_menu_form($symb);
 5561:     my $file_selector=&scantron_uploads($file2grade);
 5562:     my $format_selector=&scantron_scantab();
 5563:     my $CODE_selector=&scantron_CODElist();
 5564:     my $CODE_unique=&scantron_CODEunique();
 5565:     my $result;
 5566: 
 5567:     $ssi_error = 0;
 5568: 
 5569:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5570:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5571: 
 5572:         # Chunk of form to prompt for a scantron file upload.
 5573: 
 5574:         $r->print('
 5575:     <br />
 5576:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5577:        '.&Apache::loncommon::start_data_table_header_row().'
 5578:             <th>
 5579:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5580:             </th>
 5581:        '.&Apache::loncommon::end_data_table_header_row().'
 5582:        '.&Apache::loncommon::start_data_table_row().'
 5583:             <td>
 5584: ');
 5585:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5586:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5587:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5588:     $r->print('
 5589:               <script type="text/javascript" language="javascript">
 5590:     function checkUpload(formname) {
 5591:         if (formname.upfile.value == "") {
 5592:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5593:             return false;
 5594:         }
 5595:         formname.submit();
 5596:     }
 5597:               </script>
 5598: 
 5599:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5600:                 '.$default_form_data.'
 5601:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5602:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5603:                 <input name="command" value="scantronupload_save" type="hidden" />
 5604:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5605:                 <br />
 5606:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5607:               </form>
 5608: ');
 5609: 
 5610:         $r->print('
 5611:             </td>
 5612:        '.&Apache::loncommon::end_data_table_row().'
 5613:        '.&Apache::loncommon::end_data_table().'
 5614: ');
 5615:     }
 5616: 
 5617:     # Chunk of form to prompt for a file to grade and how:
 5618: 
 5619:     $result.= '
 5620:     <br />
 5621:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5622:     <input type="hidden" name="command" value="scantron_warning" />
 5623:     '.$default_form_data.'
 5624:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5625:        '.&Apache::loncommon::start_data_table_header_row().'
 5626:             <th colspan="2">
 5627:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5628:             </th>
 5629:        '.&Apache::loncommon::end_data_table_header_row().'
 5630:        '.&Apache::loncommon::start_data_table_row().'
 5631:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5632:        '.&Apache::loncommon::end_data_table_row().'
 5633:        '.&Apache::loncommon::start_data_table_row().'
 5634:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5635:        '.&Apache::loncommon::end_data_table_row().'
 5636:        '.&Apache::loncommon::start_data_table_row().'
 5637:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5638:        '.&Apache::loncommon::end_data_table_row().'
 5639:        '.&Apache::loncommon::start_data_table_row().'
 5640:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5641:        '.&Apache::loncommon::end_data_table_row().'
 5642:        '.&Apache::loncommon::start_data_table_row().'
 5643:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5644:        '.&Apache::loncommon::end_data_table_row().'
 5645:        '.&Apache::loncommon::start_data_table_row().'
 5646: 	    <td> '.&mt('Options:').' </td>
 5647:             <td>
 5648: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5649:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5650:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5651: 	    </td>
 5652:        '.&Apache::loncommon::end_data_table_row().'
 5653:        '.&Apache::loncommon::start_data_table_row().'
 5654:             <td colspan="2">
 5655:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5656:             </td>
 5657:        '.&Apache::loncommon::end_data_table_row().'
 5658:     '.&Apache::loncommon::end_data_table().'
 5659:     </form>
 5660: ';
 5661:    
 5662:     $r->print($result);
 5663: 
 5664:     # Chunk of the form that prompts to view a scoring office file,
 5665:     # corrected file, skipped records in a file.
 5666: 
 5667:     $r->print('
 5668:    <br />
 5669:    <form action="/adm/grades" name="scantron_download">
 5670:      '.$default_form_data.'
 5671:      <input type="hidden" name="command" value="scantron_download" />
 5672:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5673:        '.&Apache::loncommon::start_data_table_header_row().'
 5674:               <th>
 5675:                 &nbsp;'.&mt('Download a scoring office file').'
 5676:               </th>
 5677:        '.&Apache::loncommon::end_data_table_header_row().'
 5678:        '.&Apache::loncommon::start_data_table_row().'
 5679:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5680:                 <br />
 5681:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5682:        '.&Apache::loncommon::end_data_table_row().'
 5683:      '.&Apache::loncommon::end_data_table().'
 5684:    </form>
 5685:    <br />
 5686: ');
 5687: 
 5688:     &Apache::lonpickcode::code_list($r,2);
 5689: 
 5690:     $r->print('<br /><form method="post" name="checkscantron">'.
 5691:              $default_form_data."\n".
 5692:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5693:              &Apache::loncommon::start_data_table_header_row()."\n".
 5694:              '<th colspan="2">
 5695:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5696:              '</th>'."\n".
 5697:               &Apache::loncommon::end_data_table_header_row()."\n".
 5698:               &Apache::loncommon::start_data_table_row()."\n".
 5699:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5700:               '<td> '.$sequence_selector.' </td>'.
 5701:               &Apache::loncommon::end_data_table_row()."\n".
 5702:               &Apache::loncommon::start_data_table_row()."\n".
 5703:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5704:               '<td> '.$file_selector.' </td>'."\n".
 5705:               &Apache::loncommon::end_data_table_row()."\n".
 5706:               &Apache::loncommon::start_data_table_row()."\n".
 5707:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5708:               '<td> '.$format_selector.' </td>'."\n".
 5709:               &Apache::loncommon::end_data_table_row()."\n".
 5710:               &Apache::loncommon::start_data_table_row()."\n".
 5711:               '<td> '.&mt('Options').' </td>'."\n".
 5712:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5713:               &Apache::loncommon::end_data_table_row()."\n".
 5714:               &Apache::loncommon::start_data_table_row()."\n".
 5715:               '<td colspan="2">'."\n".
 5716:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5717:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5718:               '</td>'."\n".
 5719:               &Apache::loncommon::end_data_table_row()."\n".
 5720:               &Apache::loncommon::end_data_table()."\n".
 5721:               '</form><br />');
 5722:     $r->print($grading_menu_button);
 5723:     return;
 5724: }
 5725: 
 5726: =pod
 5727: 
 5728: =item get_scantron_config
 5729: 
 5730:    Parse and return the scantron configuration line selected as a
 5731:    hash of configuration file fields.
 5732: 
 5733:  Arguments:
 5734:     which - the name of the configuration to parse from the file.
 5735: 
 5736: 
 5737:  Returns:
 5738:             If the named configuration is not in the file, an empty
 5739:             hash is returned.
 5740:     a hash with the fields
 5741:       name         - internal name for the this configuration setup
 5742:       description  - text to display to operator that describes this config
 5743:       CODElocation - if 0 or the string 'none'
 5744:                           - no CODE exists for this config
 5745:                      if -1 || the string 'letter'
 5746:                           - a CODE exists for this config and is
 5747:                             a string of letters
 5748:                      Unsupported value (but planned for future support)
 5749:                           if a positive integer
 5750:                                - The CODE exists as the first n items from
 5751:                                  the question section of the form
 5752:                           if the string 'number'
 5753:                                - The CODE exists for this config and is
 5754:                                  a string of numbers
 5755:       CODEstart   - (only matter if a CODE exists) column in the line where
 5756:                      the CODE starts
 5757:       CODElength  - length of the CODE
 5758:       IDstart     - column where the student/employee ID starts
 5759:       IDlength    - length of the student/employee ID info
 5760:       Qstart      - column where the information from the bubbled
 5761:                     'questions' start
 5762:       Qlength     - number of columns comprising a single bubble line from
 5763:                     the sheet. (usually either 1 or 10)
 5764:       Qon         - either a single character representing the character used
 5765:                     to signal a bubble was chosen in the positional setup, or
 5766:                     the string 'letter' if the letter of the chosen bubble is
 5767:                     in the final, or 'number' if a number representing the
 5768:                     chosen bubble is in the file (1->A 0->J)
 5769:       Qoff        - the character used to represent that a bubble was
 5770:                     left blank
 5771:       PaperID     - if the scanning process generates a unique number for each
 5772:                     sheet scanned the column that this ID number starts in
 5773:       PaperIDlength - number of columns that comprise the unique ID number
 5774:                       for the sheet of paper
 5775:       FirstName   - column that the first name starts in
 5776:       FirstNameLength - number of columns that the first name spans
 5777:  
 5778:       LastName    - column that the last name starts in
 5779:       LastNameLength - number of columns that the last name spans
 5780:       BubblesPerRow - number of bubbles available in each row used to
 5781:                       bubble an answer. (If not specified, 10 assumed).
 5782: 
 5783: =cut
 5784: 
 5785: sub get_scantron_config {
 5786:     my ($which) = @_;
 5787:     my @lines = &get_scantronformat_file();
 5788:     my %config;
 5789:     #FIXME probably should move to XML it has already gotten a bit much now
 5790:     foreach my $line (@lines) {
 5791: 	my ($name,$descrip)=split(/:/,$line);
 5792: 	if ($name ne $which ) { next; }
 5793: 	chomp($line);
 5794: 	my @config=split(/:/,$line);
 5795: 	$config{'name'}=$config[0];
 5796: 	$config{'description'}=$config[1];
 5797: 	$config{'CODElocation'}=$config[2];
 5798: 	$config{'CODEstart'}=$config[3];
 5799: 	$config{'CODElength'}=$config[4];
 5800: 	$config{'IDstart'}=$config[5];
 5801: 	$config{'IDlength'}=$config[6];
 5802: 	$config{'Qstart'}=$config[7];
 5803:  	$config{'Qlength'}=$config[8];
 5804: 	$config{'Qoff'}=$config[9];
 5805: 	$config{'Qon'}=$config[10];
 5806: 	$config{'PaperID'}=$config[11];
 5807: 	$config{'PaperIDlength'}=$config[12];
 5808: 	$config{'FirstName'}=$config[13];
 5809: 	$config{'FirstNamelength'}=$config[14];
 5810: 	$config{'LastName'}=$config[15];
 5811: 	$config{'LastNamelength'}=$config[16];
 5812:         $config{'BubblesPerRow'}=$config[17];
 5813: 	last;
 5814:     }
 5815:     return %config;
 5816: }
 5817: 
 5818: =pod 
 5819: 
 5820: =item username_to_idmap
 5821: 
 5822:     creates a hash keyed by student/employee ID with values of the corresponding
 5823:     student username:domain.
 5824: 
 5825:   Arguments:
 5826: 
 5827:     $classlist - reference to the class list hash. This is a hash
 5828:                  keyed by student name:domain  whose elements are references
 5829:                  to arrays containing various chunks of information
 5830:                  about the student. (See loncoursedata for more info).
 5831: 
 5832:   Returns
 5833:     %idmap - the constructed hash
 5834: 
 5835: =cut
 5836: 
 5837: sub username_to_idmap {
 5838:     my ($classlist)= @_;
 5839:     my %idmap;
 5840:     foreach my $student (keys(%$classlist)) {
 5841: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5842: 	    $student;
 5843:     }
 5844:     return %idmap;
 5845: }
 5846: 
 5847: =pod
 5848: 
 5849: =item scantron_fixup_scanline
 5850: 
 5851:    Process a requested correction to a scanline.
 5852: 
 5853:   Arguments:
 5854:     $scantron_config   - hash from &get_scantron_config()
 5855:     $scan_data         - hash of correction information 
 5856:                           (see &scantron_getfile())
 5857:     $line              - existing scanline
 5858:     $whichline         - line number of the passed in scanline
 5859:     $field             - type of change to process 
 5860:                          (either 
 5861:                           'ID'     -> correct the student/employee ID
 5862:                           'CODE'   -> correct the CODE
 5863:                           'answer' -> fixup the submitted answers)
 5864:     
 5865:    $args               - hash of additional info,
 5866:                           - 'ID' 
 5867:                                'newid' -> studentID to use in replacement
 5868:                                           of existing one
 5869:                           - 'CODE' 
 5870:                                'CODE_ignore_dup' - set to true if duplicates
 5871:                                                    should be ignored.
 5872: 	                       'CODE' - is new code or 'use_unfound'
 5873:                                         if the existing unfound code should
 5874:                                         be used as is
 5875:                           - 'answer'
 5876:                                'response' - new answer or 'none' if blank
 5877:                                'question' - the bubble line to change
 5878:                                'questionnum' - the question identifier,
 5879:                                                may include subquestion. 
 5880: 
 5881:   Returns:
 5882:     $line - the modified scanline
 5883: 
 5884:   Side effects: 
 5885:     $scan_data - may be updated
 5886: 
 5887: =cut
 5888: 
 5889: 
 5890: sub scantron_fixup_scanline {
 5891:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5892:     if ($field eq 'ID') {
 5893: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5894: 	    return ($line,1,'New value too large');
 5895: 	}
 5896: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5897: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5898: 				     $args->{'newid'});
 5899: 	}
 5900: 	substr($line,$$scantron_config{'IDstart'}-1,
 5901: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5902: 	if ($args->{'newid'}=~/^\s*$/) {
 5903: 	    &scan_data($scan_data,"$whichline.user",
 5904: 		       $args->{'username'}.':'.$args->{'domain'});
 5905: 	}
 5906:     } elsif ($field eq 'CODE') {
 5907: 	if ($args->{'CODE_ignore_dup'}) {
 5908: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5909: 	}
 5910: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5911: 	if ($args->{'CODE'} ne 'use_unfound') {
 5912: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5913: 		return ($line,1,'New CODE value too large');
 5914: 	    }
 5915: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5916: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5917: 	    }
 5918: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5919: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5920: 	}
 5921:     } elsif ($field eq 'answer') {
 5922: 	my $length=$scantron_config->{'Qlength'};
 5923: 	my $off=$scantron_config->{'Qoff'};
 5924: 	my $on=$scantron_config->{'Qon'};
 5925: 	my $answer=${off}x$length;
 5926: 	if ($args->{'response'} eq 'none') {
 5927: 	    &scan_data($scan_data,
 5928: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5929: 	} else {
 5930: 	    if ($on eq 'letter') {
 5931: 		my @alphabet=('A'..'Z');
 5932: 		$answer=$alphabet[$args->{'response'}];
 5933: 	    } elsif ($on eq 'number') {
 5934: 		$answer=$args->{'response'}+1;
 5935: 		if ($answer == 10) { $answer = '0'; }
 5936: 	    } else {
 5937: 		substr($answer,$args->{'response'},1)=$on;
 5938: 	    }
 5939: 	    &scan_data($scan_data,
 5940: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5941: 	}
 5942: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5943: 	substr($line,$where-1,$length)=$answer;
 5944:     }
 5945:     return $line;
 5946: }
 5947: 
 5948: =pod
 5949: 
 5950: =item scan_data
 5951: 
 5952:     Edit or look up  an item in the scan_data hash.
 5953: 
 5954:   Arguments:
 5955:     $scan_data  - The hash (see scantron_getfile)
 5956:     $key        - shorthand of the key to edit (actual key is
 5957:                   scantronfilename_key).
 5958:     $data        - New value of the hash entry.
 5959:     $delete      - If true, the entry is removed from the hash.
 5960: 
 5961:   Returns:
 5962:     The new value of the hash table field (undefined if deleted).
 5963: 
 5964: =cut
 5965: 
 5966: 
 5967: sub scan_data {
 5968:     my ($scan_data,$key,$value,$delete)=@_;
 5969:     my $filename=$env{'form.scantron_selectfile'};
 5970:     if (defined($value)) {
 5971: 	$scan_data->{$filename.'_'.$key} = $value;
 5972:     }
 5973:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5974:     return $scan_data->{$filename.'_'.$key};
 5975: }
 5976: 
 5977: # ----- These first few routines are general use routines.----
 5978: 
 5979: # Return the number of occurences of a pattern in a string.
 5980: 
 5981: sub occurence_count {
 5982:     my ($string, $pattern) = @_;
 5983: 
 5984:     my @matches = ($string =~ /$pattern/g);
 5985: 
 5986:     return scalar(@matches);
 5987: }
 5988: 
 5989: 
 5990: # Take a string known to have digits and convert all the
 5991: # digits into letters in the range J,A..I.
 5992: 
 5993: sub digits_to_letters {
 5994:     my ($input) = @_;
 5995: 
 5996:     my @alphabet = ('J', 'A'..'I');
 5997: 
 5998:     my @input    = split(//, $input);
 5999:     my $output ='';
 6000:     for (my $i = 0; $i < scalar(@input); $i++) {
 6001: 	if ($input[$i] =~ /\d/) {
 6002: 	    $output .= $alphabet[$input[$i]];
 6003: 	} else {
 6004: 	    $output .= $input[$i];
 6005: 	}
 6006:     }
 6007:     return $output;
 6008: }
 6009: 
 6010: =pod 
 6011: 
 6012: =item scantron_parse_scanline
 6013: 
 6014:   Decodes a scanline from the selected scantron file
 6015: 
 6016:  Arguments:
 6017:     line             - The text of the scantron file line to process
 6018:     whichline        - Line number
 6019:     scantron_config  - Hash describing the format of the scantron lines.
 6020:     scan_data        - Hash of extra information about the scanline
 6021:                        (see scantron_getfile for more information)
 6022:     just_header      - True if should not process question answers but only
 6023:                        the stuff to the left of the answers.
 6024:  Returns:
 6025:    Hash containing the result of parsing the scanline
 6026: 
 6027:    Keys are all proceeded by the string 'scantron.'
 6028: 
 6029:        CODE    - the CODE in use for this scanline
 6030:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6031:                  by the operator
 6032:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6033:                             CODEs were selected, but the usage has been
 6034:                             forced by the operator
 6035:        ID  - student/employee ID
 6036:        PaperID - if used, the ID number printed on the sheet when the 
 6037:                  paper was scanned
 6038:        FirstName - first name from the sheet
 6039:        LastName  - last name from the sheet
 6040: 
 6041:      if just_header was not true these key may also exist
 6042: 
 6043:        missingerror - a list of bubble ranges that are considered to be answers
 6044:                       to a single question that don't have any bubbles filled in.
 6045:                       Of the form questionnumber:firstbubblenumber:count.
 6046:        doubleerror  - a list of bubble ranges that are considered to be answers
 6047:                       to a single question that have more than one bubble filled in.
 6048:                       Of the form questionnumber::firstbubblenumber:count
 6049:    
 6050:                 In the above, count is the number of bubble responses in the
 6051:                 input line needed to represent the possible answers to the question.
 6052:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6053:                 per line would have count = 2.
 6054: 
 6055:        maxquest     - the number of the last bubble line that was parsed
 6056: 
 6057:        (<number> starts at 1)
 6058:        <number>.answer - zero or more letters representing the selected
 6059:                          letters from the scanline for the bubble line 
 6060:                          <number>.
 6061:                          if blank there was either no bubble or there where
 6062:                          multiple bubbles, (consult the keys missingerror and
 6063:                          doubleerror if this is an error condition)
 6064: 
 6065: =cut
 6066: 
 6067: sub scantron_parse_scanline {
 6068:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 6069: 
 6070:     my %record;
 6071:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6072:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6073:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 6074:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6075: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6076: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6077: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6078: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6079: 	    $record{'scantron.CODE'}=substr($data,
 6080: 					    $$scantron_config{'CODEstart'}-1,
 6081: 					    $$scantron_config{'CODElength'});
 6082: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6083: 		$record{'scantron.useCODE'}=1;
 6084: 	    }
 6085: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6086: 		$record{'scantron.CODE_ignore_dup'}=1;
 6087: 	    }
 6088: 	} else {
 6089: 	    #FIXME interpret first N questions
 6090: 	}
 6091:     }
 6092:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6093: 				  $$scantron_config{'IDlength'});
 6094:     $record{'scantron.PaperID'}=
 6095: 	substr($data,$$scantron_config{'PaperID'}-1,
 6096: 	       $$scantron_config{'PaperIDlength'});
 6097:     $record{'scantron.FirstName'}=
 6098: 	substr($data,$$scantron_config{'FirstName'}-1,
 6099: 	       $$scantron_config{'FirstNamelength'});
 6100:     $record{'scantron.LastName'}=
 6101: 	substr($data,$$scantron_config{'LastName'}-1,
 6102: 	       $$scantron_config{'LastNamelength'});
 6103:     if ($just_header) { return \%record; }
 6104: 
 6105:     my @alphabet=('A'..'Z');
 6106:     my $questnum=0;
 6107:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6108: 
 6109:     chomp($questions);		# Get rid of any trailing \n.
 6110:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6111:     while (length($questions)) {
 6112: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 6113:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6114:                              || 1;
 6115:         $questnum++;
 6116:         my $quest_id = $questnum;
 6117:         my $currentquest = substr($questions,0,$answer_length);
 6118:         $questions       = substr($questions,$answer_length);
 6119:         if (length($currentquest) < $answer_length) { next; }
 6120: 
 6121:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 6122:             my $subquestnum = 1;
 6123:             my $subquestions = $currentquest;
 6124:             my @subanswers_needed = 
 6125:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 6126:             foreach my $subans (@subanswers_needed) {
 6127:                 my $subans_length =
 6128:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6129:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6130:                 $subquestions   = substr($subquestions,$subans_length);
 6131:                 $quest_id = "$questnum.$subquestnum";
 6132:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6133:                     ($$scantron_config{'Qon'} eq 'number')) {
 6134:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6135:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6136:                         \@alphabet,\%record,$scantron_config,$scan_data);
 6137:                 } else {
 6138:                     $ansnum = &scantron_validator_positional($ansnum,
 6139:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 6140:                 }
 6141:                 $subquestnum ++;
 6142:             }
 6143:         } else {
 6144:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6145:                 ($$scantron_config{'Qon'} eq 'number')) {
 6146:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6147:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6148:                     \@alphabet,\%record,$scantron_config,$scan_data);
 6149:             } else {
 6150:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6151:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6152:                     \@alphabet,\%record,$scantron_config,$scan_data);
 6153:             }
 6154:         }
 6155:     }
 6156:     $record{'scantron.maxquest'}=$questnum;
 6157:     return \%record;
 6158: }
 6159: 
 6160: sub scantron_validator_lettnum {
 6161:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6162:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 6163: 
 6164:     # Qon 'letter' implies for each slot in currquest we have:
 6165:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6166:     #    about anything else (esp. a value of Qoff) for missing
 6167:     #    bubbles.
 6168:     #
 6169:     # Qon 'number' implies each slot gives a digit that indexes the
 6170:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6171:     #    and * or ? for double bubbles on a single line.
 6172:     #
 6173: 
 6174:     my $matchon;
 6175:     if ($$scantron_config{'Qon'} eq 'letter') {
 6176:         $matchon = '[A-Z]';
 6177:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6178:         $matchon = '\d';
 6179:     }
 6180:     my $occurrences = 0;
 6181:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 6182:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 6183:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 6184:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 6185:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 6186:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 6187:         my @singlelines = split('',$currquest);
 6188:         foreach my $entry (@singlelines) {
 6189:             $occurrences = &occurence_count($entry,$matchon);
 6190:             if ($occurrences > 1) {
 6191:                 last;
 6192:             }
 6193:         } 
 6194:     } else {
 6195:         $occurrences = &occurence_count($currquest,$matchon); 
 6196:     }
 6197:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6198:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6199:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6200:             my $bubble = substr($currquest,$ans,1);
 6201:             if ($bubble =~ /$matchon/ ) {
 6202:                 if ($$scantron_config{'Qon'} eq 'number') {
 6203:                     if ($bubble == 0) {
 6204:                         $bubble = 10; 
 6205:                     }
 6206:                     $record->{"scantron.$ansnum.answer"} = 
 6207:                         $alphabet->[$bubble-1];
 6208:                 } else {
 6209:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6210:                 }
 6211:             } else {
 6212:                 $record->{"scantron.$ansnum.answer"}='';
 6213:             }
 6214:             $ansnum++;
 6215:         }
 6216:     } elsif (!defined($currquest)
 6217:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6218:             || (&occurence_count($currquest,$matchon) == 0)) {
 6219:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6220:             $record->{"scantron.$ansnum.answer"}='';
 6221:             $ansnum++;
 6222:         }
 6223:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6224:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6225:         }
 6226:     } else {
 6227:         if ($$scantron_config{'Qon'} eq 'number') {
 6228:             $currquest = &digits_to_letters($currquest);            
 6229:         }
 6230:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6231:             my $bubble = substr($currquest,$ans,1);
 6232:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6233:             $ansnum++;
 6234:         }
 6235:     }
 6236:     return $ansnum;
 6237: }
 6238: 
 6239: sub scantron_validator_positional {
 6240:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6241:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 6242: 
 6243:     # Otherwise there's a positional notation;
 6244:     # each bubble line requires Qlength items, and there are filled in
 6245:     # bubbles for each case where there 'Qon' characters.
 6246:     #
 6247: 
 6248:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6249: 
 6250:     # If the split only gives us one element.. the full length of the
 6251:     # answer string, no bubbles are filled in:
 6252: 
 6253:     if ($answers_needed eq '') {
 6254:         return;
 6255:     }
 6256: 
 6257:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6258:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6259:             $record->{"scantron.$ansnum.answer"}='';
 6260:             $ansnum++;
 6261:         }
 6262:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6263:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6264:         }
 6265:     } elsif (scalar(@array) == 2) {
 6266:         my $location = length($array[0]);
 6267:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6268:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6269:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6270:             if ($ans eq $line_num) {
 6271:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6272:             } else {
 6273:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6274:             }
 6275:             $ansnum++;
 6276:          }
 6277:     } else {
 6278:         #  If there's more than one instance of a bubble character
 6279:         #  That's a double bubble; with positional notation we can
 6280:         #  record all the bubbles filled in as well as the
 6281:         #  fact this response consists of multiple bubbles.
 6282:         #
 6283:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 6284:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 6285:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 6286:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 6287:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 6288:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 6289:             my $doubleerror = 0;
 6290:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6291:                    (!$doubleerror)) {
 6292:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6293:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6294:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6295:                if (length(@currarray) > 2) {
 6296:                    $doubleerror = 1;
 6297:                } 
 6298:             }
 6299:             if ($doubleerror) {
 6300:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6301:             }
 6302:         } else {
 6303:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6304:         }
 6305:         my $item = $ansnum;
 6306:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6307:             $record->{"scantron.$item.answer"} = '';
 6308:             $item ++;
 6309:         }
 6310: 
 6311:         my @ans=@array;
 6312:         my $i=0;
 6313:         my $increment = 0;
 6314:         while ($#ans) {
 6315:             $i+=length($ans[0]) + $increment;
 6316:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6317:             my $bubble = $i%$$scantron_config{'Qlength'};
 6318:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6319:             shift(@ans);
 6320:             $increment = 1;
 6321:         }
 6322:         $ansnum += $answers_needed;
 6323:     }
 6324:     return $ansnum;
 6325: }
 6326: 
 6327: =pod
 6328: 
 6329: =item scantron_add_delay
 6330: 
 6331:    Adds an error message that occurred during the grading phase to a
 6332:    queue of messages to be shown after grading pass is complete
 6333: 
 6334:  Arguments:
 6335:    $delayqueue  - arrary ref of hash ref of error messages
 6336:    $scanline    - the scanline that caused the error
 6337:    $errormesage - the error message
 6338:    $errorcode   - a numeric code for the error
 6339: 
 6340:  Side Effects:
 6341:    updates the $delayqueue to have a new hash ref of the error
 6342: 
 6343: =cut
 6344: 
 6345: sub scantron_add_delay {
 6346:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6347:     push(@$delayqueue,
 6348: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6349: 	  'ecode' => $errorcode }
 6350: 	 );
 6351: }
 6352: 
 6353: =pod
 6354: 
 6355: =item scantron_find_student
 6356: 
 6357:    Finds the username for the current scanline
 6358: 
 6359:   Arguments:
 6360:    $scantron_record - hash result from scantron_parse_scanline
 6361:    $scan_data       - hash of correction information 
 6362:                       (see &scantron_getfile() form more information)
 6363:    $idmap           - hash from &username_to_idmap()
 6364:    $line            - number of current scanline
 6365:  
 6366:   Returns:
 6367:    Either 'username:domain' or undef if unknown
 6368: 
 6369: =cut
 6370: 
 6371: sub scantron_find_student {
 6372:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6373:     my $scanID=$$scantron_record{'scantron.ID'};
 6374:     if ($scanID =~ /^\s*$/) {
 6375:  	return &scan_data($scan_data,"$line.user");
 6376:     }
 6377:     foreach my $id (keys(%$idmap)) {
 6378:  	if (lc($id) eq lc($scanID)) {
 6379:  	    return $$idmap{$id};
 6380:  	}
 6381:     }
 6382:     return undef;
 6383: }
 6384: 
 6385: =pod
 6386: 
 6387: =item scantron_filter
 6388: 
 6389:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6390:    hidden resources was selected
 6391: 
 6392: =cut
 6393: 
 6394: sub scantron_filter {
 6395:     my ($curres)=@_;
 6396: 
 6397:     if (ref($curres) && $curres->is_problem()) {
 6398: 	# if the user has asked to not have either hidden
 6399: 	# or 'randomout' controlled resources to be graded
 6400: 	# don't include them
 6401: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6402: 	    && $curres->randomout) {
 6403: 	    return 0;
 6404: 	}
 6405: 	return 1;
 6406:     }
 6407:     return 0;
 6408: }
 6409: 
 6410: =pod
 6411: 
 6412: =item scantron_process_corrections
 6413: 
 6414:    Gets correction information out of submitted form data and corrects
 6415:    the scanline
 6416: 
 6417: =cut
 6418: 
 6419: sub scantron_process_corrections {
 6420:     my ($r) = @_;
 6421:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6422:     my ($scanlines,$scan_data)=&scantron_getfile();
 6423:     my $classlist=&Apache::loncoursedata::get_classlist();
 6424:     my $which=$env{'form.scantron_line'};
 6425:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6426:     my ($skip,$err,$errmsg);
 6427:     if ($env{'form.scantron_skip_record'}) {
 6428: 	$skip=1;
 6429:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6430: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6431: 	    $env{'form.scantron_domain'};
 6432: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6433: 	($line,$err,$errmsg)=
 6434: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6435: 				     'ID',{'newid'=>$newid,
 6436: 				    'username'=>$env{'form.scantron_username'},
 6437: 				    'domain'=>$env{'form.scantron_domain'}});
 6438:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6439: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6440: 	my $newCODE;
 6441: 	my %args;
 6442: 	if      ($resolution eq 'use_unfound') {
 6443: 	    $newCODE='use_unfound';
 6444: 	} elsif ($resolution eq 'use_found') {
 6445: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6446: 	} elsif ($resolution eq 'use_typed') {
 6447: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6448: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6449: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6450: 	}
 6451: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6452: 	    $args{'CODE_ignore_dup'}=1;
 6453: 	}
 6454: 	$args{'CODE'}=$newCODE;
 6455: 	($line,$err,$errmsg)=
 6456: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6457: 				     'CODE',\%args);
 6458:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6459: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6460: 	    ($line,$err,$errmsg)=
 6461: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6462: 					 $which,'answer',
 6463: 					 { 'question'=>$question,
 6464: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6465:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6466: 	    if ($err) { last; }
 6467: 	}
 6468:     }
 6469:     if ($err) {
 6470: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6471:     } else {
 6472: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6473: 	&scantron_putfile($scanlines,$scan_data);
 6474:     }
 6475: }
 6476: 
 6477: =pod
 6478: 
 6479: =item reset_skipping_status
 6480: 
 6481:    Forgets the current set of remember skipped scanlines (and thus
 6482:    reverts back to considering all lines in the
 6483:    scantron_skipped_<filename> file)
 6484: 
 6485: =cut
 6486: 
 6487: sub reset_skipping_status {
 6488:     my ($scanlines,$scan_data)=&scantron_getfile();
 6489:     &scan_data($scan_data,'remember_skipping',undef,1);
 6490:     &scantron_putfile(undef,$scan_data);
 6491: }
 6492: 
 6493: =pod
 6494: 
 6495: =item start_skipping
 6496: 
 6497:    Marks a scanline to be skipped. 
 6498: 
 6499: =cut
 6500: 
 6501: sub start_skipping {
 6502:     my ($scan_data,$i)=@_;
 6503:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6504:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6505: 	$remembered{$i}=2;
 6506:     } else {
 6507: 	$remembered{$i}=1;
 6508:     }
 6509:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6510: }
 6511: 
 6512: =pod
 6513: 
 6514: =item should_be_skipped
 6515: 
 6516:    Checks whether a scanline should be skipped.
 6517: 
 6518: =cut
 6519: 
 6520: sub should_be_skipped {
 6521:     my ($scanlines,$scan_data,$i)=@_;
 6522:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6523: 	# not redoing old skips
 6524: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6525: 	return 0;
 6526:     }
 6527:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6528: 
 6529:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6530: 	return 0;
 6531:     }
 6532:     return 1;
 6533: }
 6534: 
 6535: =pod
 6536: 
 6537: =item remember_current_skipped
 6538: 
 6539:    Discovers what scanlines are in the scantron_skipped_<filename>
 6540:    file and remembers them into scan_data for later use.
 6541: 
 6542: =cut
 6543: 
 6544: sub remember_current_skipped {
 6545:     my ($scanlines,$scan_data)=&scantron_getfile();
 6546:     my %to_remember;
 6547:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6548: 	if ($scanlines->{'skipped'}[$i]) {
 6549: 	    $to_remember{$i}=1;
 6550: 	}
 6551:     }
 6552: 
 6553:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6554:     &scantron_putfile(undef,$scan_data);
 6555: }
 6556: 
 6557: =pod
 6558: 
 6559: =item check_for_error
 6560: 
 6561:     Checks if there was an error when attempting to remove a specific
 6562:     scantron_.. bubblesheet data file. Prints out an error if
 6563:     something went wrong.
 6564: 
 6565: =cut
 6566: 
 6567: sub check_for_error {
 6568:     my ($r,$result)=@_;
 6569:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6570: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6571:     }
 6572: }
 6573: 
 6574: =pod
 6575: 
 6576: =item scantron_warning_screen
 6577: 
 6578:    Interstitial screen to make sure the operator has selected the
 6579:    correct options before we start the validation phase.
 6580: 
 6581: =cut
 6582: 
 6583: sub scantron_warning_screen {
 6584:     my ($button_text)=@_;
 6585:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6586:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6587:     my $CODElist;
 6588:     if ($scantron_config{'CODElocation'} &&
 6589: 	$scantron_config{'CODEstart'} &&
 6590: 	$scantron_config{'CODElength'}) {
 6591: 	$CODElist=$env{'form.scantron_CODElist'};
 6592: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6593: 	$CODElist=
 6594: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6595: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6596:     }
 6597:     my $lastbubblepoints;
 6598:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6599:         $lastbubblepoints =
 6600:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6601:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6602:     }
 6603:     return ('
 6604: <p>
 6605: <span class="LC_warning">
 6606: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6607: </p>
 6608: <table>
 6609: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6610: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6611: '.$CODElist.$lastbubblepoints.'
 6612: </table>
 6613: <br />
 6614: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 6615: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 6616: 
 6617: <br />
 6618: ');
 6619: }
 6620: 
 6621: =pod
 6622: 
 6623: =item scantron_do_warning
 6624: 
 6625:    Check if the operator has picked something for all required
 6626:    fields. Error out if something is missing.
 6627: 
 6628: =cut
 6629: 
 6630: sub scantron_do_warning {
 6631:     my ($r)=@_;
 6632:     my ($symb)=&get_symb($r);
 6633:     if (!$symb) {return '';}
 6634:     my $default_form_data=&defaultFormData($symb);
 6635:     $r->print(&scantron_form_start().$default_form_data);
 6636:     if ( $env{'form.selectpage'} eq '' ||
 6637: 	 $env{'form.scantron_selectfile'} eq '' ||
 6638: 	 $env{'form.scantron_format'} eq '' ) {
 6639: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6640: 	if ( $env{'form.selectpage'} eq '') {
 6641: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6642: 	} 
 6643: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6644: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6645: 	} 
 6646: 	if ( $env{'form.scantron_format'} eq '') {
 6647: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6648: 	} 
 6649:     } else {
 6650: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6651:         my $bubbledbyhand=&hand_bubble_option();
 6652: 	$r->print('
 6653: '.$warning.$bubbledbyhand.'
 6654: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6655: <input type="hidden" name="command" value="scantron_validate" />
 6656: ');
 6657:     }
 6658:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6659:     return '';
 6660: }
 6661: 
 6662: =pod
 6663: 
 6664: =item scantron_form_start
 6665: 
 6666:     html hidden input for remembering all selected grading options
 6667: 
 6668: =cut
 6669: 
 6670: sub scantron_form_start {
 6671:     my ($max_bubble)=@_;
 6672:     my $result= <<SCANTRONFORM;
 6673: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6674:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6675:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6676:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6677:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6678:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6679:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6680:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6681:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6682:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6683: SCANTRONFORM
 6684: 
 6685:   my $line = 0;
 6686:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6687:        my $chunk =
 6688: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6689:        $chunk .=
 6690: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6691:        $chunk .= 
 6692:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6693:        $chunk .=
 6694:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6695:        $result .= $chunk;
 6696:        $line++;
 6697:    }
 6698:     return $result;
 6699: }
 6700: 
 6701: =pod
 6702: 
 6703: =item scantron_validate_file
 6704: 
 6705:     Dispatch routine for doing validation of a bubblesheet data file.
 6706: 
 6707:     Also processes any necessary information resets that need to
 6708:     occur before validation begins (ignore previous corrections,
 6709:     restarting the skipped records processing)
 6710: 
 6711: =cut
 6712: 
 6713: sub scantron_validate_file {
 6714:     my ($r) = @_;
 6715:     my ($symb)=&get_symb($r);
 6716:     if (!$symb) {return '';}
 6717:     my $default_form_data=&defaultFormData($symb);
 6718:     
 6719:     # do the detection of only doing skipped records first befroe we delete
 6720:     # them when doing the corrections reset
 6721:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6722: 	&reset_skipping_status();
 6723:     }
 6724:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6725: 	&remember_current_skipped();
 6726: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6727:     }
 6728: 
 6729:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6730: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6731: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6732: 	&check_for_error($r,&scantron_remove_scan_data());
 6733: 	$env{'form.scantron_options_ignore'}='done';
 6734:     }
 6735: 
 6736:     if ($env{'form.scantron_corrections'}) {
 6737: 	&scantron_process_corrections($r);
 6738:     }
 6739:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6740:     #get the student pick code ready
 6741:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6742:     my $nav_error;
 6743:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6744:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6745:     if ($nav_error) {
 6746:         $r->print(&navmap_errormsg());
 6747:         return '';
 6748:     }
 6749:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6750:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6751:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6752:     }
 6753:     $r->print($result);
 6754:     
 6755:     my @validate_phases=( 'sequence',
 6756: 			  'ID',
 6757: 			  'CODE',
 6758: 			  'doublebubble',
 6759: 			  'missingbubbles');
 6760:     if (!$env{'form.validatepass'}) {
 6761: 	$env{'form.validatepass'} = 0;
 6762:     }
 6763:     my $currentphase=$env{'form.validatepass'};
 6764: 
 6765: 
 6766:     my $stop=0;
 6767:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6768: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6769: 	$r->rflush();
 6770: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6771: 	{
 6772: 	    no strict 'refs';
 6773: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6774: 	}
 6775:     }
 6776:     if (!$stop) {
 6777: 	my $warning=&scantron_warning_screen('Start Grading');
 6778: 	$r->print(&mt('Validation process complete.').'<br />'.
 6779:                   $warning.
 6780:                   &mt('Perform verification for each student after storage of submissions?').
 6781:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6782:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6783:                   ('&nbsp;'x3).'<label>'.
 6784:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6785:                   '</label></span><br />'.
 6786:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6787:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6788:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6789:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6790:     } else {
 6791: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6792: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6793:     }
 6794:     if ($stop) {
 6795: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6796: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6797: 	    $r->print(' '.&mt('this error').' <br />');
 6798: 
 6799: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6800: 	} else {
 6801:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6802: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6803:             } else {
 6804:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6805:             }
 6806: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6807: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6808: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6809: 	}
 6810:     }
 6811:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6812:     return '';
 6813: }
 6814: 
 6815: 
 6816: =pod
 6817: 
 6818: =item scantron_remove_file
 6819: 
 6820:    Removes the requested bubblesheet data file, makes sure that
 6821:    scantron_original_<filename> is never removed
 6822: 
 6823: 
 6824: =cut
 6825: 
 6826: sub scantron_remove_file {
 6827:     my ($which)=@_;
 6828:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6829:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6830:     my $file='scantron_';
 6831:     if ($which eq 'corrected' || $which eq 'skipped') {
 6832: 	$file.=$which.'_';
 6833:     } else {
 6834: 	return 'refused';
 6835:     }
 6836:     $file.=$env{'form.scantron_selectfile'};
 6837:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6838: }
 6839: 
 6840: 
 6841: =pod
 6842: 
 6843: =item scantron_remove_scan_data
 6844: 
 6845:    Removes all scan_data correction for the requested bubblesheet
 6846:    data file.  (In the case that both the are doing skipped records we need
 6847:    to remember the old skipped lines for the time being so that element
 6848:    persists for a while.)
 6849: 
 6850: =cut
 6851: 
 6852: sub scantron_remove_scan_data {
 6853:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6854:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6855:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6856:     my @todelete;
 6857:     my $filename=$env{'form.scantron_selectfile'};
 6858:     foreach my $key (@keys) {
 6859: 	if ($key=~/^\Q$filename\E_/) {
 6860: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6861: 		$key=~/remember_skipping/) {
 6862: 		next;
 6863: 	    }
 6864: 	    push(@todelete,$key);
 6865: 	}
 6866:     }
 6867:     my $result;
 6868:     if (@todelete) {
 6869: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6870: 				       \@todelete,$cdom,$cname);
 6871:     } else {
 6872: 	$result = 'ok';
 6873:     }
 6874:     return $result;
 6875: }
 6876: 
 6877: 
 6878: =pod
 6879: 
 6880: =item scantron_getfile
 6881: 
 6882:     Fetches the requested bubblesheet data file (all 3 versions), and
 6883:     the scan_data hash
 6884:   
 6885:   Arguments:
 6886:     None
 6887: 
 6888:   Returns:
 6889:     2 hash references
 6890: 
 6891:      - first one has 
 6892:          orig      -
 6893:          corrected -
 6894:          skipped   -  each of which points to an array ref of the specified
 6895:                       file broken up into individual lines
 6896:          count     - number of scanlines
 6897:  
 6898:      - second is the scan_data hash possible keys are
 6899:        ($number refers to scanline numbered $number and thus the key affects
 6900:         only that scanline
 6901:         $bubline refers to the specific bubble line element and the aspects
 6902:         refers to that specific bubble line element)
 6903: 
 6904:        $number.user - username:domain to use
 6905:        $number.CODE_ignore_dup 
 6906:                     - ignore the duplicate CODE error 
 6907:        $number.useCODE
 6908:                     - use the CODE in the scanline as is
 6909:        $number.no_bubble.$bubline
 6910:                     - it is valid that there is no bubbled in bubble
 6911:                       at $number $bubline
 6912:        remember_skipping
 6913:                     - a frozen hash containing keys of $number and values
 6914:                       of either 
 6915:                         1 - we are on a 'do skipped records pass' and plan
 6916:                             on processing this line
 6917:                         2 - we are on a 'do skipped records pass' and this
 6918:                             scanline has been marked to skip yet again
 6919: 
 6920: =cut
 6921: 
 6922: sub scantron_getfile {
 6923:     #FIXME really would prefer a scantron directory
 6924:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6925:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6926:     my $lines;
 6927:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6928: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6929:     my %scanlines;
 6930:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6931:     my $temp=$scanlines{'orig'};
 6932:     $scanlines{'count'}=$#$temp;
 6933: 
 6934:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6935: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6936:     if ($lines eq '-1') {
 6937: 	$scanlines{'corrected'}=[];
 6938:     } else {
 6939: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6940:     }
 6941:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6942: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6943:     if ($lines eq '-1') {
 6944: 	$scanlines{'skipped'}=[];
 6945:     } else {
 6946: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6947:     }
 6948:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6949:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6950:     my %scan_data = @tmp;
 6951:     return (\%scanlines,\%scan_data);
 6952: }
 6953: 
 6954: =pod
 6955: 
 6956: =item lonnet_putfile
 6957: 
 6958:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6959: 
 6960:  Arguments:
 6961:    $contents - data to store
 6962:    $filename - filename to store $contents into
 6963: 
 6964:  Returns:
 6965:    result value from &Apache::lonnet::finishuserfileupload
 6966: 
 6967: =cut
 6968: 
 6969: sub lonnet_putfile {
 6970:     my ($contents,$filename)=@_;
 6971:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6972:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6973:     $env{'form.sillywaytopassafilearound'}=$contents;
 6974:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6975: 
 6976: }
 6977: 
 6978: =pod
 6979: 
 6980: =item scantron_putfile
 6981: 
 6982:     Stores the current version of the bubblesheet data files, and the
 6983:     scan_data hash. (Does not modify the original version only the
 6984:     corrected and skipped versions.
 6985: 
 6986:  Arguments:
 6987:     $scanlines - hash ref that looks like the first return value from
 6988:                  &scantron_getfile()
 6989:     $scan_data - hash ref that looks like the second return value from
 6990:                  &scantron_getfile()
 6991: 
 6992: =cut
 6993: 
 6994: sub scantron_putfile {
 6995:     my ($scanlines,$scan_data) = @_;
 6996:     #FIXME really would prefer a scantron directory
 6997:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6998:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6999:     if ($scanlines) {
 7000: 	my $prefix='scantron_';
 7001: # no need to update orig, shouldn't change
 7002: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7003: #		    $env{'form.scantron_selectfile'});
 7004: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7005: 			$prefix.'corrected_'.
 7006: 			$env{'form.scantron_selectfile'});
 7007: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7008: 			$prefix.'skipped_'.
 7009: 			$env{'form.scantron_selectfile'});
 7010:     }
 7011:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7012: }
 7013: 
 7014: =pod
 7015: 
 7016: =item scantron_get_line
 7017: 
 7018:    Returns the correct version of the scanline
 7019: 
 7020:  Arguments:
 7021:     $scanlines - hash ref that looks like the first return value from
 7022:                  &scantron_getfile()
 7023:     $scan_data - hash ref that looks like the second return value from
 7024:                  &scantron_getfile()
 7025:     $i         - number of the requested line (starts at 0)
 7026: 
 7027:  Returns:
 7028:    A scanline, (either the original or the corrected one if it
 7029:    exists), or undef if the requested scanline should be
 7030:    skipped. (Either because it's an skipped scanline, or it's an
 7031:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7032:    pass.
 7033: 
 7034: =cut
 7035: 
 7036: sub scantron_get_line {
 7037:     my ($scanlines,$scan_data,$i)=@_;
 7038:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7039:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7040:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7041:     return $scanlines->{'orig'}[$i]; 
 7042: }
 7043: 
 7044: =pod
 7045: 
 7046: =item scantron_todo_count
 7047: 
 7048:     Counts the number of scanlines that need processing.
 7049: 
 7050:  Arguments:
 7051:     $scanlines - hash ref that looks like the first return value from
 7052:                  &scantron_getfile()
 7053:     $scan_data - hash ref that looks like the second return value from
 7054:                  &scantron_getfile()
 7055: 
 7056:  Returns:
 7057:     $count - number of scanlines to process
 7058: 
 7059: =cut
 7060: 
 7061: sub get_todo_count {
 7062:     my ($scanlines,$scan_data)=@_;
 7063:     my $count=0;
 7064:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7065: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7066: 	if ($line=~/^[\s\cz]*$/) { next; }
 7067: 	$count++;
 7068:     }
 7069:     return $count;
 7070: }
 7071: 
 7072: =pod
 7073: 
 7074: =item scantron_put_line
 7075: 
 7076:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7077:     data file.
 7078: 
 7079:  Arguments:
 7080:     $scanlines - hash ref that looks like the first return value from
 7081:                  &scantron_getfile()
 7082:     $scan_data - hash ref that looks like the second return value from
 7083:                  &scantron_getfile()
 7084:     $i         - line number to update
 7085:     $newline   - contents of the updated scanline
 7086:     $skip      - if true make the line for skipping and update the
 7087:                  'skipped' file
 7088: 
 7089: =cut
 7090: 
 7091: sub scantron_put_line {
 7092:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7093:     if ($skip) {
 7094: 	$scanlines->{'skipped'}[$i]=$newline;
 7095: 	&start_skipping($scan_data,$i);
 7096: 	return;
 7097:     }
 7098:     $scanlines->{'corrected'}[$i]=$newline;
 7099: }
 7100: 
 7101: =pod
 7102: 
 7103: =item scantron_clear_skip
 7104: 
 7105:    Remove a line from the 'skipped' file
 7106: 
 7107:  Arguments:
 7108:     $scanlines - hash ref that looks like the first return value from
 7109:                  &scantron_getfile()
 7110:     $scan_data - hash ref that looks like the second return value from
 7111:                  &scantron_getfile()
 7112:     $i         - line number to update
 7113: 
 7114: =cut
 7115: 
 7116: sub scantron_clear_skip {
 7117:     my ($scanlines,$scan_data,$i)=@_;
 7118:     if (exists($scanlines->{'skipped'}[$i])) {
 7119: 	undef($scanlines->{'skipped'}[$i]);
 7120: 	return 1;
 7121:     }
 7122:     return 0;
 7123: }
 7124: 
 7125: =pod
 7126: 
 7127: =item scantron_filter_not_exam
 7128: 
 7129:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7130:    filter out resources that are not marked as 'exam' mode
 7131: 
 7132: =cut
 7133: 
 7134: sub scantron_filter_not_exam {
 7135:     my ($curres)=@_;
 7136:     
 7137:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7138: 	# if the user has asked to not have either hidden
 7139: 	# or 'randomout' controlled resources to be graded
 7140: 	# don't include them
 7141: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7142: 	    && $curres->randomout) {
 7143: 	    return 0;
 7144: 	}
 7145: 	return 1;
 7146:     }
 7147:     return 0;
 7148: }
 7149: 
 7150: =pod
 7151: 
 7152: =item scantron_validate_sequence
 7153: 
 7154:     Validates the selected sequence, checking for resource that are
 7155:     not set to exam mode.
 7156: 
 7157: =cut
 7158: 
 7159: sub scantron_validate_sequence {
 7160:     my ($r,$currentphase) = @_;
 7161: 
 7162:     my $navmap=Apache::lonnavmaps::navmap->new();
 7163:     unless (ref($navmap)) {
 7164:         $r->print(&navmap_errormsg());
 7165:         return (1,$currentphase);
 7166:     }
 7167:     my (undef,undef,$sequence)=
 7168: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7169: 
 7170:     my $map=$navmap->getResourceByUrl($sequence);
 7171: 
 7172:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7173:                                     value="ignore" />');
 7174:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7175: 	my @resources=
 7176: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7177: 	if (@resources) {
 7178: 	    $r->print('<p class="LC_warning">'
 7179:                .&mt('Some resources in the sequence currently are not set to'
 7180:                    .' exam mode. Grading these resources currently may not'
 7181:                    .' work correctly.')
 7182:                .'</p>'
 7183:             );
 7184: 	    return (1,$currentphase);
 7185: 	}
 7186:     }
 7187: 
 7188:     return (0,$currentphase+1);
 7189: }
 7190: 
 7191: 
 7192: 
 7193: sub scantron_validate_ID {
 7194:     my ($r,$currentphase) = @_;
 7195:     
 7196:     #get student info
 7197:     my $classlist=&Apache::loncoursedata::get_classlist();
 7198:     my %idmap=&username_to_idmap($classlist);
 7199: 
 7200:     #get scantron line setup
 7201:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7202:     my ($scanlines,$scan_data)=&scantron_getfile();
 7203: 
 7204:     my $nav_error;
 7205:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7206:     if ($nav_error) {
 7207:         $r->print(&navmap_errormsg());
 7208:         return(1,$currentphase);
 7209:     }
 7210: 
 7211:     my %found=('ids'=>{},'usernames'=>{});
 7212:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7213: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7214: 	if ($line=~/^[\s\cz]*$/) { next; }
 7215: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7216: 						 $scan_data);
 7217: 	my $id=$$scan_record{'scantron.ID'};
 7218: 	my $found;
 7219: 	foreach my $checkid (keys(%idmap)) {
 7220: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7221: 	}
 7222: 	if ($found) {
 7223: 	    my $username=$idmap{$found};
 7224: 	    if ($found{'ids'}{$found}) {
 7225: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7226: 					 $line,'duplicateID',$found);
 7227: 		return(1,$currentphase);
 7228: 	    } elsif ($found{'usernames'}{$username}) {
 7229: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7230: 					 $line,'duplicateID',$username);
 7231: 		return(1,$currentphase);
 7232: 	    }
 7233: 	    #FIXME store away line we previously saw the ID on to use above
 7234: 	    $found{'ids'}{$found}++;
 7235: 	    $found{'usernames'}{$username}++;
 7236: 	} else {
 7237: 	    if ($id =~ /^\s*$/) {
 7238: 		my $username=&scan_data($scan_data,"$i.user");
 7239: 		if (defined($username) && $found{'usernames'}{$username}) {
 7240: 		    &scantron_get_correction($r,$i,$scan_record,
 7241: 					     \%scantron_config,
 7242: 					     $line,'duplicateID',$username);
 7243: 		    return(1,$currentphase);
 7244: 		} elsif (!defined($username)) {
 7245: 		    &scantron_get_correction($r,$i,$scan_record,
 7246: 					     \%scantron_config,
 7247: 					     $line,'incorrectID');
 7248: 		    return(1,$currentphase);
 7249: 		}
 7250: 		$found{'usernames'}{$username}++;
 7251: 	    } else {
 7252: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7253: 					 $line,'incorrectID');
 7254: 		return(1,$currentphase);
 7255: 	    }
 7256: 	}
 7257:     }
 7258: 
 7259:     return (0,$currentphase+1);
 7260: }
 7261: 
 7262: 
 7263: sub scantron_get_correction {
 7264:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 7265: #FIXME in the case of a duplicated ID the previous line, probably need
 7266: #to show both the current line and the previous one and allow skipping
 7267: #the previous one or the current one
 7268: 
 7269:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7270:         $r->print(
 7271:             '<p class="LC_warning">'
 7272:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7273:                 "<b>$error</b>",
 7274:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7275:            ."</p> \n");
 7276:     } else {
 7277:         $r->print(
 7278:             '<p class="LC_warning">'
 7279:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7280:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7281:            ."</p> \n");
 7282:     }
 7283:     my $message =
 7284:         '<p>'
 7285:        .&mt('The ID on the form is [_1]',
 7286:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7287:        .'<br />'
 7288:        .&mt('The name on the paper is [_1], [_2]',
 7289:             $$scan_record{'scantron.LastName'},
 7290:             $$scan_record{'scantron.FirstName'})
 7291:        .'</p>';
 7292: 
 7293:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7294:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7295:                            # Array populated for doublebubble or
 7296:     my @lines_to_correct;  # missingbubble errors to build javascript
 7297:                            # to validate radio button checking   
 7298: 
 7299:     if ($error =~ /ID$/) {
 7300: 	if ($error eq 'incorrectID') {
 7301: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7302: 		      "</p>\n");
 7303: 	} elsif ($error eq 'duplicateID') {
 7304: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7305: 	}
 7306: 	$r->print($message);
 7307: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7308: 	$r->print("\n<ul><li> ");
 7309: 	#FIXME it would be nice if this sent back the user ID and
 7310: 	#could do partial userID matches
 7311: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7312: 				       'scantron_username','scantron_domain'));
 7313: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7314: 	$r->print("\n@".
 7315: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7316: 
 7317: 	$r->print('</li>');
 7318:     } elsif ($error =~ /CODE$/) {
 7319: 	if ($error eq 'incorrectCODE') {
 7320: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7321: 	} elsif ($error eq 'duplicateCODE') {
 7322: 	    $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");
 7323: 	}
 7324:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7325:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7326:                  ."</p>\n");
 7327: 	$r->print($message);
 7328: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7329: 	$r->print("\n<br /> ");
 7330: 	my $i=0;
 7331: 	if ($error eq 'incorrectCODE' 
 7332: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7333: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7334: 	    if ($closest > 0) {
 7335: 		foreach my $testcode (@{$closest}) {
 7336: 		    my $checked='';
 7337: 		    if (!$i) { $checked=' checked="checked"'; }
 7338: 		    $r->print("
 7339:    <label>
 7340:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7341:        ".&mt("Use the similar CODE [_1] instead.",
 7342: 	    "<b><tt>".$testcode."</tt></b>")."
 7343:     </label>
 7344:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7345: 		    $r->print("\n<br />");
 7346: 		    $i++;
 7347: 		}
 7348: 	    }
 7349: 	}
 7350: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7351: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7352: 	    $r->print("
 7353:     <label>
 7354:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7355:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7356: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7357:     </label>");
 7358: 	    $r->print("\n<br />");
 7359: 	}
 7360: 
 7361: 	$r->print(<<ENDSCRIPT);
 7362: <script type="text/javascript">
 7363: function change_radio(field) {
 7364:     var slct=document.scantronupload.scantron_CODE_resolution;
 7365:     var i;
 7366:     for (i=0;i<slct.length;i++) {
 7367:         if (slct[i].value==field) { slct[i].checked=true; }
 7368:     }
 7369: }
 7370: </script>
 7371: ENDSCRIPT
 7372: 	my $href="/adm/pickcode?".
 7373: 	   "form=".&escape("scantronupload").
 7374: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7375: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7376: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7377: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7378: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7379: 	    $r->print("
 7380:     <label>
 7381:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7382:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7383: 	     "<a target='_blank' href='$href'>","</a>")."
 7384:     </label> 
 7385:     ".&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\')" />'));
 7386: 	    $r->print("\n<br />");
 7387: 	}
 7388: 	$r->print("
 7389:     <label>
 7390:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7391:        ".&mt("Use [_1] as the CODE.",
 7392: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7393: 	$r->print("\n<br /><br />");
 7394:     } elsif ($error eq 'doublebubble') {
 7395: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7396: 
 7397: 	# The form field scantron_questions is acutally a list of line numbers.
 7398: 	# represented by this form so:
 7399: 
 7400: 	my $line_list = &questions_to_line_list($arg);
 7401: 
 7402: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7403: 		  $line_list.'" />');
 7404: 	$r->print($message);
 7405: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7406: 	foreach my $question (@{$arg}) {
 7407: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7408:                                                    $scan_record, $error);
 7409:             push(@lines_to_correct,@linenums);
 7410: 	}
 7411:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7412:     } elsif ($error eq 'missingbubble') {
 7413: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7414: 	$r->print($message);
 7415: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7416: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7417: 
 7418: 	# The form field scantron_questions is actually a list of line numbers not
 7419: 	# a list of question numbers. Therefore:
 7420: 	#
 7421: 	
 7422: 	my $line_list = &questions_to_line_list($arg);
 7423: 
 7424: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7425: 		  $line_list.'" />');
 7426: 	foreach my $question (@{$arg}) {
 7427: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7428:                                                    $scan_record, $error);
 7429:             push(@lines_to_correct,@linenums);
 7430: 	}
 7431:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7432:     } else {
 7433: 	$r->print("\n<ul>");
 7434:     }
 7435:     $r->print("\n</li></ul>");
 7436: }
 7437: 
 7438: sub verify_bubbles_checked {
 7439:     my (@ansnums) = @_;
 7440:     my $ansnumstr = join('","',@ansnums);
 7441:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7442:     my $output = (<<ENDSCRIPT);
 7443: <script type="text/javascript">
 7444: function verify_bubble_radio(form) {
 7445:     var ansnumArray = new Array ("$ansnumstr");
 7446:     var need_bubble_count = 0;
 7447:     for (var i=0; i<ansnumArray.length; i++) {
 7448:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7449:             var bubble_picked = 0; 
 7450:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7451:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7452:                     bubble_picked = 1;
 7453:                 }
 7454:             }
 7455:             if (bubble_picked == 0) {
 7456:                 need_bubble_count ++;
 7457:             }
 7458:         }
 7459:     }
 7460:     if (need_bubble_count) {
 7461:         alert("$warning");
 7462:         return;
 7463:     }
 7464:     form.submit(); 
 7465: }
 7466: </script>
 7467: ENDSCRIPT
 7468:     return $output;
 7469: }
 7470: 
 7471: =pod
 7472: 
 7473: =item  questions_to_line_list
 7474: 
 7475: Converts a list of questions into a string of comma separated
 7476: line numbers in the answer sheet used by the questions.  This is
 7477: used to fill in the scantron_questions form field.
 7478: 
 7479:   Arguments:
 7480:      questions    - Reference to an array of questions.
 7481: 
 7482: =cut
 7483: 
 7484: 
 7485: sub questions_to_line_list {
 7486:     my ($questions) = @_;
 7487:     my @lines;
 7488: 
 7489:     foreach my $item (@{$questions}) {
 7490:         my $question = $item;
 7491:         my ($first,$count,$last);
 7492:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7493:             $question = $1;
 7494:             my $subquestion = $2;
 7495:             $first = $first_bubble_line{$question-1} + 1;
 7496:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7497:             my $subcount = 1;
 7498:             while ($subcount<$subquestion) {
 7499:                 $first += $subans[$subcount-1];
 7500:                 $subcount ++;
 7501:             }
 7502:             $count = $subans[$subquestion-1];
 7503:         } else {
 7504: 	    $first   = $first_bubble_line{$question-1} + 1;
 7505: 	    $count   = $bubble_lines_per_response{$question-1};
 7506:         }
 7507:         $last = $first+$count-1;
 7508:         push(@lines, ($first..$last));
 7509:     }
 7510:     return join(',', @lines);
 7511: }
 7512: 
 7513: =pod 
 7514: 
 7515: =item prompt_for_corrections
 7516: 
 7517: Prompts for a potentially multiline correction to the
 7518: user's bubbling (factors out common code from scantron_get_correction
 7519: for multi and missing bubble cases).
 7520: 
 7521:  Arguments:
 7522:    $r           - Apache request object.
 7523:    $question    - The question number to prompt for.
 7524:    $scan_config - The scantron file configuration hash.
 7525:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7526:    $error       - Type of error
 7527: 
 7528:  Implicit inputs:
 7529:    %bubble_lines_per_response   - Starting line numbers for each question.
 7530:                                   Numbered from 0 (but question numbers are from
 7531:                                   1.
 7532:    %first_bubble_line           - Starting bubble line for each question.
 7533:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7534:                                   type problems render as separate sub-questions, 
 7535:                                   in exam mode. This hash contains a 
 7536:                                   comma-separated list of the lines per 
 7537:                                   sub-question.
 7538:    %responsetype_per_response   - essayresponse, formularesponse,
 7539:                                   stringresponse, imageresponse, reactionresponse,
 7540:                                   and organicresponse type problem parts can have
 7541:                                   multiple lines per response if the weight
 7542:                                   assigned exceeds 10.  In this case, only
 7543:                                   one bubble per line is permitted, but more 
 7544:                                   than one line might contain bubbles, e.g.
 7545:                                   bubbling of: line 1 - J, line 2 - J, 
 7546:                                   line 3 - B would assign 22 points.  
 7547: 
 7548: =cut
 7549: 
 7550: sub prompt_for_corrections {
 7551:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7552:     my ($current_line,$lines);
 7553:     my @linenums;
 7554:     my $questionnum = $question;
 7555:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7556:         $question = $1;
 7557:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7558:         my $subquestion = $2;
 7559:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7560:         my $subcount = 1;
 7561:         while ($subcount<$subquestion) {
 7562:             $current_line += $subans[$subcount-1];
 7563:             $subcount ++;
 7564:         }
 7565:         $lines = $subans[$subquestion-1];
 7566:     } else {
 7567:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7568:         $lines        = $bubble_lines_per_response{$question-1};
 7569:     }
 7570:     if ($lines > 1) {
 7571:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7572:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7573:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7574:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7575:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7576:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7577:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7578:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 7579:         } else {
 7580:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7581:         }
 7582:     }
 7583:     for (my $i =0; $i < $lines; $i++) {
 7584:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7585: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7586: 	        		  $questionnum,$error,split('', $selected));
 7587:         push(@linenums,$current_line);
 7588: 	$current_line++;
 7589:     }
 7590:     if ($lines > 1) {
 7591: 	$r->print("<hr /><br />");
 7592:     }
 7593:     return @linenums;
 7594: }
 7595: 
 7596: =pod
 7597: 
 7598: =item scantron_bubble_selector
 7599:   
 7600:    Generates the html radiobuttons to correct a single bubble line
 7601:    possibly showing the existing the selected bubbles if known
 7602: 
 7603:  Arguments:
 7604:     $r           - Apache request object
 7605:     $scan_config - hash from &get_scantron_config()
 7606:     $line        - Number of the line being displayed.
 7607:     $questionnum - Question number (may include subquestion)
 7608:     $error       - Type of error.
 7609:     @selected    - Array of bubbles picked on this line.
 7610: 
 7611: =cut
 7612: 
 7613: sub scantron_bubble_selector {
 7614:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7615:     my $max=$$scan_config{'Qlength'};
 7616: 
 7617:     my $scmode=$$scan_config{'Qon'};
 7618:     if ($scmode eq 'number' || $scmode eq 'letter') {
 7619:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7620:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7621:             $max=$$scan_config{'BubblesPerRow'};
 7622:             if (($scmode eq 'number') && ($max > 10)) {
 7623:                 $max = 10;
 7624:             } elsif (($scmode eq 'letter') && $max > 26) {
 7625:                 $max = 26;
 7626:             }
 7627:         } else {
 7628:             $max = 10;
 7629:         }
 7630:     }
 7631: 
 7632:     my @alphabet=('A'..'Z');
 7633:     $r->print(&Apache::loncommon::start_data_table().
 7634:               &Apache::loncommon::start_data_table_row());
 7635:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7636:     for (my $i=0;$i<$max+1;$i++) {
 7637: 	$r->print("\n".'<td align="center">');
 7638: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7639: 	else { $r->print('&nbsp;'); }
 7640: 	$r->print('</td>');
 7641:     }
 7642:     $r->print(&Apache::loncommon::end_data_table_row().
 7643:               &Apache::loncommon::start_data_table_row());
 7644:     for (my $i=0;$i<$max;$i++) {
 7645: 	$r->print("\n".
 7646: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7647: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7648:     }
 7649:     my $nobub_checked = ' ';
 7650:     if ($error eq 'missingbubble') {
 7651:         $nobub_checked = ' checked = "checked" ';
 7652:     }
 7653:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7654: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7655:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7656:               $line.'" value="'.$questionnum.'" /></td>');
 7657:     $r->print(&Apache::loncommon::end_data_table_row().
 7658:               &Apache::loncommon::end_data_table());
 7659: }
 7660: 
 7661: =pod
 7662: 
 7663: =item num_matches
 7664: 
 7665:    Counts the number of characters that are the same between the two arguments.
 7666: 
 7667:  Arguments:
 7668:    $orig - CODE from the scanline
 7669:    $code - CODE to match against
 7670: 
 7671:  Returns:
 7672:    $count - integer count of the number of same characters between the
 7673:             two arguments
 7674: 
 7675: =cut
 7676: 
 7677: sub num_matches {
 7678:     my ($orig,$code) = @_;
 7679:     my @code=split(//,$code);
 7680:     my @orig=split(//,$orig);
 7681:     my $same=0;
 7682:     for (my $i=0;$i<scalar(@code);$i++) {
 7683: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7684:     }
 7685:     return $same;
 7686: }
 7687: 
 7688: =pod
 7689: 
 7690: =item scantron_get_closely_matching_CODEs
 7691: 
 7692:    Cycles through all CODEs and finds the set that has the greatest
 7693:    number of same characters as the provided CODE
 7694: 
 7695:  Arguments:
 7696:    $allcodes - hash ref returned by &get_codes()
 7697:    $CODE     - CODE from the current scanline
 7698: 
 7699:  Returns:
 7700:    2 element list
 7701:     - first elements is number of how closely matching the best fit is 
 7702:       (5 means best set has 5 matching characters)
 7703:     - second element is an arrary ref containing the set of valid CODEs
 7704:       that best fit the passed in CODE
 7705: 
 7706: =cut
 7707: 
 7708: sub scantron_get_closely_matching_CODEs {
 7709:     my ($allcodes,$CODE)=@_;
 7710:     my @CODEs;
 7711:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7712: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7713:     }
 7714: 
 7715:     return ($#CODEs,$CODEs[-1]);
 7716: }
 7717: 
 7718: =pod
 7719: 
 7720: =item get_codes
 7721: 
 7722:    Builds a hash which has keys of all of the valid CODEs from the selected
 7723:    set of remembered CODEs.
 7724: 
 7725:  Arguments:
 7726:   $old_name - name of the set of remembered CODEs
 7727:   $cdom     - domain of the course
 7728:   $cnum     - internal course name
 7729: 
 7730:  Returns:
 7731:   %allcodes - keys are the valid CODEs, values are all 1
 7732: 
 7733: =cut
 7734: 
 7735: sub get_codes {
 7736:     my ($old_name, $cdom, $cnum) = @_;
 7737:     if (!$old_name) {
 7738: 	$old_name=$env{'form.scantron_CODElist'};
 7739:     }
 7740:     if (!$cdom) {
 7741: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7742:     }
 7743:     if (!$cnum) {
 7744: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7745:     }
 7746:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7747: 				    $cdom,$cnum);
 7748:     my %allcodes;
 7749:     if ($result{"type\0$old_name"} eq 'number') {
 7750: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7751:     } else {
 7752: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7753:     }
 7754:     return %allcodes;
 7755: }
 7756: 
 7757: =pod
 7758: 
 7759: =item scantron_validate_CODE
 7760: 
 7761:    Validates all scanlines in the selected file to not have any
 7762:    invalid or underspecified CODEs and that none of the codes are
 7763:    duplicated if this was requested.
 7764: 
 7765: =cut
 7766: 
 7767: sub scantron_validate_CODE {
 7768:     my ($r,$currentphase) = @_;
 7769:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7770:     if ($scantron_config{'CODElocation'} &&
 7771: 	$scantron_config{'CODEstart'} &&
 7772: 	$scantron_config{'CODElength'}) {
 7773: 	if (!defined($env{'form.scantron_CODElist'})) {
 7774: 	    &FIXME_blow_up()
 7775: 	}
 7776:     } else {
 7777: 	return (0,$currentphase+1);
 7778:     }
 7779:     
 7780:     my %usedCODEs;
 7781: 
 7782:     my %allcodes=&get_codes();
 7783: 
 7784:     my $nav_error;
 7785:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7786:     if ($nav_error) {
 7787:         $r->print(&navmap_errormsg());
 7788:         return(1,$currentphase);
 7789:     }
 7790: 
 7791:     my ($scanlines,$scan_data)=&scantron_getfile();
 7792:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7793: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7794: 	if ($line=~/^[\s\cz]*$/) { next; }
 7795: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7796: 						 $scan_data);
 7797: 	my $CODE=$$scan_record{'scantron.CODE'};
 7798: 	my $error=0;
 7799: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7800: 	    &scantron_get_correction($r,$i,$scan_record,
 7801: 				     \%scantron_config,
 7802: 				     $line,'incorrectCODE',\%allcodes);
 7803: 	    return(1,$currentphase);
 7804: 	}
 7805: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7806: 	    && !$$scan_record{'scantron.useCODE'}) {
 7807: 	    &scantron_get_correction($r,$i,$scan_record,
 7808: 				     \%scantron_config,
 7809: 				     $line,'incorrectCODE',\%allcodes);
 7810: 	    return(1,$currentphase);
 7811: 	}
 7812: 	if (exists($usedCODEs{$CODE}) 
 7813: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7814: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7815: 	    &scantron_get_correction($r,$i,$scan_record,
 7816: 				     \%scantron_config,
 7817: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7818: 	    return(1,$currentphase);
 7819: 	}
 7820: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7821:     }
 7822:     return (0,$currentphase+1);
 7823: }
 7824: 
 7825: =pod
 7826: 
 7827: =item scantron_validate_doublebubble
 7828: 
 7829:    Validates all scanlines in the selected file to not have any
 7830:    bubble lines with multiple bubbles marked.
 7831: 
 7832: =cut
 7833: 
 7834: sub scantron_validate_doublebubble {
 7835:     my ($r,$currentphase) = @_;
 7836:     #get student info
 7837:     my $classlist=&Apache::loncoursedata::get_classlist();
 7838:     my %idmap=&username_to_idmap($classlist);
 7839: 
 7840:     #get scantron line setup
 7841:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7842:     my ($scanlines,$scan_data)=&scantron_getfile();
 7843:     my $nav_error;
 7844:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7845:     if ($nav_error) {
 7846:         $r->print(&navmap_errormsg());
 7847:         return(1,$currentphase);
 7848:     }
 7849: 
 7850:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7851: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7852: 	if ($line=~/^[\s\cz]*$/) { next; }
 7853: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7854: 						 $scan_data);
 7855: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7856: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7857: 				 'doublebubble',
 7858: 				 $$scan_record{'scantron.doubleerror'});
 7859:     	return (1,$currentphase);
 7860:     }
 7861:     return (0,$currentphase+1);
 7862: }
 7863: 
 7864: 
 7865: sub scantron_get_maxbubble {
 7866:     my ($nav_error,$scantron_config) = @_;
 7867:     if (defined($env{'form.scantron_maxbubble'}) &&
 7868: 	$env{'form.scantron_maxbubble'}) {
 7869: 	&restore_bubble_lines();
 7870: 	return $env{'form.scantron_maxbubble'};
 7871:     }
 7872: 
 7873:     my (undef, undef, $sequence) =
 7874: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7875: 
 7876:     my $navmap=Apache::lonnavmaps::navmap->new();
 7877:     unless (ref($navmap)) {
 7878:         if (ref($nav_error)) {
 7879:             $$nav_error = 1;
 7880:         }
 7881:         return;
 7882:     }
 7883:     my $map=$navmap->getResourceByUrl($sequence);
 7884:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7885:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7886: 
 7887:     &Apache::lonxml::clear_problem_counter();
 7888: 
 7889:     my $uname       = $env{'user.name'};
 7890:     my $udom        = $env{'user.domain'};
 7891:     my $cid         = $env{'request.course.id'};
 7892:     my $total_lines = 0;
 7893:     %bubble_lines_per_response = ();
 7894:     %first_bubble_line         = ();
 7895:     %subdivided_bubble_lines   = ();
 7896:     %responsetype_per_response = ();
 7897: 
 7898:     my $response_number = 0;
 7899:     my $bubble_line     = 0;
 7900:     foreach my $resource (@resources) {
 7901:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 7902:                                                           $udom,$bubbles_per_row);
 7903:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7904: 	    foreach my $part_id (@{$parts}) {
 7905:                 my $lines;
 7906: 
 7907: 	        # TODO - make this a persistent hash not an array.
 7908: 
 7909:                 # optionresponse, matchresponse and rankresponse type items 
 7910:                 # render as separate sub-questions in exam mode.
 7911:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7912:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7913:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7914:                     my ($numbub,$numshown);
 7915:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7916:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7917:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7918:                         }
 7919:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7920:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7921:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7922:                         }
 7923:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7924:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7925:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7926:                         }
 7927:                     }
 7928:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7929:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7930:                     }
 7931:                     my $bubbles_per_row =
 7932:                         &bubblesheet_bubbles_per_row($scantron_config);
 7933:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 7934:                     if (($numbub % $bubbles_per_row) != 0) {
 7935:                         $inner_bubble_lines++;
 7936:                     }
 7937:                     for (my $i=0; $i<$numshown; $i++) {
 7938:                         $subdivided_bubble_lines{$response_number} .= 
 7939:                             $inner_bubble_lines.',';
 7940:                     }
 7941:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7942:                     $lines = $numshown * $inner_bubble_lines;
 7943:                 } else {
 7944:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7945:                 }
 7946: 
 7947:                 $first_bubble_line{$response_number} = $bubble_line;
 7948: 	        $bubble_lines_per_response{$response_number} = $lines;
 7949:                 $responsetype_per_response{$response_number} = 
 7950:                     $analysis->{$part_id.'.type'};
 7951: 	        $response_number++;
 7952: 
 7953: 	        $bubble_line +=  $lines;
 7954: 	        $total_lines +=  $lines;
 7955: 	    }
 7956:         }
 7957:     }
 7958:     &Apache::lonnet::delenv('scantron.');
 7959: 
 7960:     &save_bubble_lines();
 7961:     $env{'form.scantron_maxbubble'} =
 7962: 	$total_lines;
 7963:     return $env{'form.scantron_maxbubble'};
 7964: }
 7965: 
 7966: sub bubblesheet_bubbles_per_row {
 7967:     my ($scantron_config) = @_;
 7968:     my $bubbles_per_row;
 7969:     if (ref($scantron_config) eq 'HASH') {
 7970:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 7971:     }
 7972:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 7973:         $bubbles_per_row = 10;
 7974:     }
 7975:     return $bubbles_per_row;
 7976: }
 7977: 
 7978: sub scantron_validate_missingbubbles {
 7979:     my ($r,$currentphase) = @_;
 7980:     #get student info
 7981:     my $classlist=&Apache::loncoursedata::get_classlist();
 7982:     my %idmap=&username_to_idmap($classlist);
 7983: 
 7984:     #get scantron line setup
 7985:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7986:     my ($scanlines,$scan_data)=&scantron_getfile();
 7987:     my $nav_error;
 7988:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7989:     if ($nav_error) {
 7990:         return(1,$currentphase);
 7991:     }
 7992:     if (!$max_bubble) { $max_bubble=2**31; }
 7993:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7994: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7995: 	if ($line=~/^[\s\cz]*$/) { next; }
 7996: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7997: 						 $scan_data);
 7998: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7999: 	my @to_correct;
 8000: 	
 8001: 	# Probably here's where the error is...
 8002: 
 8003: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8004:             my $lastbubble;
 8005:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8006:                my $question = $1;
 8007:                my $subquestion = $2;
 8008:                if (!defined($first_bubble_line{$question -1})) { next; }
 8009:                my $first = $first_bubble_line{$question-1};
 8010:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 8011:                my $subcount = 1;
 8012:                while ($subcount<$subquestion) {
 8013:                    $first += $subans[$subcount-1];
 8014:                    $subcount ++;
 8015:                }
 8016:                my $count = $subans[$subquestion-1];
 8017:                $lastbubble = $first + $count;
 8018:             } else {
 8019:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 8020:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 8021:             }
 8022:             if ($lastbubble > $max_bubble) { next; }
 8023: 	    push(@to_correct,$missing);
 8024: 	}
 8025: 	if (@to_correct) {
 8026: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8027: 				     $line,'missingbubble',\@to_correct);
 8028: 	    return (1,$currentphase);
 8029: 	}
 8030: 
 8031:     }
 8032:     return (0,$currentphase+1);
 8033: }
 8034: 
 8035: sub hand_bubble_option {
 8036:     my (undef, undef, $sequence) =
 8037:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8038:     return if ($sequence eq '');
 8039:     my $navmap = Apache::lonnavmaps::navmap->new();
 8040:     unless (ref($navmap)) {
 8041:         return;
 8042:     }
 8043:     my $needs_hand_bubbles;
 8044:     my $map=$navmap->getResourceByUrl($sequence);
 8045:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8046:     foreach my $res (@resources) {
 8047:         if (ref($res)) {
 8048:             if ($res->is_problem()) {
 8049:                 my $partlist = $res->parts();
 8050:                 foreach my $part (@{ $partlist }) {
 8051:                     my @types = $res->responseType($part);
 8052:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8053:                         $needs_hand_bubbles = 1;
 8054:                         last;
 8055:                     }
 8056:                 }
 8057:             }
 8058:         }
 8059:     }
 8060:     if ($needs_hand_bubbles) {
 8061:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8062:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8063:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8064:                &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 />').
 8065:                '<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;'.
 8066:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
 8067:     }
 8068:     return;
 8069: }
 8070: 
 8071: sub scantron_process_students {
 8072:     my ($r) = @_;
 8073: 
 8074:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8075:     my ($symb)=&get_symb($r);
 8076:     if (!$symb) {
 8077: 	return '';
 8078:     }
 8079:     my $default_form_data=&defaultFormData($symb);
 8080: 
 8081:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8082:     my $bubbles_per_row =
 8083:         &bubblesheet_bubbles_per_row(\%scantron_config);
 8084:     my ($scanlines,$scan_data)=&scantron_getfile();
 8085:     my $classlist=&Apache::loncoursedata::get_classlist();
 8086:     my %idmap=&username_to_idmap($classlist);
 8087:     my $navmap=Apache::lonnavmaps::navmap->new();
 8088:     unless (ref($navmap)) {
 8089:         $r->print(&navmap_errormsg());
 8090:         return '';
 8091:     }  
 8092:     my $map=$navmap->getResourceByUrl($sequence);
 8093:     my $randomorder;
 8094:     if (ref($map)) {
 8095:         $randomorder = $map->randomorder();
 8096:     }
 8097:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8098:     my (%grader_partids_by_symb,%grader_randomlists_by_symb,%ordered);
 8099:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8100:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8101:     my ($resource_error,%symb_to_resource,@master_seq);
 8102:     foreach my $resource (@resources) {
 8103:         my $ressymb;
 8104:         if (ref($resource)) {
 8105:             $ressymb = $resource->symb();
 8106:             push(@master_seq,$ressymb);
 8107:             $symb_to_resource{$ressymb} = $resource;
 8108:         } else {
 8109:             $resource_error = 1;
 8110:             last;
 8111:         }
 8112:         my ($analysis,$parts) =
 8113:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 8114:                                       $env{'user.name'},$env{'user.domain'},
 8115:                                       1,$bubbles_per_row);
 8116:         $grader_partids_by_symb{$ressymb} = $parts;
 8117:         if (ref($analysis) eq 'HASH') {
 8118:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8119:                 $grader_randomlists_by_symb{$ressymb} = 
 8120:                     $analysis->{'parts_withrandomlist'};
 8121:             }
 8122:         }
 8123:     }
 8124:     if ($resource_error) {
 8125:         $r->print(&navmap_errormsg());
 8126:         return '';
 8127:     }
 8128: 
 8129:     my ($uname,$udom);
 8130:     my $result= <<SCANTRONFORM;
 8131: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8132:   <input type="hidden" name="command" value="scantron_configphase" />
 8133:   $default_form_data
 8134: SCANTRONFORM
 8135:     $r->print($result);
 8136: 
 8137:     my @delayqueue;
 8138:     my (%completedstudents,%scandata);
 8139:     
 8140:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8141:     my $count=&get_todo_count($scanlines,$scan_data);
 8142:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8143:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8144: 					  'Processing first student');
 8145:     $r->print('<br />');
 8146:     my $start=&Time::HiRes::time();
 8147:     my $i=-1;
 8148:     my $started;
 8149: 
 8150:     my $nav_error;
 8151:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8152:     if ($nav_error) {
 8153:         $r->print(&navmap_errormsg());
 8154:         return '';
 8155:     }
 8156: 
 8157:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8158:     # the user and return.
 8159: 
 8160:     if ($ssi_error) {
 8161: 	$r->print("</form>");
 8162: 	&ssi_print_error($r);
 8163: 	$r->print(&show_grading_menu_form($symb));
 8164:         &Apache::lonnet::remove_lock($lock);
 8165: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8166:     }
 8167: 
 8168:     my %lettdig = &letter_to_digits();
 8169:     my $numletts = scalar(keys(%lettdig));
 8170: 
 8171:     while ($i<$scanlines->{'count'}) {
 8172:  	($uname,$udom)=('','');
 8173:  	$i++;
 8174:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8175:  	if ($line=~/^[\s\cz]*$/) { next; }
 8176: 	if ($started) {
 8177: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8178: 						     'last student');
 8179: 	}
 8180: 	$started=1;
 8181:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8182:  						 $scan_data);
 8183:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8184:  					      \%idmap,$i)) {
 8185:   	    &scantron_add_delay(\@delayqueue,$line,
 8186:  				'Unable to find a student that matches',1);
 8187:  	    next;
 8188:   	}
 8189:  	if (exists $completedstudents{$uname}) {
 8190:  	    &scantron_add_delay(\@delayqueue,$line,
 8191:  				'Student '.$uname.' has multiple sheets',2);
 8192:  	    next;
 8193:  	}
 8194:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8195:         my $user = $uname.':'.$usec;
 8196:   	($uname,$udom)=split(/:/,$uname);
 8197: 
 8198:         my $scancode;
 8199:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8200:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8201:             $scancode = $scan_record->{'scantron.CODE'};
 8202:         } else {
 8203:             $scancode = '';
 8204:         }
 8205: 
 8206:         my @mapresources = @resources;
 8207:         if ($randomorder) {
 8208:             @mapresources =
 8209:                 &users_order($user,$scancode,$sequence,\@master_seq,\%ordered,
 8210:                              \%symb_to_resource);
 8211:         }
 8212:         my (%partids_by_symb,$res_error);
 8213:         foreach my $resource (@mapresources) {
 8214:             my $ressymb;
 8215:             if (ref($resource)) {
 8216:                 $ressymb = $resource->symb();
 8217:             } else {
 8218:                 $res_error = 1;
 8219:                 last;
 8220:             }
 8221:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8222:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8223:                 my ($analysis,$parts) =
 8224:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8225:                                               $uname,$udom,undef,$bubbles_per_row);
 8226:                 $partids_by_symb{$ressymb} = $parts;
 8227:             } else {
 8228:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8229:             }
 8230:         }
 8231: 
 8232:         if ($res_error) {
 8233:             &scantron_add_delay(\@delayqueue,$line,
 8234:                                 'An error occurred while grading student '.$uname,2);
 8235:             next;
 8236:         }
 8237: 
 8238: 	&Apache::lonxml::clear_problem_counter();
 8239:   	&Apache::lonnet::appenv($scan_record);
 8240: 
 8241: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8242: 	    &scantron_putfile($scanlines,$scan_data);
 8243: 	}
 8244: 	
 8245:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8246:                                    \@mapresources,\%partids_by_symb,
 8247:                                    $bubbles_per_row) eq 'ssi_error') {
 8248:             $ssi_error = 0; # So end of handler error message does not trigger.
 8249:             $r->print("</form>");
 8250:             &ssi_print_error($r);
 8251:             $r->print(&show_grading_menu_form($symb));
 8252:             &Apache::lonnet::remove_lock($lock);
 8253:             return '';      # Why return ''?  Beats me.
 8254:         }
 8255: 
 8256: 	$completedstudents{$uname}={'line'=>$line};
 8257:         if ($env{'form.verifyrecord'}) {
 8258:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8259:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8260:             chomp($studentdata);
 8261:             $studentdata =~ s/\r$//;
 8262:             my $studentrecord = '';
 8263:             my $counter = -1;
 8264:             foreach my $resource (@mapresources) {
 8265:                 my $ressymb = $resource->symb();
 8266:                 ($counter,my $recording) =
 8267:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8268:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8269:                                              \%scantron_config,\%lettdig,$numletts);
 8270:                 $studentrecord .= $recording;
 8271:             }
 8272:             if ($studentrecord ne $studentdata) {
 8273:                 &Apache::lonxml::clear_problem_counter();
 8274:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8275:                                            \@mapresources,\%partids_by_symb,
 8276:                                            $bubbles_per_row) eq 'ssi_error') {
 8277:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8278:                     $r->print("</form>");
 8279:                     &ssi_print_error($r);
 8280:                     $r->print(&show_grading_menu_form($symb));
 8281:                     &Apache::lonnet::remove_lock($lock);
 8282:                     delete($completedstudents{$uname});
 8283:                     return '';
 8284:                 }
 8285:                 $counter = -1;
 8286:                 $studentrecord = '';
 8287:                 foreach my $resource (@mapresources) {
 8288:                     my $ressymb = $resource->symb();
 8289:                     ($counter,my $recording) =
 8290:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8291:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8292:                                                  \%scantron_config,\%lettdig,$numletts);
 8293:                     $studentrecord .= $recording;
 8294:                 }
 8295:                 if ($studentrecord ne $studentdata) {
 8296:                     $r->print('<p><span class="LC_warning">');
 8297:                     if ($scancode eq '') {
 8298:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8299:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8300:                     } else {
 8301:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8302:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8303:                     }
 8304:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8305:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8306:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8307:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8308:                               &Apache::loncommon::start_data_table_row().
 8309:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8310:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 8311:                               &Apache::loncommon::end_data_table_row().
 8312:                               &Apache::loncommon::start_data_table_row().
 8313:                               '<td>'.&mt('Stored submissions').'</td>'.
 8314:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 8315:                               &Apache::loncommon::end_data_table_row().
 8316:                               &Apache::loncommon::end_data_table().'</p>');
 8317:                 } else {
 8318:                     $r->print('<br /><span class="LC_warning">'.
 8319:                              &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 />'.
 8320:                              &mt("As a consequence, this user's submission history records two tries.").
 8321:                                  '</span><br />');
 8322:                 }
 8323:             }
 8324:         }
 8325:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8326:     } continue {
 8327: 	&Apache::lonxml::clear_problem_counter();
 8328: 	&Apache::lonnet::delenv('scantron.');
 8329:     }
 8330:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8331:     &Apache::lonnet::remove_lock($lock);
 8332: #    my $lasttime = &Time::HiRes::time()-$start;
 8333: #    $r->print("<p>took $lasttime</p>");
 8334: 
 8335:     $r->print("</form>");
 8336:     $r->print(&show_grading_menu_form($symb));
 8337:     return '';
 8338: }
 8339: 
 8340: sub graders_resources_pass {
 8341:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8342:         $bubbles_per_row) = @_;
 8343:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8344:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8345:         foreach my $resource (@{$resources}) {
 8346:             my $ressymb = $resource->symb();
 8347:             my ($analysis,$parts) =
 8348:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8349:                                           $env{'user.name'},$env{'user.domain'},
 8350:                                           1,$bubbles_per_row);
 8351:             $grader_partids_by_symb->{$ressymb} = $parts;
 8352:             if (ref($analysis) eq 'HASH') {
 8353:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8354:                     $grader_randomlists_by_symb->{$ressymb} =
 8355:                         $analysis->{'parts_withrandomlist'};
 8356:                 }
 8357:             }
 8358:         }
 8359:     }
 8360:     return;
 8361: }
 8362: 
 8363: =pod
 8364: 
 8365: =item users_order
 8366: 
 8367:   Returns array of resources in current map, ordered based on either CODE,
 8368:   if this is a CODEd exam, or based on student's identity if this is a
 8369:   "NAMEd" exam.
 8370: 
 8371:   Should be used when randomorder applied when the corresponding exam was
 8372:   printed, prior to students completing bubblesheets for the version of the
 8373:   exam the student received.
 8374: 
 8375: =cut
 8376: 
 8377: sub users_order  {
 8378:     my ($user,$scancode,$mapurl,$master_seq,$ordered,$symb_to_resource) = @_;
 8379:     my @mapresources;
 8380:     unless ((ref($ordered) eq 'HASH') && (ref($symb_to_resource) eq 'HASH')) {
 8381:         return @mapresources;
 8382:     }
 8383:     if (($scancode) && (ref($ordered->{$scancode}) eq 'ARRAY')) {
 8384:         @mapresources = @{$ordered->{$scancode}};
 8385:     } elsif ($scancode) {
 8386:         $env{'form.CODE'} = $scancode;
 8387:         my $actual_seq =
 8388:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8389:                                                            $master_seq,
 8390:                                                            $user,$scancode);
 8391:         if (ref($actual_seq) eq 'ARRAY') {
 8392:             @{$ordered->{$scancode}} =
 8393:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8394:             @mapresources = @{$ordered->{$scancode}};
 8395:         }
 8396:         delete($env{'form.CODE'});
 8397:     } else {
 8398:         my $actual_seq =
 8399:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8400:                                                            $master_seq,
 8401:                                                            $user);
 8402:         if (ref($actual_seq) eq 'ARRAY') {
 8403:             @mapresources =
 8404:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8405:         }
 8406:      }
 8407:      return @mapresources;
 8408: }
 8409: 
 8410: sub grade_student_bubbles {
 8411:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
 8412:     if (ref($resources) eq 'ARRAY') {
 8413:         my $count = 0;
 8414:         foreach my $resource (@{$resources}) {
 8415:             my $ressymb = $resource->symb();
 8416:             my %form = ('submitted'      => 'scantron',
 8417:                         'grade_target'   => 'grade',
 8418:                         'grade_username' => $uname,
 8419:                         'grade_domain'   => $udom,
 8420:                         'grade_courseid' => $env{'request.course.id'},
 8421:                         'grade_symb'     => $ressymb,
 8422:                         'CODE'           => $scancode
 8423:                        );
 8424:             if ($bubbles_per_row ne '') {
 8425:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8426:             }
 8427:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8428:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8429:             }
 8430:             if (ref($parts) eq 'HASH') {
 8431:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8432:                     foreach my $part (@{$parts->{$ressymb}}) {
 8433:                         $form{'scantron_questnum_start.'.$part} =
 8434:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 8435:                         $count++;
 8436:                     }
 8437:                 }
 8438:             }
 8439:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8440:             return 'ssi_error' if ($ssi_error);
 8441:             last if (&Apache::loncommon::connection_aborted($r));
 8442:         }
 8443:     }
 8444:     return;
 8445: }
 8446: 
 8447: sub scantron_upload_scantron_data {
 8448:     my ($r)=@_;
 8449:     my $dom = $env{'request.role.domain'};
 8450:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8451:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8452:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8453: 							  'domainid',
 8454: 							  'coursename',$dom);
 8455:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8456:                        ('&nbsp'x2).&mt('(shows course personnel)');
 8457:     my ($symb) = &get_symb($r,1);
 8458:     my $default_form_data=&defaultFormData($symb);
 8459:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8460:     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.");
 8461:     $r->print('
 8462: <script type="text/javascript" language="javascript">
 8463:     function checkUpload(formname) {
 8464: 	if (formname.upfile.value == "") {
 8465: 	    alert("'.$nofile_alert.'");
 8466: 	    return false;
 8467: 	}
 8468:         if (formname.courseid.value == "") {
 8469:             alert("'.$nocourseid_alert.'");
 8470:             return false;
 8471:         }
 8472: 	formname.submit();
 8473:     }
 8474: 
 8475:     function ToSyllabus() {
 8476:         var cdom = '."'$dom'".';
 8477:         var cnum = document.rules.courseid.value;
 8478:         if (cdom == "" || cdom == null) {
 8479:             return;
 8480:         }
 8481:         if (cnum == "" || cnum == null) {
 8482:            return;
 8483:         }
 8484:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8485:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8486:         return;
 8487:     }
 8488: 
 8489: </script>
 8490: 
 8491: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8492: 
 8493: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8494: '.$default_form_data.
 8495:   &Apache::lonhtmlcommon::start_pick_box().
 8496:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8497:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8498:   &Apache::lonhtmlcommon::row_closure().
 8499:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8500:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8501:   &Apache::lonhtmlcommon::row_closure().
 8502:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8503:   '<input name="domainid" type="hidden" />'.$domdesc.
 8504:   &Apache::lonhtmlcommon::row_closure().
 8505:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8506:   '<input type="file" name="upfile" size="50" />'.
 8507:   &Apache::lonhtmlcommon::row_closure(1).
 8508:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8509: 
 8510: <input name="command" value="scantronupload_save" type="hidden" />
 8511: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8512: </form>
 8513: ');
 8514:     return '';
 8515: }
 8516: 
 8517: 
 8518: sub scantron_upload_scantron_data_save {
 8519:     my($r)=@_;
 8520:     my ($symb)=&get_symb($r,1);
 8521:     my $doanotherupload=
 8522: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8523: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8524: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8525: 	'</form>'."\n";
 8526:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8527: 	!&Apache::lonnet::allowed('usc',
 8528: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8529: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8530: 	if ($symb) {
 8531: 	    $r->print(&show_grading_menu_form($symb));
 8532: 	} else {
 8533: 	    $r->print($doanotherupload);
 8534: 	}
 8535: 	return '';
 8536:     }
 8537:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8538:     my $uploadedfile;
 8539:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8540:     if (length($env{'form.upfile'}) < 2) {
 8541:         $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>'));
 8542:     } else {
 8543:         my $result = 
 8544:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8545:                                             $env{'form.courseid'},$env{'form.domainid'});
 8546: 	if ($result =~ m{^/uploaded/}) {
 8547: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8548:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8549: 			  '<span class="LC_filename">'.$result.'</span>'));
 8550:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8551:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8552:                                                        $env{'form.courseid'},$uploadedfile));
 8553: 	} else {
 8554: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8555:                           '<span class="LC_error">','</span>',$result,
 8556: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8557: 	}
 8558:     }
 8559:     if ($symb) {
 8560: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8561:     } else {
 8562: 	$r->print($doanotherupload);
 8563:     }
 8564:     return '';
 8565: }
 8566: 
 8567: sub validate_uploaded_scantron_file {
 8568:     my ($cdom,$cname,$fname) = @_;
 8569:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8570:     my @lines;
 8571:     if ($scanlines ne '-1') {
 8572:         @lines=split("\n",$scanlines,-1);
 8573:     }
 8574:     my $output;
 8575:     if (@lines) {
 8576:         my (%counts,$max_match_format);
 8577:         my ($max_match_count,$max_match_pct) = (0,0);
 8578:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8579:         my %idmap = &username_to_idmap($classlist);
 8580:         foreach my $key (keys(%idmap)) {
 8581:             my $lckey = lc($key);
 8582:             $idmap{$lckey} = $idmap{$key};
 8583:         }
 8584:         my %unique_formats;
 8585:         my @formatlines = &get_scantronformat_file();
 8586:         foreach my $line (@formatlines) {
 8587:             chomp($line);
 8588:             my @config = split(/:/,$line);
 8589:             my $idstart = $config[5];
 8590:             my $idlength = $config[6];
 8591:             if (($idstart ne '') && ($idlength > 0)) {
 8592:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8593:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8594:                 } else {
 8595:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8596:                 }
 8597:             }
 8598:         }
 8599:         foreach my $key (keys(%unique_formats)) {
 8600:             my ($idstart,$idlength) = split(':',$key);
 8601:             %{$counts{$key}} = (
 8602:                                'found'   => 0,
 8603:                                'total'   => 0,
 8604:                               );
 8605:             foreach my $line (@lines) {
 8606:                 next if ($line =~ /^#/);
 8607:                 next if ($line =~ /^[\s\cz]*$/);
 8608:                 my $id = substr($line,$idstart-1,$idlength);
 8609:                 $id = lc($id);
 8610:                 if (exists($idmap{$id})) {
 8611:                     $counts{$key}{'found'} ++;
 8612:                 }
 8613:                 $counts{$key}{'total'} ++;
 8614:             }
 8615:             if ($counts{$key}{'total'}) {
 8616:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8617:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8618:                     $max_match_pct = $percent_match;
 8619:                     $max_match_format = $key;
 8620:                     $max_match_count = $counts{$key}{'total'};
 8621:                 }
 8622:             }
 8623:         }
 8624:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8625:             my $format_descs;
 8626:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8627:             for (my $i=0; $i<$numwithformat; $i++) {
 8628:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8629:                 if ($i<$numwithformat-2) {
 8630:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8631:                 } elsif ($i==$numwithformat-2) {
 8632:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8633:                 } elsif ($i==$numwithformat-1) {
 8634:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8635:                 }
 8636:             }
 8637:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8638:             $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).
 8639:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8640:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8641:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8642:                                   '<i>'.$cdom.'</i>').'</li>'.
 8643:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8644:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8645:                        '</ul>';
 8646:         }
 8647:     } else {
 8648:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8649:     }
 8650:     return $output;
 8651: }
 8652: 
 8653: sub valid_file {
 8654:     my ($requested_file)=@_;
 8655:     foreach my $filename (sort(&scantron_filenames())) {
 8656: 	if ($requested_file eq $filename) { return 1; }
 8657:     }
 8658:     return 0;
 8659: }
 8660: 
 8661: sub scantron_download_scantron_data {
 8662:     my ($r)=@_;
 8663:     my ($symb) = &get_symb($r,1);
 8664:     my $default_form_data=&defaultFormData($symb);
 8665:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8666:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8667:     my $file=$env{'form.scantron_selectfile'};
 8668:     if (! &valid_file($file)) {
 8669: 	$r->print('
 8670: 	<p>
 8671: 	    '.&mt('The requested file name was invalid.').'
 8672:         </p>
 8673: ');
 8674: 	$r->print(&show_grading_menu_form($symb));
 8675: 	return;
 8676:     }
 8677:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8678:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8679:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8680:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8681:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8682:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8683:     $r->print('
 8684:     <p>
 8685: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8686: 	      '<a href="'.$orig.'">','</a>').'
 8687:     </p>
 8688:     <p>
 8689: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8690: 	      '<a href="'.$corrected.'">','</a>').'
 8691:     </p>
 8692:     <p>
 8693: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8694: 	      '<a href="'.$skipped.'">','</a>').'
 8695:     </p>
 8696: ');
 8697:     $r->print(&show_grading_menu_form($symb));
 8698:     return '';
 8699: }
 8700: 
 8701: sub checkscantron_results {
 8702:     my ($r) = @_;
 8703:     my ($symb)=&get_symb($r);
 8704:     if (!$symb) {return '';}
 8705:     my $grading_menu_button=&show_grading_menu_form($symb);
 8706:     my $cid = $env{'request.course.id'};
 8707:     my %lettdig = &letter_to_digits();
 8708:     my $numletts = scalar(keys(%lettdig));
 8709:     my $cnum = $env{'course.'.$cid.'.num'};
 8710:     my $cdom = $env{'course.'.$cid.'.domain'};
 8711:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8712:     my %record;
 8713:     my %scantron_config =
 8714:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8715:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8716:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8717:     my $classlist=&Apache::loncoursedata::get_classlist();
 8718:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8719:     my $navmap=Apache::lonnavmaps::navmap->new();
 8720:     unless (ref($navmap)) {
 8721:         $r->print(&navmap_errormsg());
 8722:         return '';
 8723:     }
 8724:     my $map=$navmap->getResourceByUrl($sequence);
 8725:     my ($randomorder,@master_seq,%symb_to_resource);
 8726:     if (ref($map)) {
 8727:         $randomorder=$map->randomorder();
 8728:     }
 8729:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8730:     foreach my $resource (@resources) {
 8731:         if (ref($resource)) {
 8732:             my $ressymb = $resource->symb();
 8733:             push(@master_seq,$ressymb);
 8734:             $symb_to_resource{$ressymb} = $resource;
 8735:         }
 8736:     }
 8737:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8738:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8739:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8740:     my ($uname,$udom);
 8741:     my (%scandata,%lastname,%bylast);
 8742:     $r->print('
 8743: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8744: 
 8745:     my @delayqueue;
 8746:     my %completedstudents;
 8747: 
 8748:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8749:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8750:     my ($username,$domain,$started,%ordered);
 8751:     my $nav_error;
 8752:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8753:     if ($nav_error) {
 8754:         $r->print(&navmap_errormsg());
 8755:         return '';
 8756:     }
 8757: 
 8758:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8759:                                           'Processing first student');
 8760:     my $start=&Time::HiRes::time();
 8761:     my $i=-1;
 8762: 
 8763:     while ($i<$scanlines->{'count'}) {
 8764:         ($username,$domain,$uname)=('','','');
 8765:         $i++;
 8766:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8767:         if ($line=~/^[\s\cz]*$/) { next; }
 8768:         if ($started) {
 8769:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8770:                                                      'last student');
 8771:         }
 8772:         $started=1;
 8773:         my $scan_record=
 8774:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8775:                                                      $scan_data);
 8776:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8777:                                                               \%idmap,$i)) {
 8778:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8779:                                 'Unable to find a student that matches',1);
 8780:             next;
 8781:         }
 8782:         if (exists $completedstudents{$uname}) {
 8783:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8784:                                 'Student '.$uname.' has multiple sheets',2);
 8785:             next;
 8786:         }
 8787:         my $pid = $scan_record->{'scantron.ID'};
 8788:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8789:         push(@{$bylast{$lastname{$pid}}},$pid);
 8790:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8791:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8792:         chomp($scandata{$pid});
 8793:         $scandata{$pid} =~ s/\r$//;
 8794:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8795:         my $user = $uname.':'.$usec;
 8796:         ($username,$domain)=split(/:/,$uname);
 8797: 
 8798:         my $scancode;
 8799:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8800:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8801:             $scancode = $scan_record->{'scantron.CODE'};
 8802:         } else {
 8803:             $scancode = '';
 8804:         }
 8805: 
 8806:         my @mapresources = @resources;
 8807:         if ($randomorder) {
 8808:             @mapresources =
 8809:                 &users_order($user,$scancode,$sequence,\@master_seq,\%ordered,
 8810:                              \%symb_to_resource);
 8811:         }
 8812:         my $counter = -1;
 8813:         foreach my $resource (@mapresources) {
 8814:             my $parts;
 8815:             my $ressymb = $resource->symb();
 8816:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8817:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8818:                 (my $analysis,$parts) =
 8819:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8820:                                               $username,$domain,undef,
 8821:                                               $bubbles_per_row);
 8822:             } else {
 8823:                 $parts = $grader_partids_by_symb{$ressymb};
 8824:             }
 8825:             ($counter,my $recording) =
 8826:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8827:                                          $scandata{$pid},$parts,
 8828:                                          \%scantron_config,\%lettdig,$numletts);
 8829:             $record{$pid} .= $recording;
 8830:         }
 8831:     }
 8832:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8833:     $r->print('<br />');
 8834:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8835:     $passed = 0;
 8836:     $failed = 0;
 8837:     $numstudents = 0;
 8838:     foreach my $last (sort(keys(%bylast))) {
 8839:         if (ref($bylast{$last}) eq 'ARRAY') {
 8840:             foreach my $pid (sort(@{$bylast{$last}})) {
 8841:                 my $showscandata = $scandata{$pid};
 8842:                 my $showrecord = $record{$pid};
 8843:                 $showscandata =~ s/\s/&nbsp;/g;
 8844:                 $showrecord =~ s/\s/&nbsp;/g;
 8845:                 if ($scandata{$pid} eq $record{$pid}) {
 8846:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8847:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8848: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8849: '</tr>'."\n".
 8850: '<tr class="'.$css_class.'">'."\n".
 8851: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8852:                     $passed ++;
 8853:                 } else {
 8854:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8855:                     $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".
 8856: '</tr>'."\n".
 8857: '<tr class="'.$css_class.'">'."\n".
 8858: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8859: '</tr>'."\n";
 8860:                     $failed ++;
 8861:                 }
 8862:                 $numstudents ++;
 8863:             }
 8864:         }
 8865:     }
 8866:     $r->print('<p>'.
 8867:               &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).',
 8868:                   '<b>',
 8869:                   $numstudents,
 8870:                   '</b>',
 8871:                   $env{'form.scantron_maxbubble'}).
 8872:               '</p>'
 8873:     );
 8874:     $r->print('<p>'
 8875:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 8876:              .'<br />'
 8877:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 8878:              .'</p>');
 8879:     if ($passed) {
 8880:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8881:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8882:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8883:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8884:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8885:                  $okstudents."\n".
 8886:                  &Apache::loncommon::end_data_table().'<br />');
 8887:     }
 8888:     if ($failed) {
 8889:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8890:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8891:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8892:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8893:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8894:                  $badstudents."\n".
 8895:                  &Apache::loncommon::end_data_table()).'<br />'.
 8896:                  &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.');  
 8897:     }
 8898:     $r->print('</form><br />'.$grading_menu_button);
 8899:     return;
 8900: }
 8901: 
 8902: sub verify_scantron_grading {
 8903:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8904:         $scantron_config,$lettdig,$numletts) = @_;
 8905:     my ($record,%expected,%startpos);
 8906:     return ($counter,$record) if (!ref($resource));
 8907:     return ($counter,$record) if (!$resource->is_problem());
 8908:     my $symb = $resource->symb();
 8909:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8910:     foreach my $part_id (@{$partids}) {
 8911:         $counter ++;
 8912:         $expected{$part_id} = 0;
 8913:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8914:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8915:             foreach my $item (@sub_lines) {
 8916:                 $expected{$part_id} += $item;
 8917:             }
 8918:         } else {
 8919:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8920:         }
 8921:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8922:     }
 8923:     if ($symb) {
 8924:         my %recorded;
 8925:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8926:         if ($returnhash{'version'}) {
 8927:             my %lasthash=();
 8928:             my $version;
 8929:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8930:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8931:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8932:                 }
 8933:             }
 8934:             foreach my $key (keys(%lasthash)) {
 8935:                 if ($key =~ /\.scantron$/) {
 8936:                     my $value = &unescape($lasthash{$key});
 8937:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8938:                     if ($value eq '') {
 8939:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8940:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8941:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8942:                             }
 8943:                         }
 8944:                     } else {
 8945:                         my @tocheck;
 8946:                         my @items = split(//,$value);
 8947:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8948:                             ($scantron_config->{'Qon'} eq 'number')) {
 8949:                             if (@items < $expected{$part_id}) {
 8950:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8951:                                 my @singles = split(//,$fragment);
 8952:                                 foreach my $pos (@singles) {
 8953:                                     if ($pos eq ' ') {
 8954:                                         push(@tocheck,$pos);
 8955:                                     } else {
 8956:                                         my $next = shift(@items);
 8957:                                         push(@tocheck,$next);
 8958:                                     }
 8959:                                 }
 8960:                             } else {
 8961:                                 @tocheck = @items;
 8962:                             }
 8963:                             foreach my $letter (@tocheck) {
 8964:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8965:                                     if ($letter !~ /^[A-J]$/) {
 8966:                                         $letter = $scantron_config->{'Qoff'};
 8967:                                     }
 8968:                                     $recorded{$part_id} .= $letter;
 8969:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8970:                                     my $digit;
 8971:                                     if ($letter !~ /^[A-J]$/) {
 8972:                                         $digit = $scantron_config->{'Qoff'};
 8973:                                     } else {
 8974:                                         $digit = $lettdig->{$letter};
 8975:                                     }
 8976:                                     $recorded{$part_id} .= $digit;
 8977:                                 }
 8978:                             }
 8979:                         } else {
 8980:                             @tocheck = @items;
 8981:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8982:                                 my $curr_sub = shift(@tocheck);
 8983:                                 my $digit;
 8984:                                 if ($curr_sub =~ /^[A-J]$/) {
 8985:                                     $digit = $lettdig->{$curr_sub}-1;
 8986:                                 }
 8987:                                 if ($curr_sub eq 'J') {
 8988:                                     $digit += scalar($numletts);
 8989:                                 }
 8990:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8991:                                     if ($j == $digit) {
 8992:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8993:                                     } else {
 8994:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8995:                                     }
 8996:                                 }
 8997:                             }
 8998:                         }
 8999:                     }
 9000:                 }
 9001:             }
 9002:         }
 9003:         foreach my $part_id (@{$partids}) {
 9004:             if ($recorded{$part_id} eq '') {
 9005:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9006:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9007:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9008:                     }
 9009:                 }
 9010:             }
 9011:             $record .= $recorded{$part_id};
 9012:         }
 9013:     }
 9014:     return ($counter,$record);
 9015: }
 9016: 
 9017: sub letter_to_digits { 
 9018:     my %lettdig = (
 9019:                     A => 1,
 9020:                     B => 2,
 9021:                     C => 3,
 9022:                     D => 4,
 9023:                     E => 5,
 9024:                     F => 6,
 9025:                     G => 7,
 9026:                     H => 8,
 9027:                     I => 9,
 9028:                     J => 0,
 9029:                   );
 9030:     return %lettdig;
 9031: }
 9032: 
 9033: 
 9034: #-------- end of section for handling grading scantron forms -------
 9035: #
 9036: #-------------------------------------------------------------------
 9037: 
 9038: #-------------------------- Menu interface -------------------------
 9039: #
 9040: #--- Show a Grading Menu button - Calls the next routine ---
 9041: sub show_grading_menu_form {
 9042:     my ($symb)=@_;
 9043:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9044: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9045: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9046: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9047: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9048: 	'</form>'."\n";
 9049:     return $result;
 9050: }
 9051: 
 9052: # -- Retrieve choices for grading form
 9053: sub savedState {
 9054:     my %savedState = ();
 9055:     if ($env{'form.saveState'}) {
 9056: 	foreach (split(/:/,$env{'form.saveState'})) {
 9057: 	    my ($key,$value) = split(/=/,$_,2);
 9058: 	    $savedState{$key} = $value;
 9059: 	}
 9060:     }
 9061:     return \%savedState;
 9062: }
 9063: 
 9064: #--- Href with symb and command ---
 9065: 
 9066: sub href_symb_cmd {
 9067:     my ($symb,$cmd)=@_;
 9068:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9069: }
 9070: 
 9071: sub grading_menu {
 9072:     my ($request) = @_;
 9073:     my ($symb)=&get_symb($request);
 9074:     if (!$symb) {return '';}
 9075:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9076:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9077: 
 9078:     $request->print($table);
 9079:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9080:                   'handgrade'=>$hdgrade,
 9081:                   'probTitle'=>$probTitle,
 9082:                   'command'=>'submit_options',
 9083:                   'saveState'=>"",
 9084:                   'gradingMenu'=>1,
 9085:                   'showgrading'=>"yes");
 9086:     
 9087:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9088:     
 9089:     $fields{'command'} = 'csvform';
 9090:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9091:     
 9092:     $fields{'command'} = 'processclicker';
 9093:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9094:     
 9095:     $fields{'command'} = 'scantron_selectphase';
 9096:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9097:     
 9098:     my @menu = ({	categorytitle=>'Course Grading',
 9099:             items =>[
 9100:                         {	linktext => 'Manual Grading/View Submissions',
 9101:                     		url => $url1,
 9102:                     		permission => 'F',
 9103:                     		icon => 'edit-find-replace.png',
 9104:                     		linktitle => 'Start the process of hand grading submissions.'
 9105:                         },
 9106:                 	    {	linktext => 'Upload Scores',
 9107:                     		url => $url2,
 9108:                     		permission => 'F',
 9109:                     		icon => 'uploadscores.png',
 9110:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9111:                 	    },
 9112:                 	    {	linktext => 'Process Clicker',
 9113:                     		url => $url3,
 9114:                     		permission => 'F',
 9115:                     		icon => 'addClickerInfoFile.png',
 9116:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9117:                 	    },
 9118:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9119:                     		url => $url4,
 9120:                     		permission => 'F',
 9121:                     		icon => 'stat.png',
 9122:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9123:                 	    }
 9124:                     ]
 9125:             });
 9126: 
 9127:     #$fields{'command'} = 'verify';
 9128:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9129:     #
 9130:     # Create the menu
 9131:     my $Str;
 9132:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9133:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9134:     $Str .= '<input type="hidden" name="command" value="" />'.
 9135:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9136: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9137: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9138: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9139: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9140: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9141: 
 9142:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9143:     #$menudata->{'jscript'}
 9144:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9145:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9146:         ' /> '.
 9147:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9148:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9149: 
 9150:     $Str .="</form>\n";
 9151:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9152:     $request->print(<<GRADINGMENUJS);
 9153: <script type="text/javascript" language="javascript">
 9154:     function checkChoice(formname,val,cmdx) {
 9155: 	if (val <= 2) {
 9156: 	    var cmd = radioSelection(formname.radioChoice);
 9157: 	    var cmdsave = cmd;
 9158: 	} else {
 9159: 	    cmd = cmdx;
 9160: 	    cmdsave = 'submission';
 9161: 	}
 9162: 	formname.command.value = cmd;
 9163: 	if (val < 5) formname.submit();
 9164: 	if (val == 5) {
 9165: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9166: 	        return false;
 9167: 	    } else {
 9168: 	        formname.submit();
 9169: 	    }
 9170: 	}
 9171:     }
 9172: 
 9173:     function checkReceiptNo(formname,nospace) {
 9174: 	var receiptNo = formname.receipt.value;
 9175: 	var checkOpt = false;
 9176: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9177: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9178: 	if (checkOpt) {
 9179: 	    alert("$receiptalert");
 9180: 	    formname.receipt.value = "";
 9181: 	    formname.receipt.focus();
 9182: 	    return false;
 9183: 	}
 9184: 	return true;
 9185:     }
 9186: </script>
 9187: GRADINGMENUJS
 9188:     &commonJSfunctions($request);
 9189:     return $Str;    
 9190: }
 9191: 
 9192: 
 9193: #--- Displays the submissions first page -------
 9194: sub submit_options {
 9195:     my ($request) = @_;
 9196:     my ($symb)=&get_symb($request);
 9197:     if (!$symb) {return '';}
 9198:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9199: 
 9200:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9201:     $request->print(<<GRADINGMENUJS);
 9202: <script type="text/javascript" language="javascript">
 9203:     function checkChoice(formname,val,cmdx) {
 9204: 	if (val <= 2) {
 9205: 	    var cmd = radioSelection(formname.radioChoice);
 9206: 	    var cmdsave = cmd;
 9207: 	} else {
 9208: 	    cmd = cmdx;
 9209: 	    cmdsave = 'submission';
 9210: 	}
 9211: 	formname.command.value = cmd;
 9212: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9213: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9214: 	if (val < 5) formname.submit();
 9215: 	if (val == 5) {
 9216: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9217: 	    formname.submit();
 9218: 	}
 9219: 	if (val < 7) formname.submit();
 9220:     }
 9221: 
 9222:     function checkReceiptNo(formname,nospace) {
 9223: 	var receiptNo = formname.receipt.value;
 9224: 	var checkOpt = false;
 9225: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9226: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9227: 	if (checkOpt) {
 9228: 	    alert("$receiptalert");
 9229: 	    formname.receipt.value = "";
 9230: 	    formname.receipt.focus();
 9231: 	    return false;
 9232: 	}
 9233: 	return true;
 9234:     }
 9235: </script>
 9236: GRADINGMENUJS
 9237:     &commonJSfunctions($request);
 9238:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9239:     my $result;
 9240:     my (undef,$sections) = &getclasslist('all','0');
 9241:     my $savedState = &savedState();
 9242:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9243:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9244:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9245:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9246: 
 9247:     # Preselect sections
 9248:     my $selsec="";
 9249:     if (ref($sections)) {
 9250:         foreach my $section (sort(@$sections)) {
 9251:             $selsec.='<option value="'.$section.'" '.
 9252:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9253:         }
 9254:     }
 9255: 
 9256:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9257: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9258: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9259: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9260: 	'<input type="hidden" name="command"     value="" />'."\n".
 9261: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9262: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9263: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9264: 
 9265:     $result.='
 9266: <h2>
 9267:   '.&mt('Grade Current Resource').'
 9268: </h2>
 9269: <div>
 9270:   '.$table.'
 9271: </div>
 9272: 
 9273: <div class="LC_columnSection">
 9274:   
 9275:     <fieldset>
 9276:       <legend>
 9277:        '.&mt('Sections').'
 9278:       </legend>
 9279:       <select name="section" multiple="multiple" size="5">'."\n";
 9280:     $result.= $selsec;
 9281:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9282:     $result.='
 9283:     </fieldset>
 9284:   
 9285:     <fieldset>
 9286:       <legend>
 9287:         '.&mt('Groups').'
 9288:       </legend>
 9289:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9290:     </fieldset>
 9291:   
 9292:     <fieldset>
 9293:       <legend>
 9294:         '.&mt('Access Status').'
 9295:       </legend>
 9296:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9297:     </fieldset>
 9298:   
 9299:     <fieldset>
 9300:       <legend>
 9301:         '.&mt('Submission Status').'
 9302:       </legend>
 9303:       <select name="submitonly" size="5">
 9304: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9305: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9306: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9307: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9308:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9309:       </select>
 9310:     </fieldset>
 9311:   
 9312: </div>
 9313: 
 9314: <br />
 9315:           <div>
 9316:             <div>
 9317:               <label>
 9318:                 <input type="radio" name="radioChoice" value="submission" '.
 9319:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9320:              &mt('Select individual students to grade and view submissions.').'
 9321: 	      </label> 
 9322:             </div>
 9323:             <div>
 9324: 	      <label>
 9325:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9326:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 9327:                     &mt('Grade all selected students in a grading table.').'
 9328:               </label>
 9329:             </div>
 9330:             <div>
 9331: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9332:             </div>
 9333:           </div>
 9334: 
 9335: 
 9336:         <h2>
 9337:          '.&mt('Grade Complete Folder for One Student').'
 9338:         </h2>
 9339:         <div>
 9340:             <div>
 9341:               <label>
 9342:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 9343: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 9344:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 9345:               </label>
 9346:             </div>
 9347:             <div>
 9348: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9349:             </div>
 9350:         </div>
 9351:   </form>';
 9352:     $result .= &show_grading_menu_form($symb);
 9353:     return $result;
 9354: }
 9355: 
 9356: sub reset_perm {
 9357:     undef(%perm);
 9358: }
 9359: 
 9360: sub init_perm {
 9361:     &reset_perm();
 9362:     foreach my $test_perm ('vgr','mgr','opa') {
 9363: 
 9364: 	my $scope = $env{'request.course.id'};
 9365: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9366: 
 9367: 	    $scope .= '/'.$env{'request.course.sec'};
 9368: 	    if ( $perm{$test_perm}=
 9369: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9370: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9371: 	    } else {
 9372: 		delete($perm{$test_perm});
 9373: 	    }
 9374: 	}
 9375:     }
 9376: }
 9377: 
 9378: sub init_old_essays {
 9379:     my ($symb,$apath,$adom,$aname) = @_;
 9380:     if ($symb ne '') {
 9381:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9382:         if (keys(%essays) > 0) {
 9383:             $old_essays{$symb} = \%essays;
 9384:         }
 9385:     }
 9386:     return;
 9387: }
 9388: 
 9389: sub reset_old_essays {
 9390:     undef(%old_essays);
 9391: }
 9392: 
 9393: sub gather_clicker_ids {
 9394:     my %clicker_ids;
 9395: 
 9396:     my $classlist = &Apache::loncoursedata::get_classlist();
 9397: 
 9398:     # Set up a couple variables.
 9399:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9400:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9401:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9402: 
 9403:     foreach my $student (keys(%$classlist)) {
 9404:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9405:         my $username = $classlist->{$student}->[$username_idx];
 9406:         my $domain   = $classlist->{$student}->[$domain_idx];
 9407:         my $clickers =
 9408: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9409:         foreach my $id (split(/\,/,$clickers)) {
 9410:             $id=~s/^[\#0]+//;
 9411:             $id=~s/[\-\:]//g;
 9412:             if (exists($clicker_ids{$id})) {
 9413: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9414:             } else {
 9415: 		$clicker_ids{$id}=$username.':'.$domain;
 9416:             }
 9417:         }
 9418:     }
 9419:     return %clicker_ids;
 9420: }
 9421: 
 9422: sub gather_adv_clicker_ids {
 9423:     my %clicker_ids;
 9424:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9425:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9426:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9427:     foreach my $element (sort(keys(%coursepersonnel))) {
 9428:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9429:             my ($puname,$pudom)=split(/\:/,$person);
 9430:             my $clickers =
 9431: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9432:             foreach my $id (split(/\,/,$clickers)) {
 9433: 		$id=~s/^[\#0]+//;
 9434:                 $id=~s/[\-\:]//g;
 9435: 		if (exists($clicker_ids{$id})) {
 9436: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9437: 		} else {
 9438: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9439: 		}
 9440:             }
 9441:         }
 9442:     }
 9443:     return %clicker_ids;
 9444: }
 9445: 
 9446: sub clicker_grading_parameters {
 9447:     return ('gradingmechanism' => 'scalar',
 9448:             'upfiletype' => 'scalar',
 9449:             'specificid' => 'scalar',
 9450:             'pcorrect' => 'scalar',
 9451:             'pincorrect' => 'scalar');
 9452: }
 9453: 
 9454: sub process_clicker {
 9455:     my ($r)=@_;
 9456:     my ($symb)=&get_symb($r);
 9457:     if (!$symb) {return '';}
 9458:     my $result=&checkforfile_js();
 9459:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 9460:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 9461:     $result.=$table;
 9462:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 9463:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 9464:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 9465:         '</b></td></tr>'."\n";
 9466:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 9467: # Attempt to restore parameters from last session, set defaults if not present
 9468:     my %Saveable_Parameters=&clicker_grading_parameters();
 9469:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9470:                                                  \%Saveable_Parameters);
 9471:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9472:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9473:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9474:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9475: 
 9476:     my %checked;
 9477:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9478:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9479:           $checked{$gradingmechanism}=' checked="checked"';
 9480:        }
 9481:     }
 9482: 
 9483:     my $upload=&mt("Upload File");
 9484:     my $type=&mt("Type");
 9485:     my $attendance=&mt("Award points just for participation");
 9486:     my $personnel=&mt("Correctness determined from response by course personnel");
 9487:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9488:     my $given=&mt("Correctness determined from given list of answers").' '.
 9489:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9490:     my $pcorrect=&mt("Percentage points for correct solution");
 9491:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9492:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9493:                                                    {'iclicker' => 'i>clicker',
 9494:                                                     'interwrite' => 'interwrite PRS',
 9495:                                                     'turning' => 'Turning Technologies'});
 9496:     $symb = &Apache::lonenc::check_encrypt($symb);
 9497:     $result.=<<ENDUPFORM;
 9498: <script type="text/javascript">
 9499: function sanitycheck() {
 9500: // Accept only integer percentages
 9501:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9502:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9503: // Find out grading choice
 9504:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9505:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9506:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9507:       }
 9508:    }
 9509: // By default, new choice equals user selection
 9510:    newgradingchoice=gradingchoice;
 9511: // Not good to give more points for false answers than correct ones
 9512:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9513:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9514:    }
 9515: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9516:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9517:       document.forms.gradesupload.pcorrect.value=100;
 9518:       document.forms.gradesupload.pincorrect.value=100;
 9519:    }
 9520: // If the values are different, cannot be attendance only
 9521:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9522:        (gradingchoice=='attendance')) {
 9523:        newgradingchoice='personnel';
 9524:    }
 9525: // Change grading choice to new one
 9526:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9527:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9528:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9529:       } else {
 9530:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9531:       }
 9532:    }
 9533: // Remember the old state
 9534:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9535: }
 9536: </script>
 9537: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9538: <input type="hidden" name="symb" value="$symb" />
 9539: <input type="hidden" name="command" value="processclickerfile" />
 9540: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9541: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9542: <input type="file" name="upfile" size="50" />
 9543: <br /><label>$type: $selectform</label>
 9544: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9545: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9546: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9547: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9548: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9549: <br />&nbsp;&nbsp;&nbsp;
 9550: <input type="text" name="givenanswer" size="50" />
 9551: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9552: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9553: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9554: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9555: </form>
 9556: ENDUPFORM
 9557:     $result.='</td></tr></table>'."\n".
 9558:              '</td></tr></table><br /><br />'."\n";
 9559:     $result.=&show_grading_menu_form($symb);
 9560:     return $result;
 9561: }
 9562: 
 9563: sub process_clicker_file {
 9564:     my ($r)=@_;
 9565:     my ($symb)=&get_symb($r);
 9566:     if (!$symb) {return '';}
 9567: 
 9568:     my %Saveable_Parameters=&clicker_grading_parameters();
 9569:     &Apache::loncommon::store_course_settings('grades_clicker',
 9570:                                               \%Saveable_Parameters);
 9571: 
 9572:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9573:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9574: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9575: 	return $result.&show_grading_menu_form($symb);
 9576:     }
 9577:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9578:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9579:         return $result.&show_grading_menu_form($symb);
 9580:     }
 9581:     my $foundgiven=0;
 9582:     if ($env{'form.gradingmechanism'} eq 'given') {
 9583:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9584:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9585:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9586:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9587:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9588:         $foundgiven=$#answers+1;
 9589:     }
 9590:     my %clicker_ids=&gather_clicker_ids();
 9591:     my %correct_ids;
 9592:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9593: 	%correct_ids=&gather_adv_clicker_ids();
 9594:     }
 9595:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9596: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9597: 	   $correct_id=~tr/a-z/A-Z/;
 9598: 	   $correct_id=~s/\s//gs;
 9599: 	   $correct_id=~s/^[\#0]+//;
 9600:            $correct_id=~s/[\-\:]//g;
 9601:            if ($correct_id) {
 9602: 	      $correct_ids{$correct_id}='specified';
 9603:            }
 9604:         }
 9605:     }
 9606:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9607: 	$result.=&mt('Score based on attendance only');
 9608:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9609:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9610:     } else {
 9611: 	my $number=0;
 9612: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9613: 	foreach my $id (sort(keys(%correct_ids))) {
 9614: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9615: 	    if ($correct_ids{$id} eq 'specified') {
 9616: 		$result.=&mt('specified');
 9617: 	    } else {
 9618: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9619: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9620: 	    }
 9621: 	    $number++;
 9622: 	}
 9623:         $result.="</p>\n";
 9624: 	if ($number==0) {
 9625: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9626: 	    return $result.&show_grading_menu_form($symb);
 9627: 	}
 9628:     }
 9629:     if (length($env{'form.upfile'}) < 2) {
 9630:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9631: 		     '<span class="LC_error">',
 9632: 		     '</span>',
 9633: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9634:         return $result.&show_grading_menu_form($symb);
 9635:     }
 9636: 
 9637: # Were able to get all the info needed, now analyze the file
 9638: 
 9639:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9640:     $symb = &Apache::lonenc::check_encrypt($symb);
 9641:     my $heading=&mt('Scanning clicker file');
 9642:     $result.=(<<ENDHEADER);
 9643: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9644: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9645: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
 9646: <form method="post" action="/adm/grades" name="clickeranalysis">
 9647: <input type="hidden" name="symb" value="$symb" />
 9648: <input type="hidden" name="command" value="assignclickergrades" />
 9649: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9650: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9651: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9652: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9653: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9654: ENDHEADER
 9655:     if ($env{'form.gradingmechanism'} eq 'given') {
 9656:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9657:     } 
 9658:     my %responses;
 9659:     my @questiontitles;
 9660:     my $errormsg='';
 9661:     my $number=0;
 9662:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9663: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9664:     }
 9665:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9666:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9667:     }
 9668:     if ($env{'form.upfiletype'} eq 'turning') {
 9669:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9670:     }
 9671:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9672:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9673:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9674:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9675:              '<br />';
 9676:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9677:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9678:        return $result.&show_grading_menu_form($symb);
 9679:     } 
 9680: # Remember Question Titles
 9681: # FIXME: Possibly need delimiter other than ":"
 9682:     for (my $i=0;$i<$number;$i++) {
 9683:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9684:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9685:     }
 9686:     my $correct_count=0;
 9687:     my $student_count=0;
 9688:     my $unknown_count=0;
 9689: # Match answers with usernames
 9690: # FIXME: Possibly need delimiter other than ":"
 9691:     foreach my $id (keys(%responses)) {
 9692:        if ($correct_ids{$id}) {
 9693:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9694:           $correct_count++;
 9695:        } elsif ($clicker_ids{$id}) {
 9696:           if ($clicker_ids{$id}=~/\,/) {
 9697: # More than one user with the same clicker!
 9698:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9699:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9700:                            "<select name='multi".$id."'>";
 9701:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9702:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9703:              }
 9704:              $result.='</select>';
 9705:              $unknown_count++;
 9706:           } else {
 9707: # Good: found one and only one user with the right clicker
 9708:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9709:              $student_count++;
 9710:           }
 9711:        } else {
 9712:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9713:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9714:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9715:                    "\n".&mt("Domain").": ".
 9716:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9717:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9718:           $unknown_count++;
 9719:        }
 9720:     }
 9721:     $result.='<hr />'.
 9722:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9723:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9724:        if ($correct_count==0) {
 9725:           $errormsg.="Found no correct answers answers for grading!";
 9726:        } elsif ($correct_count>1) {
 9727:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9728:        }
 9729:     }
 9730:     if ($number<1) {
 9731:        $errormsg.="Found no questions.";
 9732:     }
 9733:     if ($errormsg) {
 9734:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9735:     } else {
 9736:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9737:     }
 9738:     $result.='</form></td></tr></table>'."\n".
 9739:              '</td></tr></table><br /><br />'."\n";
 9740:     return $result.&show_grading_menu_form($symb);
 9741: }
 9742: 
 9743: sub iclicker_eval {
 9744:     my ($questiontitles,$responses)=@_;
 9745:     my $number=0;
 9746:     my $errormsg='';
 9747:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9748:         my %components=&Apache::loncommon::record_sep($line);
 9749:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9750: 	if ($entries[0] eq 'Question') {
 9751: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9752: 		$$questiontitles[$number]=$entries[$i];
 9753: 		$number++;
 9754: 	    }
 9755: 	}
 9756: 	if ($entries[0]=~/^\#/) {
 9757: 	    my $id=$entries[0];
 9758: 	    my @idresponses;
 9759: 	    $id=~s/^[\#0]+//;
 9760: 	    for (my $i=0;$i<$number;$i++) {
 9761: 		my $idx=3+$i*6;
 9762:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9763: 		push(@idresponses,$entries[$idx]);
 9764: 	    }
 9765: 	    $$responses{$id}=join(',',@idresponses);
 9766: 	}
 9767:     }
 9768:     return ($errormsg,$number);
 9769: }
 9770: 
 9771: sub interwrite_eval {
 9772:     my ($questiontitles,$responses)=@_;
 9773:     my $number=0;
 9774:     my $errormsg='';
 9775:     my $skipline=1;
 9776:     my $questionnumber=0;
 9777:     my %idresponses=();
 9778:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9779:         my %components=&Apache::loncommon::record_sep($line);
 9780:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9781:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9782:         if ($entries[1] eq 'Response') { $skipline=1; }
 9783:         next if $skipline;
 9784:         if ($entries[0]!=$questionnumber) {
 9785:            $questionnumber=$entries[0];
 9786:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9787:            $number++;
 9788:         }
 9789:         my $id=$entries[4];
 9790:         $id=~s/^[\#0]+//;
 9791:         $id=~s/^v\d*\://i;
 9792:         $id=~s/[\-\:]//g;
 9793:         $idresponses{$id}[$number]=$entries[6];
 9794:     }
 9795:     foreach my $id (keys(%idresponses)) {
 9796:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9797:        $$responses{$id}=~s/^\s*\,//;
 9798:     }
 9799:     return ($errormsg,$number);
 9800: }
 9801: 
 9802: sub turning_eval {
 9803:     my ($questiontitles,$responses)=@_;
 9804:     my $number=0;
 9805:     my $errormsg='';
 9806:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9807:         my %components=&Apache::loncommon::record_sep($line);
 9808:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9809:         if ($#entries>$number) { $number=$#entries; }
 9810:         my $id=$entries[0];
 9811:         my @idresponses;
 9812:         $id=~s/^[\#0]+//;
 9813:         unless ($id) { next; }
 9814:         for (my $idx=1;$idx<=$#entries;$idx++) {
 9815:             $entries[$idx]=~s/\,/\;/g;
 9816:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
 9817:             push(@idresponses,$entries[$idx]);
 9818:         }
 9819:         $$responses{$id}=join(',',@idresponses);
 9820:     }
 9821:     for (my $i=1; $i<=$number; $i++) {
 9822:         $$questiontitles[$i]=&mt('Question [_1]',$i);
 9823:     }
 9824:     return ($errormsg,$number);
 9825: }
 9826: 
 9827: sub assign_clicker_grades {
 9828:     my ($r)=@_;
 9829:     my ($symb)=&get_symb($r);
 9830:     if (!$symb) {return '';}
 9831: # See which part we are saving to
 9832:     my $res_error;
 9833:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9834:     if ($res_error) {
 9835:         return &navmap_errormsg();
 9836:     }
 9837: # FIXME: This should probably look for the first handgradeable part
 9838:     my $part=$$partlist[0];
 9839: # Start screen output
 9840:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9841: 
 9842:     $result .= '<br />'.
 9843:                &Apache::loncommon::start_data_table().
 9844:                &Apache::loncommon::start_data_table_header_row().
 9845:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9846:                &Apache::loncommon::end_data_table_header_row().
 9847:                &Apache::loncommon::start_data_table_row().'<td>';
 9848: 
 9849: # Get correct result
 9850: # FIXME: Possibly need delimiter other than ":"
 9851:     my @correct=();
 9852:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9853:     my $number=$env{'form.number'};
 9854:     if ($gradingmechanism ne 'attendance') {
 9855:        foreach my $key (keys(%env)) {
 9856:           if ($key=~/^form\.correct\:/) {
 9857:              my @input=split(/\,/,$env{$key});
 9858:              for (my $i=0;$i<=$#input;$i++) {
 9859:                  if (($correct[$i]) && ($input[$i]) &&
 9860:                      ($correct[$i] ne $input[$i])) {
 9861:                     $result.='<br /><span class="LC_warning">'.
 9862:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9863:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9864:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9865:                     $correct[$i]=$input[$i];
 9866:                  }
 9867:              }
 9868:           }
 9869:        }
 9870:        for (my $i=0;$i<$number;$i++) {
 9871:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
 9872:              $result.='<br /><span class="LC_error">'.
 9873:                       &mt('No correct result given for question "[_1]"!',
 9874:                           $env{'form.question:'.$i}).'</span>';
 9875:           }
 9876:        }
 9877:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
 9878:     }
 9879: # Start grading
 9880:     my $pcorrect=$env{'form.pcorrect'};
 9881:     my $pincorrect=$env{'form.pincorrect'};
 9882:     my $storecount=0;
 9883:     my %users=();
 9884:     foreach my $key (keys(%env)) {
 9885:        my $user='';
 9886:        if ($key=~/^form\.student\:(.*)$/) {
 9887:           $user=$1;
 9888:        }
 9889:        if ($key=~/^form\.unknown\:(.*)$/) {
 9890:           my $id=$1;
 9891:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9892:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9893:           } elsif ($env{'form.multi'.$id}) {
 9894:              $user=$env{'form.multi'.$id};
 9895:           }
 9896:        }
 9897:        if ($user) {
 9898:           if ($users{$user}) {
 9899:              $result.='<br /><span class="LC_warning">'.
 9900:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9901:                       '</span><br />';
 9902:           }
 9903:           $users{$user}=1;
 9904:           my @answer=split(/\,/,$env{$key});
 9905:           my $sum=0;
 9906:           my $realnumber=$number;
 9907:           for (my $i=0;$i<$number;$i++) {
 9908:              if  ($correct[$i] eq '-') {
 9909:                 $realnumber--;
 9910:              } elsif ($answer[$i]) {
 9911:                 if ($gradingmechanism eq 'attendance') {
 9912:                    $sum+=$pcorrect;
 9913:                 } elsif ($correct[$i] eq '*') {
 9914:                    $sum+=$pcorrect;
 9915:                 } else {
 9916: # We actually grade if correct or not
 9917:                    my $increment=$pincorrect;
 9918: # Special case: numerical answer "0"
 9919:                    if ($correct[$i] eq '0') {
 9920:                       if ($answer[$i]=~/^[0\.]+$/) {
 9921:                          $increment=$pcorrect;
 9922:                       }
 9923: # General numerical answer, both evaluate to something non-zero
 9924:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
 9925:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
 9926:                          $increment=$pcorrect;
 9927:                       }
 9928: # Must be just alphanumeric
 9929:                    } elsif ($answer[$i] eq $correct[$i]) {
 9930:                       $increment=$pcorrect;
 9931:                    }
 9932:                    $sum+=$increment;
 9933:                 }
 9934:              }
 9935:           }
 9936:           my $ave=$sum/(100*$realnumber);
 9937: # Store
 9938:           my ($username,$domain)=split(/\:/,$user);
 9939:           my %grades=();
 9940:           $grades{"resource.$part.solved"}='correct_by_override';
 9941:           $grades{"resource.$part.awarded"}=$ave;
 9942:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9943:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9944:                                                  $env{'request.course.id'},
 9945:                                                  $domain,$username);
 9946:           if ($returncode ne 'ok') {
 9947:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9948:           } else {
 9949:              $storecount++;
 9950:           }
 9951:        }
 9952:     }
 9953: # We are done
 9954:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9955:              '</td>'.
 9956:              &Apache::loncommon::end_data_table_row().
 9957:              &Apache::loncommon::end_data_table()."<br /><br />\n";
 9958:     return $result.&show_grading_menu_form($symb);
 9959: }
 9960: 
 9961: sub navmap_errormsg {
 9962:     return '<div class="LC_error">'.
 9963:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9964:            &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>').
 9965:            '</div>';
 9966: }
 9967: 
 9968: sub startpage {
 9969:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
 9970:     if ($nomenu) {
 9971:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
 9972:     } else {
 9973:         $r->print(&Apache::loncommon::start_page('Grading',$js,
 9974:                                                  {'bread_crumbs' => $crumbs}));
 9975:     }
 9976:     unless ($nodisplayflag) {
 9977:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
 9978:     }
 9979: }
 9980: 
 9981: sub handler {
 9982:     my $request=$_[0];
 9983:     &reset_caches();
 9984:     if ($request->header_only) {
 9985:         &Apache::loncommon::content_type($request,'text/html');
 9986:         $request->send_http_header;
 9987:         return OK;
 9988:     }
 9989:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9990: 
 9991:     my $symb=&get_symb($request,1);
 9992:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9993:     my $command=$commands[0];
 9994: 
 9995:     if ($#commands > 0) {
 9996: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9997:     }
 9998: 
 9999:     $ssi_error = 0;
10000:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10001:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10002:                                                     {'bread_crumbs' => $brcrum});
10003:     if ($symb eq '' && $command eq '') {
10004: 	if ($env{'user.adv'}) {
10005:             &Apache::loncommon::content_type($request,'text/html');
10006:             $request->send_http_header;
10007:             $request->print($start_page);
10008: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10009: 		($env{'form.codethree'})) {
10010: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10011: 		    $env{'form.codethree'};
10012: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10013: 		    &Apache::lonnet::checkin($token);
10014: 		if ($tsymb) {
10015: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10016: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10017: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10018: 					  ('grade_username' => $tuname,
10019: 					   'grade_domain' => $tudom,
10020: 					   'grade_courseid' => $tcrsid,
10021: 					   'grade_symb' => $tsymb)));
10022: 		    } else {
10023: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10024: 		    }
10025: 		} else {
10026: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10027: 		}
10028: 	    } else {
10029: 		$request->print(&Apache::lonxml::tokeninputfield());
10030: 	    }
10031:         } elsif ($env{'request.course.id'}) {
10032:             &init_perm(); 
10033:             if (!%perm) {
10034:                 $request->internal_redirect('/adm/quickgrades');
10035:             } else {
10036:                 &Apache::loncommon::content_type($request,'text/html');
10037:                 $request->send_http_header;
10038:                 $request->print($start_page);
10039:             }
10040:         }
10041:     } else {
10042:         &init_perm();
10043:         if (!$env{'request.course.id'}) {
10044:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10045:                     ($command =~ /^scantronupload/)) {
10046:                 # Not in a course.
10047:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10048:                 return HTTP_NOT_ACCEPTABLE;
10049:             }
10050:         } elsif (!%perm) {
10051:             $request->internal_redirect('/adm/quickgrades');
10052:         }
10053:         &Apache::loncommon::content_type($request,'text/html');
10054:         $request->send_http_header;
10055:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10056:             $request->print($start_page); 
10057:         }
10058: 	if ($command eq 'submission' && $perm{'vgr'}) {
10059:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10060:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10061:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10062:                     &choose_task_version_form($symb,$env{'form.student'},
10063:                                               $env{'form.userdom'});
10064:             }
10065:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10066:             if ($versionform) {
10067:                 $request->print($versionform);
10068:             }
10069:             $request->print('<br clear="all" />');
10070: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10071:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10072:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10073:                 &choose_task_version_form($symb,$env{'form.student'},
10074:                                           $env{'form.userdom'},
10075:                                           $env{'form.inhibitmenu'});
10076:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10077:             if ($versionform) {
10078:                 $request->print($versionform);
10079:             }
10080:             $request->print('<br clear="all" />');
10081:             $request->print(&show_previous_task_version($request,$symb));
10082: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10083: 	    &pickStudentPage($request);
10084: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10085: 	    &displayPage($request);
10086: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10087: 	    &updateGradeByPage($request);
10088: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10089: 	    &processGroup($request);
10090: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10091: 	    $request->print(&grading_menu($request));
10092: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10093: 	    $request->print(&submit_options($request));
10094: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10095: 	    $request->print(&viewgrades($request));
10096: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10097: 	    $request->print(&processHandGrade($request));
10098: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10099: 	    $request->print(&editgrades($request));
10100: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10101: 	    $request->print(&verifyreceipt($request));
10102:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10103:             $request->print(&process_clicker($request));
10104:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10105:             $request->print(&process_clicker_file($request));
10106:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10107:             $request->print(&assign_clicker_grades($request));
10108: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10109: 	    $request->print(&upcsvScores_form($request));
10110: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10111: 	    $request->print(&csvupload($request));
10112: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10113: 	    $request->print(&csvuploadmap($request));
10114: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10115: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10116: 		$request->print(&csvuploadoptions($request));
10117: 	    } else {
10118: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10119: 		    $env{'form.upfile_associate'} = 'reverse';
10120: 		} else {
10121: 		    $env{'form.upfile_associate'} = 'forward';
10122: 		}
10123: 		$request->print(&csvuploadmap($request));
10124: 	    }
10125: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10126: 	    $request->print(&csvuploadassign($request));
10127: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10128: 	    $request->print(&scantron_selectphase($request));
10129:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10130:  	    $request->print(&scantron_do_warning($request));
10131: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10132: 	    $request->print(&scantron_validate_file($request));
10133: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10134: 	    $request->print(&scantron_process_students($request));
10135:  	} elsif ($command eq 'scantronupload' && 
10136:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10137: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10138:  	    $request->print(&scantron_upload_scantron_data($request)); 
10139:  	} elsif ($command eq 'scantronupload_save' &&
10140:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10141: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10142:  	    $request->print(&scantron_upload_scantron_data_save($request));
10143:  	} elsif ($command eq 'scantron_download' &&
10144: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10145:  	    $request->print(&scantron_download_scantron_data($request));
10146:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10147:             $request->print(&checkscantron_results($request));     
10148: 	} elsif ($command) {
10149: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10150: 	}
10151:     }
10152:     if ($ssi_error) {
10153: 	&ssi_print_error($request);
10154:     }
10155:     $request->print(&Apache::loncommon::end_page());
10156:     &reset_caches();
10157:     return OK;
10158: }
10159: 
10160: 1;
10161: 
10162: __END__;
10163: 
10164: 
10165: =head1 NAME
10166: 
10167: Apache::grades
10168: 
10169: =head1 SYNOPSIS
10170: 
10171: Handles the viewing of grades.
10172: 
10173: This is part of the LearningOnline Network with CAPA project
10174: described at http://www.lon-capa.org.
10175: 
10176: =head1 OVERVIEW
10177: 
10178: Do an ssi with retries:
10179: While I'd love to factor out this with the vesrion in lonprintout,
10180: 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
10181: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10182: 
10183: At least the logic that drives this has been pulled out into loncommon.
10184: 
10185: 
10186: 
10187: ssi_with_retries - Does the server side include of a resource.
10188:                      if the ssi call returns an error we'll retry it up to
10189:                      the number of times requested by the caller.
10190:                      If we still have a proble, no text is appended to the
10191:                      output and we set some global variables.
10192:                      to indicate to the caller an SSI error occurred.  
10193:                      All of this is supposed to deal with the issues described
10194:                      in LonCAPA BZ 5631 see:
10195:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10196:                      by informing the user that this happened.
10197: 
10198: Parameters:
10199:   resource   - The resource to include.  This is passed directly, without
10200:                interpretation to lonnet::ssi.
10201:   form       - The form hash parameters that guide the interpretation of the resource
10202:                
10203:   retries    - Number of retries allowed before giving up completely.
10204: Returns:
10205:   On success, returns the rendered resource identified by the resource parameter.
10206: Side Effects:
10207:   The following global variables can be set:
10208:    ssi_error                - If an unrecoverable error occurred this becomes true.
10209:                               It is up to the caller to initialize this to false
10210:                               if desired.
10211:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10212:                               of the resource that could not be rendered by the ssi
10213:                               call.
10214:    ssi_error_message   - The error string fetched from the ssi response
10215:                               in the event of an error.
10216: 
10217: 
10218: =head1 HANDLER SUBROUTINE
10219: 
10220: ssi_with_retries()
10221: 
10222: =head1 SUBROUTINES
10223: 
10224: =over
10225: 
10226: =item scantron_get_correction() : 
10227: 
10228:    Builds the interface screen to interact with the operator to fix a
10229:    specific error condition in a specific scanline
10230: 
10231:  Arguments:
10232:     $r           - Apache request object
10233:     $i           - number of the current scanline
10234:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10235:     $scan_config - hash ref as returned from &get_scantron_config()
10236:     $line        - full contents of the current scanline
10237:     $error       - error condition, valid values are
10238:                    'incorrectCODE', 'duplicateCODE',
10239:                    'doublebubble', 'missingbubble',
10240:                    'duplicateID', 'incorrectID'
10241:     $arg         - extra information needed
10242:        For errors:
10243:          - duplicateID   - paper number that this studentID was seen before on
10244:          - duplicateCODE - array ref of the paper numbers this CODE was
10245:                            seen on before
10246:          - incorrectCODE - current incorrect CODE 
10247:          - doublebubble  - array ref of the bubble lines that have double
10248:                            bubble errors
10249:          - missingbubble - array ref of the bubble lines that have missing
10250:                            bubble errors
10251: 
10252: =item  scantron_get_maxbubble() : 
10253: 
10254:    Arguments:
10255:        $nav_error  - Reference to scalar which is a flag to indicate a
10256:                       failure to retrieve a navmap object.
10257:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10258:        calling routine should trap the error condition and display the warning
10259:        found in &navmap_errormsg().
10260: 
10261:        $scantron_config - Reference to bubblesheet format configuration hash.
10262: 
10263:    Returns the maximum number of bubble lines that are expected to
10264:    occur. Does this by walking the selected sequence rendering the
10265:    resource and then checking &Apache::lonxml::get_problem_counter()
10266:    for what the current value of the problem counter is.
10267: 
10268:    Caches the results to $env{'form.scantron_maxbubble'},
10269:    $env{'form.scantron.bubble_lines.n'}, 
10270:    $env{'form.scantron.first_bubble_line.n'} and
10271:    $env{"form.scantron.sub_bubblelines.n"}
10272:    which are the total number of bubble, lines, the number of bubble
10273:    lines for response n and number of the first bubble line for response n,
10274:    and a comma separated list of numbers of bubble lines for sub-questions
10275:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10276: 
10277: 
10278: =item  scantron_validate_missingbubbles() : 
10279: 
10280:    Validates all scanlines in the selected file to not have any
10281:     answers that don't have bubbles that have not been verified
10282:     to be bubble free.
10283: 
10284: =item  scantron_process_students() : 
10285: 
10286:    Routine that does the actual grading of the bubblesheet information.
10287: 
10288:    The parsed scanline hash is added to %env 
10289: 
10290:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10291:    foreach resource , with the form data of
10292: 
10293: 	'submitted'     =>'scantron' 
10294: 	'grade_target'  =>'grade',
10295: 	'grade_username'=> username of student
10296: 	'grade_domain'  => domain of student
10297: 	'grade_courseid'=> of course
10298: 	'grade_symb'    => symb of resource to grade
10299: 
10300:     This triggers a grading pass. The problem grading code takes care
10301:     of converting the bubbled letter information (now in %env) into a
10302:     valid submission.
10303: 
10304: =item  scantron_upload_scantron_data() :
10305: 
10306:     Creates the screen for adding a new bubblesheet data file to a course.
10307: 
10308: =item  scantron_upload_scantron_data_save() : 
10309: 
10310:    Adds a provided bubble information data file to the course if user
10311:    has the correct privileges to do so. 
10312: 
10313: =item  valid_file() :
10314: 
10315:    Validates that the requested bubble data file exists in the course.
10316: 
10317: =item  scantron_download_scantron_data() : 
10318: 
10319:    Shows a list of the three internal files (original, corrected,
10320:    skipped) for a specific bubblesheet data file that exists in the
10321:    course.
10322: 
10323: =item  scantron_validate_ID() : 
10324: 
10325:    Validates all scanlines in the selected file to not have any
10326:    invalid or underspecified student/employee IDs
10327: 
10328: =item navmap_errormsg() :
10329: 
10330:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10331:    Should be called whenever the request to instantiate a navmap object fails.  
10332: 
10333: =back
10334: 
10335: =cut

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