File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.19: download - view: text, annotated - select for diffs
Fri Aug 16 15:36:08 2013 UTC (10 years, 8 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  - Backport 1.701
  - Exclude HTML tags from phrases to be translated (commensurate with changes
    in localize/localize/de.pm rev. 1.463.2.12).

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.19 2013/08/16 15:36:08 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::bridgetask();
   47: use String::Similarity;
   48: use LONCAPA;
   49: 
   50: use POSIX qw(floor);
   51: 
   52: 
   53: 
   54: my %perm=();
   55: my %old_essays=();
   56: 
   57: #  These variables are used to recover from ssi errors
   58: 
   59: my $ssi_retries = 5;
   60: my $ssi_error;
   61: my $ssi_error_resource;
   62: my $ssi_error_message;
   63: 
   64: 
   65: sub ssi_with_retries {
   66:     my ($resource, $retries, %form) = @_;
   67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   68:     if ($response->is_error) {
   69: 	$ssi_error          = 1;
   70: 	$ssi_error_resource = $resource;
   71: 	$ssi_error_message  = $response->code . " " . $response->message;
   72:     }
   73: 
   74:     return $content;
   75: 
   76: }
   77: #
   78: #  Prodcuces an ssi retry failure error message to the user:
   79: #
   80: 
   81: sub ssi_print_error {
   82:     my ($r) = @_;
   83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   84:     $r->print('
   85: <br />
   86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   87: <p>
   88: '.&mt('Unable to retrieve a resource from a server:').'<br />
   89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   90: '.&mt('Error:').' '.$ssi_error_message.'
   91: </p>
   92: <p>'.
   93: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   95: '</p>');
   96:     return;
   97: }
   98: 
   99: #
  100: # --- Retrieve the parts from the metadata file.---
  101: sub getpartlist {
  102:     my ($symb,$errorref) = @_;
  103: 
  104:     my $navmap   = Apache::lonnavmaps::navmap->new();
  105:     unless (ref($navmap)) {
  106:         if (ref($errorref)) { 
  107:             $$errorref = 'navmap';
  108:             return;
  109:         }
  110:     }
  111:     my $res      = $navmap->getBySymb($symb);
  112:     my $partlist = $res->parts();
  113:     my $url      = $res->src();
  114:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  115: 
  116:     my @stores;
  117:     foreach my $part (@{ $partlist }) {
  118: 	foreach my $key (@metakeys) {
  119: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  120: 	}
  121:     }
  122:     return @stores;
  123: }
  124: 
  125: # --- Get the symbolic name of a problem and the url
  126: sub get_symb {
  127:     my ($request,$silent) = @_;
  128:     my $symb=$env{'form.symb'};
  129:     unless ($symb) {
  130:         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  131:         $symb = &Apache::lonnet::symbread($url);
  132:         if ($symb eq '') { 
  133: 	    if (!$silent) {
  134:                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  135: 	        return ();
  136: 	    }
  137:         }
  138:     }
  139:     &Apache::lonenc::check_decrypt(\$symb);
  140:     return ($symb);
  141: }
  142: 
  143: #--- Format fullname, username:domain if different for display
  144: #--- Use anywhere where the student names are listed
  145: sub nameUserString {
  146:     my ($type,$fullname,$uname,$udom) = @_;
  147:     if ($type eq 'header') {
  148: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  149:     } else {
  150: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  151: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  152:     }
  153: }
  154: 
  155: #--- Get the partlist and the response type for a given problem. ---
  156: #--- Indicate if a response type is coded handgraded or not. ---
  157: sub response_type {
  158:     my ($symb,$response_error) = @_;
  159: 
  160:     my $navmap = Apache::lonnavmaps::navmap->new();
  161:     unless (ref($navmap)) {
  162:         if (ref($response_error)) {
  163:             $$response_error = 1;
  164:         }
  165:         return;
  166:     }
  167:     my $res = $navmap->getBySymb($symb);
  168:     unless (ref($res)) {
  169:         $$response_error = 1;
  170:         return;
  171:     }
  172:     my $partlist = $res->parts();
  173:     my %vPart = 
  174: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  175:     my (%response_types,%handgrade);
  176:     foreach my $part (@{ $partlist }) {
  177: 	next if (%vPart && !exists($vPart{$part}));
  178: 
  179: 	my @types = $res->responseType($part);
  180: 	my @ids = $res->responseIds($part);
  181: 	for (my $i=0; $i < scalar(@ids); $i++) {
  182: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  183: 	    $handgrade{$part.'_'.$ids[$i]} = 
  184: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  185: 				     '.handgrade',$symb);
  186: 	}
  187:     }
  188:     return ($partlist,\%handgrade,\%response_types);
  189: }
  190: 
  191: sub flatten_responseType {
  192:     my ($responseType) = @_;
  193:     my @part_response_id =
  194: 	map { 
  195: 	    my $part = $_;
  196: 	    map {
  197: 		[$part,$_]
  198: 		} sort(keys(%{ $responseType->{$part} }));
  199: 	} sort(keys(%$responseType));
  200:     return @part_response_id;
  201: }
  202: 
  203: sub get_display_part {
  204:     my ($partID,$symb)=@_;
  205:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  206:     if (defined($display) and $display ne '') {
  207:         $display.= ' (<span class="LC_internal_info">'
  208:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  209:     } else {
  210: 	$display=$partID;
  211:     }
  212:     return $display;
  213: }
  214: 
  215: #--- Show resource title
  216: #--- and parts and response type
  217: sub showResourceInfo {
  218:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  219:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  220:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  221:     if (ref($res_error)) {
  222:         if ($$res_error) {
  223:             return;
  224:         }
  225:     }
  226:     $result.=&Apache::loncommon::start_data_table()
  227:             .&Apache::loncommon::start_data_table_header_row();
  228:     if ($checkboxes) {
  229:         $result.='<th>&nbsp;</th>';
  230:     }
  231:     $result.='<th>'.&mt('Problem Part').'</th>'
  232:             .'<th>'.&mt('Res. ID').'</th>'
  233:             .'<th>'.&mt('Type').'</th>'
  234:             .&Apache::loncommon::end_data_table_header_row();
  235:     my %resptype = ();
  236:     my $hdgrade='no';
  237:     my %partsseen;
  238:     foreach my $partID (sort(keys(%$responseType))) {
  239:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  240:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  241:             my $responsetype = $responseType->{$partID}->{$resID};
  242:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  243:             $result.=&Apache::loncommon::start_data_table_row();
  244:             if ($checkboxes) {
  245:                 if (exists($partsseen{$partID})) {
  246:                     $result.="<td>&nbsp;</td>";
  247:                 } else {
  248:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  249:                 }
  250:                 $partsseen{$partID}=1;
  251:             }
  252:             my $display_part=&get_display_part($partID,$symb);
  253:             $result.='<td>'.$display_part.'</td>'
  254:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  255:                     .'<td>'.&mt($responsetype).'</td>'
  256: #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
  257:                     .&Apache::loncommon::end_data_table_row();
  258:         }
  259:     }
  260:     $result.=&Apache::loncommon::end_data_table();
  261:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  262: }
  263: 
  264: sub reset_caches {
  265:     &reset_analyze_cache();
  266:     &reset_perm();
  267:     &reset_old_essays();
  268: }
  269: 
  270: {
  271:     my %analyze_cache;
  272:     my %analyze_cache_formkeys;
  273: 
  274:     sub reset_analyze_cache {
  275: 	undef(%analyze_cache);
  276:         undef(%analyze_cache_formkeys);
  277:     }
  278: 
  279:     sub get_analyze {
  280: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  281: 	my $key = "$symb\0$uname\0$udom";
  282:         if ($type eq 'randomizetry') {
  283:             if ($trial ne '') {
  284:                 $key .= "\0".$trial;
  285:             }
  286:         }
  287: 	if (exists($analyze_cache{$key})) {
  288:             my $getupdate = 0;
  289:             if (ref($add_to_hash) eq 'HASH') {
  290:                 foreach my $item (keys(%{$add_to_hash})) {
  291:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  292:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  293:                             $getupdate = 1;
  294:                             last;
  295:                         }
  296:                     } else {
  297:                         $getupdate = 1;
  298:                     }
  299:                 }
  300:             }
  301:             if (!$getupdate) {
  302:                 return $analyze_cache{$key};
  303:             }
  304:         }
  305: 
  306: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  307: 	$url=&Apache::lonnet::clutter($url);
  308:         my %form = ('grade_target'      => 'analyze',
  309:                     'grade_domain'      => $udom,
  310:                     'grade_symb'        => $symb,
  311:                     'grade_courseid'    =>  $env{'request.course.id'},
  312:                     'grade_username'    => $uname,
  313:                     'grade_noincrement' => $no_increment);
  314:         if ($bubbles_per_row ne '') {
  315:             $form{'bubbles_per_row'} = $bubbles_per_row;
  316:         }
  317:         if ($type eq 'randomizetry') {
  318:             $form{'grade_questiontype'} = $type;
  319:             if ($rndseed ne '') {
  320:                 $form{'grade_rndseed'} = $rndseed;
  321:             }
  322:         }
  323:         if (ref($add_to_hash)) {
  324:             %form = (%form,%{$add_to_hash});
  325:         }
  326: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  327: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  328: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  329:         if (ref($add_to_hash) eq 'HASH') {
  330:             $analyze_cache_formkeys{$key} = $add_to_hash;
  331:         } else {
  332:             $analyze_cache_formkeys{$key} = {};
  333:         }
  334: 	return $analyze_cache{$key} = \%analyze;
  335:     }
  336: 
  337:     sub get_order {
  338: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  339: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  340: 	return $analyze->{"$partid.$respid.shown"};
  341:     }
  342: 
  343:     sub get_radiobutton_correct_foil {
  344: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  345: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  346:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  347:         if (ref($foils) eq 'ARRAY') {
  348: 	    foreach my $foil (@{$foils}) {
  349: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  350: 		    return $foil;
  351: 	        }
  352: 	    }
  353: 	}
  354:     }
  355: 
  356:     sub scantron_partids_tograde {
  357:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  358:         my (%analysis,@parts);
  359:         if (ref($resource)) {
  360:             my $symb = $resource->symb();
  361:             my $add_to_form;
  362:             if ($check_for_randomlist) {
  363:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  364:             }
  365:             my $analyze =
  366:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  367:                              undef,undef,undef,$bubbles_per_row);
  368:             if (ref($analyze) eq 'HASH') {
  369:                 %analysis = %{$analyze};
  370:             }
  371:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  372:                 foreach my $part (@{$analysis{'parts'}}) {
  373:                     my ($id,$respid) = split(/\./,$part);
  374:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  375:                         push(@parts,$part);
  376:                     }
  377:                 }
  378:             }
  379:         }
  380:         return (\%analysis,\@parts);
  381:     }
  382: 
  383: }
  384: 
  385: #--- Clean response type for display
  386: #--- Currently filters option/rank/radiobutton/match/essay/Task
  387: #        response types only.
  388: sub cleanRecord {
  389:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  390: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  391:     my $grayFont = '<span class="LC_internal_info">';
  392:     if ($response =~ /^(option|rank)$/) {
  393: 	my %answer=&Apache::lonnet::str2hash($answer);
  394: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  395: 	my ($toprow,$bottomrow);
  396: 	foreach my $foil (@$order) {
  397: 	    if ($grading{$foil} == 1) {
  398: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  399: 	    } else {
  400: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  401: 	    }
  402: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  403: 	}
  404: 	return '<blockquote><table border="1">'.
  405: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  406: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  407: 	    $bottomrow.'</tr></table></blockquote>';
  408:     } elsif ($response eq 'match') {
  409: 	my %answer=&Apache::lonnet::str2hash($answer);
  410: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  411: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  412: 	my ($toprow,$middlerow,$bottomrow);
  413: 	foreach my $foil (@$order) {
  414: 	    my $item=shift(@items);
  415: 	    if ($grading{$foil} == 1) {
  416: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  417: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  418: 	    } else {
  419: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  420: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  421: 	    }
  422: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  423: 	}
  424: 	return '<blockquote><table border="1">'.
  425: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  426: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  427: 	    $middlerow.'</tr>'.
  428: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  429: 	    $bottomrow.'</tr></table></blockquote>';
  430:     } elsif ($response eq 'radiobutton') {
  431: 	my %answer=&Apache::lonnet::str2hash($answer);
  432: 	my ($toprow,$bottomrow);
  433: 	my $correct = 
  434: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  435: 	foreach my $foil (@$order) {
  436: 	    if (exists($answer{$foil})) {
  437: 		if ($foil eq $correct) {
  438: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  439: 		} else {
  440: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  441: 		}
  442: 	    } else {
  443: 		$toprow.='<td>'.&mt('false').'</td>';
  444: 	    }
  445: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  446: 	}
  447: 	return '<blockquote><table border="1">'.
  448: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  449: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  450: 	    $bottomrow.'</tr></table></blockquote>';
  451:     } elsif ($response eq 'essay') {
  452: 	if (! exists ($env{'form.'.$symb})) {
  453: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  454: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  455: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  456: 
  457: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  458: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  459: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  460: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  461: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  462: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  463: 	}
  464: 	$answer =~ s-\n-<br />-g;
  465: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  466:     } elsif ( $response eq 'organic') {
  467: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  468: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  469: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  470: 	return $result;
  471:     } elsif ( $response eq 'Task') {
  472: 	if ( $answer eq 'SUBMITTED') {
  473: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  474: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  475: 	    return $result;
  476: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  477: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  478: 			       keys(%{$record}));
  479: 	    return join('<br />',($version,@matches));
  480: 			       
  481: 			       
  482: 	} else {
  483: 	    my $result =
  484: 		'<p>'
  485: 		.&mt('Overall result: [_1]',
  486: 		     $record->{$version."resource.$respid.$partid.status"})
  487: 		.'</p>';
  488: 	    
  489: 	    $result .= '<ul>';
  490: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  491: 			     keys(%{$record}));
  492: 	    foreach my $grade (sort(@grade)) {
  493: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  494: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  495: 				     $dim, $record->{$grade}).
  496: 			  '</li>';
  497: 	    }
  498: 	    $result.='</ul>';
  499: 	    return $result;
  500: 	}
  501:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  502: 	$answer = 
  503: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  504: 							      $answer);
  505:     }
  506:     return $answer;
  507: }
  508: 
  509: #-- A couple of common js functions
  510: sub commonJSfunctions {
  511:     my $request = shift;
  512:     $request->print(<<COMMONJSFUNCTIONS);
  513: <script type="text/javascript" language="javascript">
  514:     function radioSelection(radioButton) {
  515: 	var selection=null;
  516: 	if (radioButton.length > 1) {
  517: 	    for (var i=0; i<radioButton.length; i++) {
  518: 		if (radioButton[i].checked) {
  519: 		    return radioButton[i].value;
  520: 		}
  521: 	    }
  522: 	} else {
  523: 	    if (radioButton.checked) return radioButton.value;
  524: 	}
  525: 	return selection;
  526:     }
  527: 
  528:     function pullDownSelection(selectOne) {
  529: 	var selection="";
  530: 	if (selectOne.length > 1) {
  531: 	    for (var i=0; i<selectOne.length; i++) {
  532: 		if (selectOne[i].selected) {
  533: 		    return selectOne[i].value;
  534: 		}
  535: 	    }
  536: 	} else {
  537:             // only one value it must be the selected one
  538: 	    return selectOne.value;
  539: 	}
  540:     }
  541: </script>
  542: COMMONJSFUNCTIONS
  543: }
  544: 
  545: #--- Dumps the class list with usernames,list of sections,
  546: #--- section, ids and fullnames for each user.
  547: sub getclasslist {
  548:     my ($getsec,$filterlist,$getgroup) = @_;
  549:     my @getsec;
  550:     my @getgroup;
  551:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  552:     if (!ref($getsec)) {
  553: 	if ($getsec ne '' && $getsec ne 'all') {
  554: 	    @getsec=($getsec);
  555: 	}
  556:     } else {
  557: 	@getsec=@{$getsec};
  558:     }
  559:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  560:     if (!ref($getgroup)) {
  561: 	if ($getgroup ne '' && $getgroup ne 'all') {
  562: 	    @getgroup=($getgroup);
  563: 	}
  564:     } else {
  565: 	@getgroup=@{$getgroup};
  566:     }
  567:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  568: 
  569:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  570:     # Bail out if we were unable to get the classlist
  571:     return if (! defined($classlist));
  572:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  573:     #
  574:     my %sections;
  575:     my %fullnames;
  576:     foreach my $student (keys(%$classlist)) {
  577:         my $end      = 
  578:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  579:         my $start    = 
  580:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  581:         my $id       = 
  582:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  583:         my $section  = 
  584:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  585:         my $fullname = 
  586:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  587:         my $status   = 
  588:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  589:         my $group   = 
  590:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  591: 	# filter students according to status selected
  592: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  593: 	    if (!($stu_status =~ $status)) {
  594: 		delete($classlist->{$student});
  595: 		next;
  596: 	    }
  597: 	}
  598: 	# filter students according to groups selected
  599: 	my @stu_groups = split(/,/,$group);
  600: 	if (@getgroup) {
  601: 	    my $exclude = 1;
  602: 	    foreach my $grp (@getgroup) {
  603: 	        foreach my $stu_group (@stu_groups) {
  604: 	            if ($stu_group eq $grp) {
  605: 	                $exclude = 0;
  606:     	            } 
  607: 	        }
  608:     	        if (($grp eq 'none') && !$group) {
  609:         	        $exclude = 0;
  610:         	}
  611: 	    }
  612: 	    if ($exclude) {
  613: 	        delete($classlist->{$student});
  614: 	    }
  615: 	}
  616: 	$section = ($section ne '' ? $section : 'none');
  617: 	if (&canview($section)) {
  618: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  619: 		$sections{$section}++;
  620: 		if ($classlist->{$student}) {
  621: 		    $fullnames{$student}=$fullname;
  622: 		}
  623: 	    } else {
  624: 		delete($classlist->{$student});
  625: 	    }
  626: 	} else {
  627: 	    delete($classlist->{$student});
  628: 	}
  629:     }
  630:     my %seen = ();
  631:     my @sections = sort(keys(%sections));
  632:     return ($classlist,\@sections,\%fullnames);
  633: }
  634: 
  635: sub canmodify {
  636:     my ($sec)=@_;
  637:     if ($perm{'mgr'}) {
  638: 	if (!defined($perm{'mgr_section'})) {
  639: 	    # can modify whole class
  640: 	    return 1;
  641: 	} else {
  642: 	    if ($sec eq $perm{'mgr_section'}) {
  643: 		#can modify the requested section
  644: 		return 1;
  645: 	    } else {
  646: 		# can't modify the request section
  647: 		return 0;
  648: 	    }
  649: 	}
  650:     }
  651:     #can't modify
  652:     return 0;
  653: }
  654: 
  655: sub canview {
  656:     my ($sec)=@_;
  657:     if ($perm{'vgr'}) {
  658: 	if (!defined($perm{'vgr_section'})) {
  659: 	    # can modify whole class
  660: 	    return 1;
  661: 	} else {
  662: 	    if ($sec eq $perm{'vgr_section'}) {
  663: 		#can modify the requested section
  664: 		return 1;
  665: 	    } else {
  666: 		# can't modify the request section
  667: 		return 0;
  668: 	    }
  669: 	}
  670:     }
  671:     #can't modify
  672:     return 0;
  673: }
  674: 
  675: #--- Retrieve the grade status of a student for all the parts
  676: sub student_gradeStatus {
  677:     my ($symb,$udom,$uname,$partlist) = @_;
  678:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  679:     my %partstatus = ();
  680:     foreach (@$partlist) {
  681: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  682: 	$status              = 'nothing' if ($status eq '');
  683: 	$partstatus{$_}      = $status;
  684: 	my $subkey           = "resource.$_.submitted_by";
  685: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  686:     }
  687:     return %partstatus;
  688: }
  689: 
  690: # hidden form and javascript that calls the form
  691: # Use by verifyscript and viewgrades
  692: # Shows a student's view of problem and submission
  693: sub jscriptNform {
  694:     my ($symb) = @_;
  695:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  696:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  697: 	'    function viewOneStudent(user,domain) {'."\n".
  698: 	'	document.onestudent.student.value = user;'."\n".
  699: 	'	document.onestudent.userdom.value = domain;'."\n".
  700: 	'	document.onestudent.submit();'."\n".
  701: 	'    }'."\n".
  702: 	'</script>'."\n";
  703:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  704: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  705: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  706: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  707: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  708: 	'<input type="hidden" name="command" value="submission" />'."\n".
  709: 	'<input type="hidden" name="student" value="" />'."\n".
  710: 	'<input type="hidden" name="userdom" value="" />'."\n".
  711: 	'</form>'."\n";
  712:     return $jscript;
  713: }
  714: 
  715: 
  716: 
  717: # Given the score (as a number [0-1] and the weight) what is the final
  718: # point value? This function will round to the nearest tenth, third,
  719: # or quarter if one of those is within the tolerance of .00001.
  720: sub compute_points {
  721:     my ($score, $weight) = @_;
  722:     
  723:     my $tolerance = .00001;
  724:     my $points = $score * $weight;
  725: 
  726:     # Check for nearness to 1/x.
  727:     my $check_for_nearness = sub {
  728:         my ($factor) = @_;
  729:         my $num = ($points * $factor) + $tolerance;
  730:         my $floored_num = floor($num);
  731:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  732:             return $floored_num / $factor;
  733:         }
  734:         return $points;
  735:     };
  736: 
  737:     $points = $check_for_nearness->(10);
  738:     $points = $check_for_nearness->(3);
  739:     $points = $check_for_nearness->(4);
  740:     
  741:     return $points;
  742: }
  743: 
  744: #------------------ End of general use routines --------------------
  745: 
  746: #
  747: # Find most similar essay
  748: #
  749: 
  750: sub most_similar {
  751:     my ($uname,$udom,$symb,$uessay)=@_;
  752: 
  753:     unless ($symb) { return ''; }
  754: 
  755:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  756: 
  757: # ignore spaces and punctuation
  758: 
  759:     $uessay=~s/\W+/ /gs;
  760: 
  761: # ignore empty submissions (occuring when only files are sent)
  762: 
  763:     unless ($uessay=~/\w+/s) { return ''; }
  764: 
  765: # these will be returned. Do not care if not at least 50 percent similar
  766:     my $limit=0.6;
  767:     my $sname='';
  768:     my $sdom='';
  769:     my $scrsid='';
  770:     my $sessay='';
  771: # go through all essays ...
  772:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  773: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  774: # ... except the same student
  775:         next if (($tname eq $uname) && ($tdom eq $udom));
  776: 	my $tessay=$old_essays{$symb}{$tkey};
  777: 	$tessay=~s/\W+/ /gs;
  778: # String similarity gives up if not even limit
  779: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  780: # Found one
  781: 	if ($tsimilar>$limit) {
  782: 	    $limit=$tsimilar;
  783: 	    $sname=$tname;
  784: 	    $sdom=$tdom;
  785: 	    $scrsid=$tcrsid;
  786: 	    $sessay=$old_essays{$symb}{$tkey};
  787: 	}
  788:     }
  789:     if ($limit>0.6) {
  790:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  791:     } else {
  792:        return ('','','','',0);
  793:     }
  794: }
  795: 
  796: #-------------------------------------------------------------------
  797: 
  798: #------------------------------------ Receipt Verification Routines
  799: #
  800: #--- Check whether a receipt number is valid.---
  801: sub verifyreceipt {
  802:     my $request  = shift;
  803: 
  804:     my $courseid = $env{'request.course.id'};
  805:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  806: 	$env{'form.receipt'};
  807:     $receipt     =~ s/[^\-\d]//g;
  808:     my ($symb)   = &get_symb($request);
  809: 
  810:     my $title.=
  811: 	'<h3><span class="LC_info">'.
  812: 	&mt('Verifying Receipt No. [_1]',$receipt).
  813: 	'</span></h3>'."\n".
  814: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  815: 	'</h4>'."\n";
  816: 
  817:     my ($string,$contents,$matches) = ('','',0);
  818:     my (undef,undef,$fullname) = &getclasslist('all','0');
  819:     
  820:     my $receiptparts=0;
  821:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  822: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  823:     my $parts=['0'];
  824:     if ($receiptparts) {
  825:         my $res_error; 
  826:         ($parts)=&response_type($symb,\$res_error);
  827:         if ($res_error) {
  828:             return &navmap_errormsg();
  829:         } 
  830:     }
  831:     
  832:     my $header = 
  833: 	&Apache::loncommon::start_data_table().
  834: 	&Apache::loncommon::start_data_table_header_row().
  835: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  836: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  837: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  838:     if ($receiptparts) {
  839: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  840:     }
  841:     $header.=
  842: 	&Apache::loncommon::end_data_table_header_row();
  843: 
  844:     foreach (sort 
  845: 	     {
  846: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  847: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  848: 		 }
  849: 		 return $a cmp $b;
  850: 	     } (keys(%$fullname))) {
  851: 	my ($uname,$udom)=split(/\:/);
  852: 	foreach my $part (@$parts) {
  853: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  854: 		$contents.=
  855: 		    &Apache::loncommon::start_data_table_row().
  856: 		    '<td>&nbsp;'."\n".
  857: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  858: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  859: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  860: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  861: 		if ($receiptparts) {
  862: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  863: 		}
  864: 		$contents.= 
  865: 		    &Apache::loncommon::end_data_table_row()."\n";
  866: 		
  867: 		$matches++;
  868: 	    }
  869: 	}
  870:     }
  871:     if ($matches == 0) {
  872:         $string = $title
  873:                  .'<p class="LC_warning">'
  874:                  .&mt('No match found for the above receipt number.')
  875:                  .'</p>';
  876:     } else {
  877: 	$string = &jscriptNform($symb).$title.
  878: 	    '<p>'.
  879: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  880: 	    '</p>'.
  881: 	    $header.
  882: 	    $contents.
  883: 	    &Apache::loncommon::end_data_table()."\n";
  884:     }
  885:     return $string.&show_grading_menu_form($symb);
  886: }
  887: 
  888: #--- This is called by a number of programs.
  889: #--- Called from the Grading Menu - View/Grade an individual student
  890: #--- Also called directly when one clicks on the subm button 
  891: #    on the problem page.
  892: sub listStudents {
  893:     my ($request) = shift;
  894: 
  895:     my ($symb) = &get_symb($request);
  896:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  897:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  898:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  899:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  900:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  901:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  902:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  903: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  904: 
  905:     my $result='<h3><span class="LC_info">&nbsp;'
  906: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  907: 	.'</span></h3>';
  908: 
  909:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  910: 
  911:     my %lt = &Apache::lonlocal::texthash (
  912: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  913: 		'single'   => 'Please select the student before clicking on the Next button.',
  914: 	     );
  915:     $request->print(<<LISTJAVASCRIPT);
  916: <script type="text/javascript" language="javascript">
  917:     function checkSelect(checkBox) {
  918: 	var ctr=0;
  919: 	var sense="";
  920: 	if (checkBox.length > 1) {
  921: 	    for (var i=0; i<checkBox.length; i++) {
  922: 		if (checkBox[i].checked) {
  923: 		    ctr++;
  924: 		}
  925: 	    }
  926: 	    sense = '$lt{'multiple'}';
  927: 	} else {
  928: 	    if (checkBox.checked) {
  929: 		ctr = 1;
  930: 	    }
  931: 	    sense = '$lt{'single'}';
  932: 	}
  933: 	if (ctr == 0) {
  934: 	    alert(sense);
  935: 	    return false;
  936: 	}
  937: 	document.gradesub.submit();
  938:     }
  939: 
  940:     function reLoadList(formname) {
  941: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  942: 	formname.command.value = 'submission';
  943: 	formname.submit();
  944:     }
  945: </script>
  946: LISTJAVASCRIPT
  947: 
  948:     &commonJSfunctions($request);
  949:     $request->print($result);
  950: 
  951:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  952:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  953:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  954: 	"\n".$table;
  955: 	
  956:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  957:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  958:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  959:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  960:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  961:                   .&Apache::lonhtmlcommon::row_closure();
  962:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  963:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  964:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  965:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  966:                   .&Apache::lonhtmlcommon::row_closure();
  967: 
  968:     my $submission_options;
  969:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  970: 	$submission_options.=
  971: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  972:     }
  973:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  974:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  975:     $env{'form.Status'} = $saveStatus;
  976:     $submission_options.=
  977:         '<span class="LC_nobreak">'.
  978:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  979:         &mt('last submission only').' </label></span>'."\n".
  980:         '<span class="LC_nobreak">'.
  981:         '<label><input type="radio" name="lastSub" value="last" /> '.
  982:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  983:         '<span class="LC_nobreak">'.
  984:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  985:         &mt('by dates and submissions').'</label></span>'."\n".
  986:         '<span class="LC_nobreak">'.
  987:         '<label><input type="radio" name="lastSub" value="all" /> '.
  988:         &mt('all details').'</label></span>';
  989:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  990:                   .$submission_options
  991:                   .&Apache::lonhtmlcommon::row_closure();
  992: 
  993:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  994:                   .'<select name="increment">'
  995:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  996:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  997:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  998:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  999:                   .'</select>'
 1000:                   .&Apache::lonhtmlcommon::row_closure();
 1001: 
 1002:     $gradeTable .= 
 1003:         &build_section_inputs().
 1004: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1005: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1006: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1007: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1008: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1009: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1010: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1011: 
 1012:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1013: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1014:     } else {
 1015:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1016:                       .&Apache::lonhtmlcommon::StatusOptions(
 1017:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1018:                       .&Apache::lonhtmlcommon::row_closure();
 1019:     }
 1020: 
 1021:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1022:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1023:                   .&Apache::lonhtmlcommon::row_closure(1)
 1024:                   .&Apache::lonhtmlcommon::end_pick_box();
 1025: 
 1026:     $gradeTable .= '<p>'
 1027:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
 1028:                   .'<input type="hidden" name="command" value="processGroup" />'
 1029:                   .'</p>';
 1030: 
 1031: # checkall buttons
 1032:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1033:     $gradeTable.='<input type="button" '."\n".
 1034:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1035:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1036:     $gradeTable.=&check_buttons();
 1037:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1038:     $gradeTable.= &Apache::loncommon::start_data_table().
 1039: 	&Apache::loncommon::start_data_table_header_row();
 1040:     my $loop = 0;
 1041:     while ($loop < 2) {
 1042: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1043: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1044: 	if ($env{'form.showgrading'} eq 'yes' 
 1045: 	    && $submitonly ne 'queued'
 1046: 	    && $submitonly ne 'all') {
 1047: 	    foreach my $part (sort(@$partlist)) {
 1048: 		my $display_part=
 1049: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1050: 		$gradeTable.=
 1051: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1052: 	    }
 1053: 	} elsif ($submitonly eq 'queued') {
 1054: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1055: 	}
 1056: 	$loop++;
 1057: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1058:     }
 1059:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1060: 
 1061:     my $ctr = 0;
 1062:     foreach my $student (sort 
 1063: 			 {
 1064: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1065: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1066: 			     }
 1067: 			     return $a cmp $b;
 1068: 			 }
 1069: 			 (keys(%$fullname))) {
 1070: 	my ($uname,$udom) = split(/:/,$student);
 1071: 
 1072: 	my %status = ();
 1073: 
 1074: 	if ($submitonly eq 'queued') {
 1075: 	    my %queue_status = 
 1076: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1077: 							$udom,$uname);
 1078: 	    next if (!defined($queue_status{'gradingqueue'}));
 1079: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1080: 	}
 1081: 
 1082: 	if ($env{'form.showgrading'} eq 'yes' 
 1083: 	    && $submitonly ne 'queued'
 1084: 	    && $submitonly ne 'all') {
 1085: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1086: 	    my $submitted = 0;
 1087: 	    my $graded = 0;
 1088: 	    my $incorrect = 0;
 1089: 	    foreach (keys(%status)) {
 1090: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1091: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1092: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1093: 		
 1094: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1095: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1096: 		    $submitted = 0;
 1097: 		    my ($part)=split(/\./,$partid);
 1098: 		    $gradeTable.='<input type="hidden" name="'.
 1099: 			$student.':'.$part.':submitted_by" value="'.
 1100: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1101: 		}
 1102: 	    }
 1103: 	    
 1104: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1105: 				     $submitonly eq 'incorrect' ||
 1106: 				     $submitonly eq 'graded'));
 1107: 	    next if (!$graded && ($submitonly eq 'graded'));
 1108: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1109: 	}
 1110: 
 1111: 	$ctr++;
 1112: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1113:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1114: 	if ( $perm{'vgr'} eq 'F' ) {
 1115: 	    if ($ctr%2 ==1) {
 1116: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1117: 	    }
 1118: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1119:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1120:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1121: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1122: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1123: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1124: 
 1125: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1126: 		foreach (sort(keys(%status))) {
 1127: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1128: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1129: 		}
 1130: 	    }
 1131: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1132: 	    if ($ctr%2 ==0) {
 1133: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1134: 	    }
 1135: 	}
 1136:     }
 1137:     if ($ctr%2 ==1) {
 1138: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1139: 	    if ($env{'form.showgrading'} eq 'yes' 
 1140: 		&& $submitonly ne 'queued'
 1141: 		&& $submitonly ne 'all') {
 1142: 		foreach (@$partlist) {
 1143: 		    $gradeTable.='<td>&nbsp;</td>';
 1144: 		}
 1145: 	    } elsif ($submitonly eq 'queued') {
 1146: 		$gradeTable.='<td>&nbsp;</td>';
 1147: 	    }
 1148: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1149:     }
 1150: 
 1151:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1152:         '<input type="button" '.
 1153:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1154:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1155:     if ($ctr == 0) {
 1156: 	my $num_students=(scalar(keys(%$fullname)));
 1157: 	if ($num_students eq 0) {
 1158: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1159: 	} else {
 1160: 	    my $submissions='submissions';
 1161: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1162: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1163: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1164: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1165: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1166: 		    $num_students).
 1167: 		'</span><br />';
 1168: 	}
 1169:     } elsif ($ctr == 1) {
 1170: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1171:     }
 1172:     $gradeTable.=&show_grading_menu_form($symb);
 1173:     $request->print($gradeTable);
 1174:     return '';
 1175: }
 1176: 
 1177: #---- Called from the listStudents routine
 1178: 
 1179: sub check_script {
 1180:     my ($form, $type)=@_;
 1181:     my $chkallscript='<script type="text/javascript">
 1182:     function checkall() {
 1183:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1184:             ele = document.forms.'.$form.'.elements[i];
 1185:             if (ele.name == "'.$type.'") {
 1186:             document.forms.'.$form.'.elements[i].checked=true;
 1187:                                        }
 1188:         }
 1189:     }
 1190: 
 1191:     function checksec() {
 1192:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1193:             ele = document.forms.'.$form.'.elements[i];
 1194:            string = document.forms.'.$form.'.chksec.value;
 1195:            if
 1196:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1197:               document.forms.'.$form.'.elements[i].checked=true;
 1198:             }
 1199:         }
 1200:     }
 1201: 
 1202: 
 1203:     function uncheckall() {
 1204:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1205:             ele = document.forms.'.$form.'.elements[i];
 1206:             if (ele.name == "'.$type.'") {
 1207:             document.forms.'.$form.'.elements[i].checked=false;
 1208:                                        }
 1209:         }
 1210:     }
 1211: 
 1212: </script>'."\n";
 1213:     return $chkallscript;
 1214: }
 1215: 
 1216: sub check_buttons {
 1217:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1218:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1219:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1220:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1221:     return $buttons;
 1222: }
 1223: 
 1224: #     Displays the submissions for one student or a group of students
 1225: sub processGroup {
 1226:     my ($request)  = shift;
 1227:     my $ctr        = 0;
 1228:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1229:     my $total      = scalar(@stuchecked)-1;
 1230: 
 1231:     foreach my $student (@stuchecked) {
 1232: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1233: 	$env{'form.student'}        = $uname;
 1234: 	$env{'form.userdom'}        = $udom;
 1235: 	$env{'form.fullname'}       = $fullname;
 1236: 	&submission($request,$ctr,$total);
 1237: 	$ctr++;
 1238:     }
 1239:     return '';
 1240: }
 1241: 
 1242: #------------------------------------------------------------------------------------
 1243: #
 1244: #-------------------------- Next few routines handles grading by student, essentially
 1245: #                           handles essay response type problem/part
 1246: #
 1247: #--- Javascript to handle the submission page functionality ---
 1248: sub sub_page_js {
 1249:     my $request = shift;
 1250: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1251:     $request->print(<<SUBJAVASCRIPT);
 1252: <script type="text/javascript" language="javascript">
 1253:     function updateRadio(formname,id,weight) {
 1254: 	var gradeBox = formname["GD_BOX"+id];
 1255: 	var radioButton = formname["RADVAL"+id];
 1256: 	var oldpts = formname["oldpts"+id].value;
 1257: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1258: 	gradeBox.value = pts;
 1259: 	var resetbox = false;
 1260: 	if (isNaN(pts) || pts < 0) {
 1261: 	    alert("$alertmsg"+pts);
 1262: 	    for (var i=0; i<radioButton.length; i++) {
 1263: 		if (radioButton[i].checked) {
 1264: 		    gradeBox.value = i;
 1265: 		    resetbox = true;
 1266: 		}
 1267: 	    }
 1268: 	    if (!resetbox) {
 1269: 		formtextbox.value = "";
 1270: 	    }
 1271: 	    return;
 1272: 	}
 1273: 
 1274: 	if (pts > weight) {
 1275: 	    var resp = confirm("You entered a value ("+pts+
 1276: 			       ") greater than the weight for the part. Accept?");
 1277: 	    if (resp == false) {
 1278: 		gradeBox.value = oldpts;
 1279: 		return;
 1280: 	    }
 1281: 	}
 1282: 
 1283: 	for (var i=0; i<radioButton.length; i++) {
 1284: 	    radioButton[i].checked=false;
 1285: 	    if (pts == i && pts != "") {
 1286: 		radioButton[i].checked=true;
 1287: 	    }
 1288: 	}
 1289: 	updateSelect(formname,id);
 1290: 	formname["stores"+id].value = "0";
 1291:     }
 1292: 
 1293:     function writeBox(formname,id,pts) {
 1294: 	var gradeBox = formname["GD_BOX"+id];
 1295: 	if (checkSolved(formname,id) == 'update') {
 1296: 	    gradeBox.value = pts;
 1297: 	} else {
 1298: 	    var oldpts = formname["oldpts"+id].value;
 1299: 	    gradeBox.value = oldpts;
 1300: 	    var radioButton = formname["RADVAL"+id];
 1301: 	    for (var i=0; i<radioButton.length; i++) {
 1302: 		radioButton[i].checked=false;
 1303: 		if (i == oldpts) {
 1304: 		    radioButton[i].checked=true;
 1305: 		}
 1306: 	    }
 1307: 	}
 1308: 	formname["stores"+id].value = "0";
 1309: 	updateSelect(formname,id);
 1310: 	return;
 1311:     }
 1312: 
 1313:     function clearRadBox(formname,id) {
 1314: 	if (checkSolved(formname,id) == 'noupdate') {
 1315: 	    updateSelect(formname,id);
 1316: 	    return;
 1317: 	}
 1318: 	gradeSelect = formname["GD_SEL"+id];
 1319: 	for (var i=0; i<gradeSelect.length; i++) {
 1320: 	    if (gradeSelect[i].selected) {
 1321: 		var selectx=i;
 1322: 	    }
 1323: 	}
 1324: 	var stores = formname["stores"+id];
 1325: 	if (selectx == stores.value) { return };
 1326: 	var gradeBox = formname["GD_BOX"+id];
 1327: 	gradeBox.value = "";
 1328: 	var radioButton = formname["RADVAL"+id];
 1329: 	for (var i=0; i<radioButton.length; i++) {
 1330: 	    radioButton[i].checked=false;
 1331: 	}
 1332: 	stores.value = selectx;
 1333:     }
 1334: 
 1335:     function checkSolved(formname,id) {
 1336: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1337: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1338: 	    if (!reply) {return "noupdate";}
 1339: 	    formname.overRideScore.value = 'yes';
 1340: 	}
 1341: 	return "update";
 1342:     }
 1343: 
 1344:     function updateSelect(formname,id) {
 1345: 	formname["GD_SEL"+id][0].selected = true;
 1346: 	return;
 1347:     }
 1348: 
 1349: //=========== Check that a point is assigned for all the parts  ============
 1350:     function checksubmit(formname,val,total,parttot) {
 1351: 	formname.gradeOpt.value = val;
 1352: 	if (val == "Save & Next") {
 1353: 	    for (i=0;i<=total;i++) {
 1354: 		for (j=0;j<parttot;j++) {
 1355: 		    var partid = formname["partid"+i+"_"+j].value;
 1356: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1357: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1358: 			if (points == "") {
 1359: 			    var name = formname["name"+i].value;
 1360: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1361: 			    var resp = confirm("You did not assign a score for "+studentID+
 1362: 					       ", part "+partid+". Continue?");
 1363: 			    if (resp == false) {
 1364: 				formname["GD_BOX"+i+"_"+partid].focus();
 1365: 				return false;
 1366: 			    }
 1367: 			}
 1368: 		    }
 1369: 		    
 1370: 		}
 1371: 	    }
 1372: 	    
 1373: 	}
 1374: 	if (val == "Grade Student") {
 1375: 	    formname.showgrading.value = "yes";
 1376: 	    if (formname.Status.value == "") {
 1377: 		formname.Status.value = "Active";
 1378: 	    }
 1379: 	    formname.studentNo.value = total;
 1380: 	}
 1381: 	formname.submit();
 1382:     }
 1383: 
 1384: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1385:     function checkSubmitPage(formname,total) {
 1386: 	noscore = new Array(100);
 1387: 	var ptr = 0;
 1388: 	for (i=1;i<total;i++) {
 1389: 	    var partid = formname["q_"+i].value;
 1390: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1391: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1392: 		var status = formname["solved"+i+"_"+partid].value;
 1393: 		if (points == "" && status != "correct_by_student") {
 1394: 		    noscore[ptr] = i;
 1395: 		    ptr++;
 1396: 		}
 1397: 	    }
 1398: 	}
 1399: 	if (ptr != 0) {
 1400: 	    var sense = ptr == 1 ? ": " : "s: ";
 1401: 	    var prolist = "";
 1402: 	    if (ptr == 1) {
 1403: 		prolist = noscore[0];
 1404: 	    } else {
 1405: 		var i = 0;
 1406: 		while (i < ptr-1) {
 1407: 		    prolist += noscore[i]+", ";
 1408: 		    i++;
 1409: 		}
 1410: 		prolist += "and "+noscore[i];
 1411: 	    }
 1412: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1413: 	    if (resp == false) {
 1414: 		return false;
 1415: 	    }
 1416: 	}
 1417: 
 1418: 	formname.submit();
 1419:     }
 1420: </script>
 1421: SUBJAVASCRIPT
 1422: }
 1423: 
 1424: #--- javascript for essay type problem --
 1425: sub sub_page_kw_js {
 1426:     my $request = shift;
 1427:     my $iconpath = $request->dir_config('lonIconsURL');
 1428:     &commonJSfunctions($request);
 1429: 
 1430:     my $inner_js_msg_central=<<INNERJS;
 1431:     <script text="text/javascript">
 1432:     function checkInput() {
 1433:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1434:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1435:       var usrctr = document.msgcenter.usrctr.value;
 1436:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1437:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1438: 
 1439:       var msgchk = "";
 1440:       if (document.msgcenter.subchk.checked) {
 1441:          msgchk = "msgsub,";
 1442:       }
 1443:       var includemsg = 0;
 1444:       for (var i=1; i<=nmsg; i++) {
 1445:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1446:           var frmmsg = document.msgcenter["msg"+i];
 1447:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1448:           var showflg = opener.document.SCORE["shownOnce"+i];
 1449:           showflg.value = "1";
 1450:           var chkbox = document.msgcenter["msgn"+i];
 1451:           if (chkbox.checked) {
 1452:              msgchk += "savemsg"+i+",";
 1453:              includemsg = 1;
 1454:           }
 1455:       }
 1456:       if (document.msgcenter.newmsgchk.checked) {
 1457:          msgchk += "newmsg"+usrctr;
 1458:          includemsg = 1;
 1459:       }
 1460:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1461:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1462:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1463:       includemsg.value = msgchk;
 1464: 
 1465:       self.close()
 1466: 
 1467:     }
 1468:     </script>
 1469: INNERJS
 1470: 
 1471:     my $inner_js_highlight_central=<<INNERJS;
 1472:  <script type="text/javascript">
 1473:     function updateChoice(flag) {
 1474:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1475:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1476:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1477:       opener.document.SCORE.refresh.value = "on";
 1478:       if (opener.document.SCORE.keywords.value!=""){
 1479:          opener.document.SCORE.submit();
 1480:       }
 1481:       self.close()
 1482:     }
 1483: </script>
 1484: INNERJS
 1485: 
 1486:     my $start_page_msg_central = 
 1487:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1488: 				       {'js_ready'  => 1,
 1489: 					'only_body' => 1,
 1490: 					'bgcolor'   =>'#FFFFFF',});
 1491:     my $end_page_msg_central = 
 1492: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1493: 
 1494: 
 1495:     my $start_page_highlight_central = 
 1496:         &Apache::loncommon::start_page('Highlight Central',
 1497: 				       $inner_js_highlight_central,
 1498: 				       {'js_ready'  => 1,
 1499: 					'only_body' => 1,
 1500: 					'bgcolor'   =>'#FFFFFF',});
 1501:     my $end_page_highlight_central = 
 1502: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1503: 
 1504:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1505:     $docopen=~s/^document\.//;
 1506:     my %lt = &Apache::lonlocal::texthash(
 1507:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1508:                 plse => 'Please select a word or group of words from document and then click this link.',
 1509:                 adds => 'Add selection to keyword list? Edit if desired.',
 1510:                 comp => 'Compose Message for: ',
 1511:                 incl => 'Include',
 1512:                 type => 'Type',
 1513:                 subj => 'Subject',
 1514:                 mesa => 'Message',
 1515:                 new  => 'New',
 1516:                 save => 'Save',
 1517:                 canc => 'Cancel',
 1518:                 kehi => 'Keyword Highlight Options',
 1519:                 txtc => 'Text Color',
 1520:                 font => 'Font Size',
 1521:                 fnst => 'Font Style',
 1522:              );
 1523:     $request->print(<<SUBJAVASCRIPT);
 1524: <script type="text/javascript" language="javascript">
 1525: 
 1526: //===================== Show list of keywords ====================
 1527:   function keywords(formname) {
 1528:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1529:     if (nret==null) return;
 1530:     formname.keywords.value = nret;
 1531: 
 1532:     if (formname.keywords.value != "") {
 1533: 	formname.refresh.value = "on";
 1534: 	formname.submit();
 1535:     }
 1536:     return;
 1537:   }
 1538: 
 1539: //===================== Script to view submitted by ==================
 1540:   function viewSubmitter(submitter) {
 1541:     document.SCORE.refresh.value = "on";
 1542:     document.SCORE.NCT.value = "1";
 1543:     document.SCORE.unamedom0.value = submitter;
 1544:     document.SCORE.submit();
 1545:     return;
 1546:   }
 1547: 
 1548: //===================== Script to add keyword(s) ==================
 1549:   function getSel() {
 1550:     if (document.getSelection) txt = document.getSelection();
 1551:     else if (document.selection) txt = document.selection.createRange().text;
 1552:     else return;
 1553:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1554:     if (cleantxt=="") {
 1555: 	alert("$lt{'plse'}");
 1556: 	return;
 1557:     }
 1558:     var nret = prompt("$lt{'adds'}",cleantxt);
 1559:     if (nret==null) return;
 1560:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1561:     if (document.SCORE.keywords.value != "") {
 1562: 	document.SCORE.refresh.value = "on";
 1563: 	document.SCORE.submit();
 1564:     }
 1565:     return;
 1566:   }
 1567: 
 1568: //====================== Script for composing message ==============
 1569:    // preload images
 1570:    img1 = new Image();
 1571:    img1.src = "$iconpath/mailbkgrd.gif";
 1572:    img2 = new Image();
 1573:    img2.src = "$iconpath/mailto.gif";
 1574: 
 1575:   function msgCenter(msgform,usrctr,fullname) {
 1576:     var Nmsg  = msgform.savemsgN.value;
 1577:     savedMsgHeader(Nmsg,usrctr,fullname);
 1578:     var subject = msgform.msgsub.value;
 1579:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1580:     re = /msgsub/;
 1581:     var shwsel = "";
 1582:     if (re.test(msgchk)) { shwsel = "checked" }
 1583:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1584:     displaySubject(checkEntities(subject),shwsel);
 1585:     for (var i=1; i<=Nmsg; i++) {
 1586: 	var testmsg = "savemsg"+i+",";
 1587: 	re = new RegExp(testmsg,"g");
 1588: 	shwsel = "";
 1589: 	if (re.test(msgchk)) { shwsel = "checked" }
 1590: 	var message = document.SCORE["savemsg"+i].value;
 1591: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1592: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1593: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1594:     }
 1595:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1596:     shwsel = "";
 1597:     re = /newmsg/;
 1598:     if (re.test(msgchk)) { shwsel = "checked" }
 1599:     newMsg(newmsg,shwsel);
 1600:     msgTail(); 
 1601:     return;
 1602:   }
 1603: 
 1604:   function checkEntities(strx) {
 1605:     if (strx.length == 0) return strx;
 1606:     var orgStr = ["&", "<", ">", '"']; 
 1607:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1608:     var counter = 0;
 1609:     while (counter < 4) {
 1610: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1611: 	counter++;
 1612:     }
 1613:     return strx;
 1614:   }
 1615: 
 1616:   function strReplace(strx, orgStr, newStr) {
 1617:     return strx.split(orgStr).join(newStr);
 1618:   }
 1619: 
 1620:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1621:     var height = 70*Nmsg+250;
 1622:     if (height > 600) {
 1623: 	height = 600;
 1624:     }
 1625:     var xpos = (screen.width-600)/2;
 1626:     xpos = (xpos < 0) ? '0' : xpos;
 1627:     var ypos = (screen.height-height)/2-30;
 1628:     ypos = (ypos < 0) ? '0' : ypos;
 1629: 
 1630:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1631:     pWin.focus();
 1632:     pDoc = pWin.document;
 1633:     pDoc.$docopen;
 1634:     pDoc.write('$start_page_msg_central');
 1635: 
 1636:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1637:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1638:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1639: 
 1640:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1641:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1642:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1643: }
 1644:     function displaySubject(msg,shwsel) {
 1645:     pDoc = pWin.document;
 1646:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1647:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1648:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1649:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1650: }
 1651: 
 1652:   function displaySavedMsg(ctr,msg,shwsel) {
 1653:     pDoc = pWin.document;
 1654:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1655:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1656:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1657:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1658: }
 1659: 
 1660:   function newMsg(newmsg,shwsel) {
 1661:     pDoc = pWin.document;
 1662:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1663:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1664:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1665:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1666: }
 1667: 
 1668:   function msgTail() {
 1669:     pDoc = pWin.document;
 1670:     pDoc.write("<\\/table>");
 1671:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1672:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1673:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1674:     pDoc.write("<\\/form>");
 1675:     pDoc.write('$end_page_msg_central');
 1676:     pDoc.close();
 1677: }
 1678: 
 1679: //====================== Script for keyword highlight options ==============
 1680:   function kwhighlight() {
 1681:     var kwclr    = document.SCORE.kwclr.value;
 1682:     var kwsize   = document.SCORE.kwsize.value;
 1683:     var kwstyle  = document.SCORE.kwstyle.value;
 1684:     var redsel = "";
 1685:     var grnsel = "";
 1686:     var blusel = "";
 1687:     if (kwclr=="red")   {var redsel="checked"};
 1688:     if (kwclr=="green") {var grnsel="checked"};
 1689:     if (kwclr=="blue")  {var blusel="checked"};
 1690:     var sznsel = "";
 1691:     var sz1sel = "";
 1692:     var sz2sel = "";
 1693:     if (kwsize=="0")  {var sznsel="checked"};
 1694:     if (kwsize=="+1") {var sz1sel="checked"};
 1695:     if (kwsize=="+2") {var sz2sel="checked"};
 1696:     var synsel = "";
 1697:     var syisel = "";
 1698:     var sybsel = "";
 1699:     if (kwstyle=="")    {var synsel="checked"};
 1700:     if (kwstyle=="<i>") {var syisel="checked"};
 1701:     if (kwstyle=="<b>") {var sybsel="checked"};
 1702:     highlightCentral();
 1703:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1704:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1705:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1706:     highlightend();
 1707:     return;
 1708:   }
 1709: 
 1710:   function highlightCentral() {
 1711: //    if (window.hwdWin) window.hwdWin.close();
 1712:     var xpos = (screen.width-400)/2;
 1713:     xpos = (xpos < 0) ? '0' : xpos;
 1714:     var ypos = (screen.height-330)/2-30;
 1715:     ypos = (ypos < 0) ? '0' : ypos;
 1716: 
 1717:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1718:     hwdWin.focus();
 1719:     var hDoc = hwdWin.document;
 1720:     hDoc.$docopen;
 1721:     hDoc.write('$start_page_highlight_central');
 1722:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1723:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1724: 
 1725:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1726:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1727:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
 1728:   }
 1729: 
 1730:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1731:     var hDoc = hwdWin.document;
 1732:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1733:     hDoc.write("<td align=\\"left\\">");
 1734:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1735:     hDoc.write("<td align=\\"left\\">");
 1736:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1737:     hDoc.write("<td align=\\"left\\">");
 1738:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1739:     hDoc.write("<\\/tr>");
 1740:   }
 1741: 
 1742:   function highlightend() { 
 1743:     var hDoc = hwdWin.document;
 1744:     hDoc.write("<\\/table>");
 1745:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1746:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1747:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1748:     hDoc.write("<\\/form>");
 1749:     hDoc.write('$end_page_highlight_central');
 1750:     hDoc.close();
 1751:   }
 1752: 
 1753: </script>
 1754: SUBJAVASCRIPT
 1755: }
 1756: 
 1757: sub get_increment {
 1758:     my $increment = $env{'form.increment'};
 1759:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1760:         $increment != .1) {
 1761:         $increment = 1;
 1762:     }
 1763:     return $increment;
 1764: }
 1765: 
 1766: sub gradeBox_start {
 1767:     return (
 1768:         &Apache::loncommon::start_data_table()
 1769:        .&Apache::loncommon::start_data_table_header_row()
 1770:        .'<th>'.&mt('Part').'</th>'
 1771:        .'<th>'.&mt('Points').'</th>'
 1772:        .'<th>&nbsp;</th>'
 1773:        .'<th>'.&mt('Assign Grade').'</th>'
 1774:        .'<th>'.&mt('Weight').'</th>'
 1775:        .'<th>'.&mt('Grade Status').'</th>'
 1776:        .&Apache::loncommon::end_data_table_header_row()
 1777:     );
 1778: }
 1779: 
 1780: sub gradeBox_end {
 1781:     return (
 1782:         &Apache::loncommon::end_data_table()
 1783:     );
 1784: }
 1785: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1786: sub gradeBox {
 1787:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1788:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1789: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1790:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1791:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1792:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1793:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1794:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1795: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1796:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1797:     my $display_part= &get_display_part($partid,$symb);
 1798:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1799: 				       [$partid]);
 1800:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1801:     if ($last_resets{$partid}) {
 1802:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1803:     }
 1804:     my $result=&Apache::loncommon::start_data_table_row();
 1805:     my $ctr = 0;
 1806:     my $thisweight = 0;
 1807:     my $increment = &get_increment();
 1808: 
 1809:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1810:     while ($thisweight<=$wgt) {
 1811: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1812:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1813: 	    $thisweight.')" value="'.$thisweight.'" '.
 1814: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1815: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1816:         $thisweight += $increment;
 1817: 	$ctr++;
 1818:     }
 1819:     $radio.='</tr></table>';
 1820: 
 1821:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1822: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1823: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1824: 	$wgt.')" /></td>'."\n";
 1825:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1826: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1827: 	' </td>'."\n";
 1828:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1829: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1830:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1831: 	$line.='<option></option>'.
 1832: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1833:     } else {
 1834: 	$line.='<option selected="selected"></option>'.
 1835: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1836:     }
 1837:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1838: 
 1839: 
 1840:     $result .= 
 1841: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1842:     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
 1843:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1844: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1845: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1846: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1847:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1848:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1849:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1850:         $aggtries.'" />'."\n";
 1851:     my $res_error;
 1852:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1853:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1854:     if ($res_error) {
 1855:         return &navmap_errormsg();
 1856:     }
 1857:     return $result;
 1858: }
 1859: 
 1860: sub handback_box {
 1861:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1862:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1863:     my (@respids);
 1864:     my @part_response_id = &flatten_responseType($responseType);
 1865:     foreach my $part_response_id (@part_response_id) {
 1866:     	my ($part,$resp) = @{ $part_response_id };
 1867:         if ($part eq $partid) {
 1868:             push(@respids,$resp);
 1869:         }
 1870:     }
 1871:     my $result;
 1872:     foreach my $respid (@respids) {
 1873: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1874: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1875: 	next if (!@$files);
 1876: 	my $file_counter = 0;
 1877: 	foreach my $file (@$files) {
 1878: 	    if ($file =~ /\/portfolio\//) {
 1879:                 $file_counter++;
 1880:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1881:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1882:     	        $file_disp = "$name.$ext";
 1883:     	        $file = $file_path.$file_disp;
 1884:     	        $result.=&mt('Return commented version of [_1] to student.',
 1885:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1886:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1887:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1888: 	    }
 1889: 	}
 1890:         if ($file_counter) {
 1891:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1892:                        '<span class="LC_info">'.
 1893:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1894:         }
 1895:     }
 1896:     return $result;    
 1897: }
 1898: 
 1899: sub show_problem {
 1900:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1901:     my $rendered;
 1902:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1903:     &Apache::lonxml::remember_problem_counter();
 1904:     if ($mode eq 'both' or $mode eq 'text') {
 1905: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1906: 						       $env{'request.course.id'},
 1907: 						       undef,\%form);
 1908:     }
 1909:     if ($removeform) {
 1910: 	$rendered=~s|<form(.*?)>||g;
 1911: 	$rendered=~s|</form>||g;
 1912: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1913:     }
 1914:     my $companswer;
 1915:     if ($mode eq 'both' or $mode eq 'answer') {
 1916: 	&Apache::lonxml::restore_problem_counter();
 1917: 	$companswer=
 1918: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1919: 						    $env{'request.course.id'},
 1920: 						    %form);
 1921:     }
 1922:     if ($removeform) {
 1923: 	$companswer=~s|<form(.*?)>||g;
 1924: 	$companswer=~s|</form>||g;
 1925: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1926:     }
 1927:     my $renderheading = &mt('View of the problem');
 1928:     my $answerheading = &mt('Correct answer');
 1929:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1930:         my $stu_fullname = $env{'form.fullname'};
 1931:         if ($stu_fullname eq '') {
 1932:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1933:         }
 1934:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1935:         if ($forwhom ne '') {
 1936:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1937:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1938:         }
 1939:     }
 1940:     $rendered=
 1941:         '<div class="LC_Box">'
 1942:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1943:        .$rendered
 1944:        .'</div>';
 1945:     $companswer=
 1946:         '<div class="LC_Box">'
 1947:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1948:        .$companswer
 1949:        .'</div>';
 1950:     my $result;
 1951:     if ($mode eq 'both') {
 1952:         $result=$rendered.$companswer;
 1953:     } elsif ($mode eq 'text') {
 1954:         $result=$rendered;
 1955:     } elsif ($mode eq 'answer') {
 1956:         $result=$companswer;
 1957:     }
 1958:     return $result;
 1959: }
 1960: 
 1961: sub files_exist {
 1962:     my ($r, $symb) = @_;
 1963:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1964: 
 1965:     foreach my $student (@students) {
 1966:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1967:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1968: 					      $udom,$uname);
 1969:         my ($string,$timestamp)= &get_last_submission(\%record);
 1970:         foreach my $submission (@$string) {
 1971:             my ($partid,$respid) =
 1972: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1973:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1974: 					   \%record);
 1975:             return 1 if (@$files);
 1976:         }
 1977:     }
 1978:     return 0;
 1979: }
 1980: 
 1981: sub download_all_link {
 1982:     my ($r,$symb) = @_;
 1983:     my $all_students = 
 1984: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1985: 
 1986:     my $parts =
 1987: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1988: 
 1989:     my $identifier = &Apache::loncommon::get_cgi_id();
 1990:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1991:                              'cgi.'.$identifier.'.symb' => $symb,
 1992:                              'cgi.'.$identifier.'.parts' => $parts,});
 1993:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1994: 	      &mt('Download All Submitted Documents').'</a>');
 1995:     return
 1996: }
 1997: 
 1998: sub build_section_inputs {
 1999:     my $section_inputs;
 2000:     if ($env{'form.section'} eq '') {
 2001:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2002:     } else {
 2003:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2004:         foreach my $section (@sections) {
 2005:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2006:         }
 2007:     }
 2008:     return $section_inputs;
 2009: }
 2010: 
 2011: # --------------------------- show submissions of a student, option to grade 
 2012: sub submission {
 2013:     my ($request,$counter,$total) = @_;
 2014:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2015:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2016:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2017:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2018:     my ($symb) = &get_symb($request); 
 2019:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2020: 
 2021:     if (!&canview($usec)) {
 2022: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 2023: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 2024: 			$env{'request.course.id'}.')</span>');
 2025: 	$request->print(&show_grading_menu_form($symb));
 2026: 	return;
 2027:     }
 2028: 
 2029:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2030:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2031:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2032:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2033:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2034: 	'" src="'.$request->dir_config('lonIconsURL').
 2035: 	'/check.gif" height="16" border="0" />';
 2036: 
 2037:     # header info
 2038:     if ($counter == 0) {
 2039: 	&sub_page_js($request);
 2040: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2041: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2042: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2043: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2044: 	    &download_all_link($request, $symb);
 2045: 	}
 2046: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2047: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 2048: 
 2049: 	# option to display problem, only once else it cause problems 
 2050:         # with the form later since the problem has a form.
 2051: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2052: 	    my $mode;
 2053: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2054: 		$mode='both';
 2055: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2056: 		$mode='text';
 2057: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2058: 		$mode='answer';
 2059: 	    }
 2060: 	    &Apache::lonxml::clear_problem_counter();
 2061: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2062: 	}
 2063: 
 2064: 	# kwclr is the only variable that is guaranteed to be non blank 
 2065:         # if this subroutine has been called once.
 2066: 	my %keyhash = ();
 2067: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2068: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2069: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2070: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2071: 
 2072: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2073: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2074: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2075: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2076: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2077: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2078: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2079: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2080: 	}
 2081: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2082: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2083: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2084: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2085: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2086: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2087: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2088: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2089: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2090: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2091: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2092: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2093: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2094: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2095: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2096: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2097: 			&build_section_inputs().
 2098: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2099: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2100: 			'<input type="hidden" name="NCT"'.
 2101: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2102: 	if ($env{'form.handgrade'} eq 'yes') {
 2103: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2104: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2105: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2106: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2107: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2108: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2109: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2110: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2111: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2112: 	    }
 2113: 	}
 2114: 	
 2115: 	my ($cts,$prnmsg) = (1,'');
 2116: 	while ($cts <= $env{'form.savemsgN'}) {
 2117: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2118: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2119: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2120: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2121: 		'" />'."\n".
 2122: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2123: 	    $cts++;
 2124: 	}
 2125: 	$request->print($prnmsg);
 2126: 
 2127: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2128: 
 2129:             my %lt = &Apache::lonlocal::texthash(
 2130:                           keyw => 'Keyword Options',
 2131:                           list => 'List',
 2132:                           past => 'Paste Selection to List',
 2133:                           high => 'Highlight Attribute',
 2134:                      );
 2135: #
 2136: # Print out the keyword options line
 2137: #
 2138: 	    $request->print(<<KEYWORDS);
 2139: &nbsp;<b>$lt{'keyw'}:</b>&nbsp;
 2140: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2141: <a href="#" onmousedown="javascript:getSel(); return false"
 2142:  class="page">$lt{'past'}</a>&nbsp; &nbsp;
 2143: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2144: KEYWORDS
 2145: #
 2146: # Load the other essays for similarity check
 2147: #
 2148:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2149: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2150: 	    $apath=&escape($apath);
 2151: 	    $apath=~s/\W/\_/gs;
 2152:             &init_old_essays($symb,$apath,$adom,$aname);
 2153:         }
 2154:     }
 2155: 
 2156: # This is where output for one specific student would start
 2157:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2158:     $request->print(
 2159:         "\n\n"
 2160:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2161:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2162:        ."\n"
 2163:     );
 2164: 
 2165:     # Show additional functions if allowed
 2166:     if ($perm{'vgr'}) {
 2167:         $request->print(
 2168:             &Apache::loncommon::track_student_link(
 2169:                 &mt('View recent activity'),
 2170:                 $uname,$udom,'check')
 2171:            .' '
 2172:         );
 2173:     }
 2174:     if ($perm{'opa'}) {
 2175:         $request->print(
 2176:             &Apache::loncommon::pprmlink(
 2177:                 &mt('Set/Change parameters'),
 2178:                 $uname,$udom,$symb,'check'));
 2179:     }
 2180: 
 2181:     # Show Problem
 2182:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2183: 	my $mode;
 2184: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2185: 	    $mode='both';
 2186: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2187: 	    $mode='text';
 2188: 	} elsif ($env{'form.vAns'} eq 'all') {
 2189: 	    $mode='answer';
 2190: 	}
 2191: 	&Apache::lonxml::clear_problem_counter();
 2192: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2193:     }
 2194: 
 2195:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2196:     my $res_error;
 2197:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2198:     if ($res_error) {
 2199:         $request->print(&navmap_errormsg());
 2200:         return;
 2201:     }
 2202: 
 2203:     # Display student info
 2204:     $request->print(($counter == 0 ? '' : '<br />'));
 2205: 
 2206:     my $result='<div class="LC_Box">'
 2207:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2208:     $result.='<input type="hidden" name="name'.$counter.
 2209:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2210:     if ($env{'form.handgrade'} eq 'no') {
 2211:         $result.='<p class="LC_info">'
 2212:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2213:                 ."</p>\n";
 2214:     }
 2215: 
 2216:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2217:     my $fullname;
 2218:     my $col_fullnames = [];
 2219:     if ($env{'form.handgrade'} eq 'yes') {
 2220: 	(my $sub_result,$fullname,$col_fullnames)=
 2221: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2222: 				 $counter);
 2223: 	$result.=$sub_result;
 2224:     }
 2225:     $request->print($result."\n");
 2226: 
 2227:     # print student answer/submission
 2228:     # Options are (1) Handgraded submission only
 2229:     #             (2) Last submission, includes submission that is not handgraded 
 2230:     #                  (for multi-response type part)
 2231:     #             (3) Last submission plus the parts info
 2232:     #             (4) The whole record for this student
 2233:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2234: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2235: 	
 2236: 	my $lastsubonly;
 2237: 
 2238:         if ($$timestamp eq '') {
 2239:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2240:         } else {
 2241:             $lastsubonly =
 2242:                 '<div class="LC_grade_submissions_body">'
 2243:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2244: 
 2245: 	    my %seenparts;
 2246: 	    my @part_response_id = &flatten_responseType($responseType);
 2247: 	    foreach my $part (@part_response_id) {
 2248: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2249: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2250: 
 2251: 		my ($partid,$respid) = @{ $part };
 2252: 		my $display_part=&get_display_part($partid,$symb);
 2253: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2254: 		    if (exists($seenparts{$partid})) { next; }
 2255: 		    $seenparts{$partid}=1;
 2256:                     $request->print(
 2257:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2258:                         ' <b>'.&mt('Collaborative submission by: [_1]',
 2259:                                    '<a href="javascript:viewSubmitter(\''.
 2260:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
 2261:                                    '\');" target="_self">'.
 2262:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2263:                         '<br />');
 2264: 		    next;
 2265: 		}
 2266: 		my $responsetype = $responseType->{$partid}->{$respid};
 2267: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2268:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2269:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2270:                         ' <span class="LC_internal_info">'.
 2271:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2272:                         '</span>&nbsp; &nbsp;'.
 2273: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2274: 		    next;
 2275: 		}
 2276: 		foreach my $submission (@$string) {
 2277: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2278: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2279: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2280: 		    # Similarity check
 2281: 		    my $similar='';
 2282:                     my ($type,$trial,$rndseed);
 2283:                     if ($hide eq 'rand') {
 2284:                         $type = 'randomizetry';
 2285:                         $trial = $record{"resource.$partid.tries"};
 2286:                         $rndseed = $record{"resource.$partid.rndseed"};
 2287:                     }
 2288: 		    if($env{'form.checkPlag'}){
 2289: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2290: 			    &most_similar($uname,$udom,$symb,$subval);
 2291: 			if ($osim) {
 2292: 			    $osim=int($osim*100.0);
 2293: 			    my %old_course_desc = 
 2294: 				&Apache::lonnet::coursedescription($ocrsid,
 2295: 								   {'one_time' => 1});
 2296: 
 2297:                             if ($hide eq 'anon') {
 2298:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2299:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2300:                             } else {
 2301: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2302: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2303: 				        $osim,
 2304: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2305: 				        $old_course_desc{'description'},
 2306: 				        $old_course_desc{'num'},
 2307: 				        $old_course_desc{'domain'}).
 2308: 				    '</span></h3><blockquote><i>'.
 2309: 				    &keywords_highlight($oessay).
 2310: 				    '</i></blockquote><hr />';
 2311:                             }
 2312: 			}
 2313: 		    }
 2314: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2315:                                          undef,$type,$trial,$rndseed);
 2316: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2317: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2318: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2319: 			my $display_part=&get_display_part($partid,$symb);
 2320:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2321:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2322:                             ' <span class="LC_internal_info">'.
 2323:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2324:                             '</span>&nbsp; &nbsp;';
 2325: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2326: 			if (@$files) {
 2327:                             if ($hide eq 'anon') {
 2328:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2329:                             } else {
 2330:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2331:                                             .'<br /><span class="LC_warning">';
 2332:                                 if(@$files == 1) {
 2333:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2334:                                 } else {
 2335:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2336:                                 }
 2337:                                 $lastsubonly .= '</span>';
 2338: 
 2339:                                 foreach my $file (@$files) {
 2340:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2341:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2342:                                 }
 2343:                             }
 2344: 			    $lastsubonly.='<br />';
 2345: 			}
 2346:                         if ($hide eq 'anon') {
 2347:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2348:                         } else {
 2349: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
 2350: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2351: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2352:                         }
 2353: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2354: 			$lastsubonly.='</div>';
 2355: 		    }
 2356: 		}
 2357: 	    }
 2358: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2359: 	}
 2360: 	$request->print($lastsubonly);
 2361:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2362: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2363: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2364:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2365: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2366: 								 $env{'request.course.id'},
 2367: 								 $last,'.submission',
 2368: 								 'Apache::grades::keywords_highlight'));
 2369:     }
 2370: 
 2371:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2372: 	.$udom.'" />'."\n");
 2373:     # return if view submission with no grading option
 2374:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2375: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2376: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2377: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2378: 	$toGrade.='</div>'."\n";
 2379: 	if (($env{'form.command'} eq 'submission') || 
 2380: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2381: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2382: 	}
 2383: 	$request->print($toGrade);
 2384: 	return;
 2385:     } else {
 2386: 	$request->print('</div>'."\n");
 2387:     }
 2388: 
 2389:     # essay grading message center
 2390:     if ($env{'form.handgrade'} eq 'yes') {
 2391: 	my $result='<div class="LC_grade_message_center">';
 2392:     
 2393: 	$result.='<div class="LC_grade_message_center_header">'.
 2394: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2395: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2396: 	my $msgfor = $givenn.' '.$lastname;
 2397: 	if (scalar(@$col_fullnames) > 0) {
 2398: 	    my $lastone = pop(@$col_fullnames);
 2399: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2400: 	}
 2401: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2402: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2403: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2404: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2405: 	    ',\''.$msgfor.'\');" target="_self">'.
 2406: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2407: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2408: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2409: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2410: 	    '<br />&nbsp;('.
 2411: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2412: 	$result.='</div></div>';
 2413: 	$request->print($result);
 2414:     }
 2415: 
 2416:     my %seen = ();
 2417:     my @partlist;
 2418:     my @gradePartRespid;
 2419:     my @part_response_id = &flatten_responseType($responseType);
 2420:     $request->print(
 2421:         '<div class="LC_Box">'
 2422:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2423:     );
 2424:     $request->print(&gradeBox_start());
 2425:     foreach my $part_response_id (@part_response_id) {
 2426:     	my ($partid,$respid) = @{ $part_response_id };
 2427: 	my $part_resp = join('_',@{ $part_response_id });
 2428: 	next if ($seen{$partid} > 0);
 2429: 	$seen{$partid}++;
 2430: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2431: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2432: 	push(@partlist,$partid);
 2433: 	push(@gradePartRespid,$partid.'.'.$respid);
 2434: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2435:     }
 2436:     $request->print(&gradeBox_end()); # </div>
 2437:     $request->print('</div>');
 2438: 
 2439:     $request->print('<div class="LC_grade_info_links">');
 2440:     $request->print('</div>');
 2441: 
 2442:     $result='<input type="hidden" name="partlist'.$counter.
 2443: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2444:     $result.='<input type="hidden" name="gradePartRespid'.
 2445: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2446:     my $ctr = 0;
 2447:     while ($ctr < scalar(@partlist)) {
 2448: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2449: 	    $partlist[$ctr].'" />'."\n";
 2450: 	$ctr++;
 2451:     }
 2452:     $request->print($result.''."\n");
 2453: 
 2454: # Done with printing info for one student
 2455: 
 2456:     $request->print('</div>');#LC_grade_show_user
 2457: 
 2458: 
 2459:     # print end of form
 2460:     if ($counter == $total) {
 2461:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2462: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2463: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2464: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2465: 	my $ntstu ='<select name="NTSTU">'.
 2466: 	    '<option>1</option><option>2</option>'.
 2467: 	    '<option>3</option><option>5</option>'.
 2468: 	    '<option>7</option><option>10</option></select>'."\n";
 2469: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2470: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2471:         $endform.=&mt('[_1]student(s)',$ntstu);
 2472: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2473: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2474: 	    '<input type="button" value="'.&mt('Next').'" '.
 2475: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2476:         $endform.='<span class="LC_warning">'.
 2477:                   &mt('(Next and Previous (student) do not save the scores.)').
 2478:                   '</span>'."\n" ;
 2479:         $endform.="<input type='hidden' value='".&get_increment().
 2480:             "' name='increment' />";
 2481: 	$endform.='</td></tr></table></form>';
 2482: 	$endform.=&show_grading_menu_form($symb);
 2483: 	$request->print($endform);
 2484:     }
 2485:     return '';
 2486: }
 2487: 
 2488: sub check_collaborators {
 2489:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2490:     my ($result,@col_fullnames);
 2491:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2492:     foreach my $part (keys(%$handgrade)) {
 2493: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2494: 					'.maxcollaborators',
 2495: 					$symb,$udom,$uname);
 2496: 	next if ($ncol <= 0);
 2497: 	$part =~ s/\_/\./g;
 2498: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2499: 	my (@good_collaborators, @bad_collaborators);
 2500: 	foreach my $possible_collaborator
 2501: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2502: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2503: 	    next if ($possible_collaborator eq '');
 2504: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2505: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2506: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2507: 	    # Doing this grep allows 'fuzzy' specification
 2508: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2509: 			       keys(%$classlist));
 2510: 	    if (! scalar(@matches)) {
 2511: 		push(@bad_collaborators, $possible_collaborator);
 2512: 	    } else {
 2513: 		push(@good_collaborators, @matches);
 2514: 	    }
 2515: 	}
 2516: 	if (scalar(@good_collaborators) != 0) {
 2517: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2518: 	    foreach my $name (@good_collaborators) {
 2519: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2520: 		push(@col_fullnames, $givenn.' '.$lastname);
 2521: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2522: 	    }
 2523: 	    $result.='</ol><br />'."\n";
 2524: 	    my ($part)=split(/\./,$part);
 2525: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2526: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2527: 		"\n";
 2528: 	}
 2529: 	if (scalar(@bad_collaborators) > 0) {
 2530: 	    $result.='<div class="LC_warning">';
 2531: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2532: 	    $result .= '</div>';
 2533: 	}         
 2534: 	if (scalar(@bad_collaborators > $ncol)) {
 2535: 	    $result .= '<div class="LC_warning">';
 2536: 	    $result .= &mt('This student has submitted too many '.
 2537: 		'collaborators.  Maximum is [_1].',$ncol);
 2538: 	    $result .= '</div>';
 2539: 	}
 2540:     }
 2541:     return ($result,$fullname,\@col_fullnames);
 2542: }
 2543: 
 2544: #--- Retrieve the last submission for all the parts
 2545: sub get_last_submission {
 2546:     my ($returnhash)=@_;
 2547:     my (@string,$timestamp,%lasthidden);
 2548:     if ($$returnhash{'version'}) {
 2549: 	my %lasthash=();
 2550: 	my ($version);
 2551: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2552: 	    foreach my $key (sort(split(/\:/,
 2553: 					$$returnhash{$version.':keys'}))) {
 2554: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2555: 		$timestamp = 
 2556: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2557: 	    }
 2558: 	}
 2559:         my (%typeparts,%randombytry);
 2560:         my $showsurv = 
 2561:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2562:         foreach my $key (sort(keys(%lasthash))) {
 2563:             if ($key =~ /\.type$/) {
 2564:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2565:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2566:                     ($lasthash{$key} eq 'randomizetry')) {
 2567:                     my ($ign,@parts) = split(/\./,$key);
 2568:                     pop(@parts);
 2569:                     my $id = join('.',@parts);
 2570:                     if ($lasthash{$key} eq 'randomizetry') {
 2571:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2572:                     } else {
 2573:                         unless ($showsurv) {
 2574:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2575:                         }
 2576:                     }
 2577:                     delete($lasthash{$key});
 2578:                 }
 2579:             }
 2580:         }
 2581:         my @hidden = keys(%typeparts);
 2582:         my @randomize = keys(%randombytry);
 2583: 	foreach my $key (keys(%lasthash)) {
 2584: 	    next if ($key !~ /\.submission$/);
 2585:             my $hide;
 2586:             if (@hidden) {
 2587:                 foreach my $id (@hidden) {
 2588:                     if ($key =~ /^\Q$id\E/) {
 2589:                         $hide = 'anon';
 2590:                         last;
 2591:                     }
 2592:                 }
 2593:             }
 2594:             unless ($hide) {
 2595:                 if (@randomize) {
 2596:                     foreach my $id (@hidden) {
 2597:                         if ($key =~ /^\Q$id\E/) {
 2598:                             $hide = 'rand';
 2599:                             last;
 2600:                         }
 2601:                     }
 2602:                 }
 2603:             }
 2604: 	    my ($partid,$foo) = split(/submission$/,$key);
 2605: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2606: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2607: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2608: 	}
 2609:     }
 2610:     if (!@string) {
 2611: 	$string[0] =
 2612: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2613:     }
 2614:     return (\@string,\$timestamp);
 2615: }
 2616: 
 2617: #--- High light keywords, with style choosen by user.
 2618: sub keywords_highlight {
 2619:     my $string    = shift;
 2620:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2621:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2622:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2623:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2624:     foreach my $keyword (@keylist) {
 2625: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2626:     }
 2627:     return $string;
 2628: }
 2629: 
 2630: # For Tasks provide a mechanism to display previous version for one specific student
 2631: 
 2632: sub show_previous_task_version {
 2633:     my ($request,$symb) = @_;
 2634:     if ($symb eq '') {
 2635:         $request->print("Unable to handle ambiguous references.");
 2636: 
 2637:         return '';
 2638:     }
 2639:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2640:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2641:     if (!&canview($usec)) {
 2642:         $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
 2643:                         $uname.':'.$udom.' in section '.$usec.' in course id '.
 2644:                         $env{'request.course.id'}.')</span>');
 2645:         return;
 2646:     }
 2647:     my $mode = 'both';
 2648:     my $isTask = ($symb =~/\.task$/);
 2649:     if ($isTask) {
 2650:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2651:             if ($env{'form.fullname'} eq '') {
 2652:                 $env{'form.fullname'} =
 2653:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2654:             }
 2655:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2656:             $request->print("\n\n".
 2657:                             '<div class="LC_grade_show_user">'.
 2658:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2659:                             '</h2>'."\n");
 2660:             &Apache::lonxml::clear_problem_counter();
 2661:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2662:                             {'previousversion' => $env{'form.previousversion'} }));
 2663:             $request->print("\n</div>");
 2664:         }
 2665:     }
 2666:     return;
 2667: }
 2668: 
 2669: sub choose_task_version_form {
 2670:     my ($symb,$uname,$udom,$nomenu) = @_;
 2671:     my $isTask = ($symb =~/\.task$/);
 2672:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2673:     if ($isTask) {
 2674:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2675:                                               $udom,$uname);
 2676:         if (($record{'resource.0.version'} eq '') ||
 2677:             ($record{'resource.0.version'} < 2)) {
 2678:             return ($record{'resource.0.version'},
 2679:                     $record{'resource.0.version'},$result,$js);
 2680:         } else {
 2681:             $current = $record{'resource.0.version'};
 2682:         }
 2683:         if ($env{'form.previousversion'}) {
 2684:             $displayed = $env{'form.previousversion'};
 2685:             $rowtitle = &mt('Choose another version:')
 2686:         } else {
 2687:             $displayed = $current;
 2688:             $rowtitle = &mt('Show earlier version:');
 2689:         }
 2690:         $result = '<div class="LC_left_float">';
 2691:         my $list;
 2692:         my $numversions = 0;
 2693:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2694:             if ($i == $current) {
 2695:                 if (!$env{'form.previousversion'} || $nomenu) {
 2696:                     next;
 2697:                 } else {
 2698:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2699:                     $numversions ++;
 2700:                 }
 2701:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2702:                 unless ($i == $env{'form.previousversion'}) {
 2703:                     $numversions ++;
 2704:                 }
 2705:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2706:             }
 2707:         }
 2708:         if ($numversions) {
 2709:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2710:             $result .=
 2711:                 '<form name="getprev" method="post" action=""'.
 2712:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2713:                 &Apache::loncommon::start_data_table().
 2714:                 &Apache::loncommon::start_data_table_row().
 2715:                 '<th align="left">'.$rowtitle.'</th>'.
 2716:                 '<td><select name="version">'.
 2717:                 '<option>'.&mt('Select').'</option>'.
 2718:                 $list.
 2719:                 '</select></td>'.
 2720:                 &Apache::loncommon::end_data_table_row();
 2721:             unless ($nomenu) {
 2722:                 $result .= &Apache::loncommon::start_data_table_row().
 2723:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2724:                 '<td><span class="LC_nobreak">'.
 2725:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2726:                 &mt('Yes').'</label>'.
 2727:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2728:                 '</span></td>'.
 2729:                 &Apache::loncommon::end_data_table_row();
 2730:             }
 2731:             $result .=
 2732:                 &Apache::loncommon::start_data_table_row().
 2733:                 '<th align="left">&nbsp;</th>'.
 2734:                 '<td>'.
 2735:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2736:                 '</td>'.
 2737:                 &Apache::loncommon::end_data_table_row().
 2738:                 &Apache::loncommon::end_data_table().
 2739:                 '</form>';
 2740:             $js = &previous_display_javascript($nomenu,$current);
 2741:         } elsif ($displayed && $nomenu) {
 2742:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2743:         } else {
 2744:             $result .= &mt('No previous versions to show for this student');
 2745:         }
 2746:         $result .= '</div>';
 2747:     }
 2748:     return ($current,$displayed,$result,$js);
 2749: }
 2750: 
 2751: sub previous_display_javascript {
 2752:     my ($nomenu,$current) = @_;
 2753:     my $js = <<"JSONE";
 2754: <script type="text/javascript">
 2755: // <![CDATA[
 2756: function previousVersion(uname,udom,symb) {
 2757:     var current = '$current';
 2758:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2759:     var prevstr = new RegExp("^\\\\d+\$");
 2760:     if (!prevstr.test(version)) {
 2761:         return false;
 2762:     }
 2763:     var url = '';
 2764:     if (version == current) {
 2765:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2766:     } else {
 2767:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2768:     }
 2769: JSONE
 2770:     if ($nomenu) {
 2771:         $js .= <<"JSTWO";
 2772:     document.location.href = url;
 2773: JSTWO
 2774:     } else {
 2775:         $js .= <<"JSTHREE";
 2776:     var newwin = 0;
 2777:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2778:         if (document.getprev.prevwin[i].checked == true) {
 2779:             newwin = document.getprev.prevwin[i].value;
 2780:         }
 2781:     }
 2782:     if (newwin == 1) {
 2783:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2784:         url = url+'&inhibitmenu=yes';
 2785:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2786:             previousWin = window.open(url,'',options,1);
 2787:         } else {
 2788:             previousWin.location.href = url;
 2789:         }
 2790:         previousWin.focus();
 2791:         return false;
 2792:     } else {
 2793:         document.location.href = url;
 2794:         return false;
 2795:     }
 2796: JSTHREE
 2797:     }
 2798:     $js .= <<"ENDJS";
 2799:     return false;
 2800: }
 2801: // ]]>
 2802: </script>
 2803: ENDJS
 2804: 
 2805: }
 2806: 
 2807: #--- Called from submission routine
 2808: sub processHandGrade {
 2809:     my ($request) = shift;
 2810:     my ($symb)   = &get_symb($request);
 2811:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2812:     my $button = $env{'form.gradeOpt'};
 2813:     my $ngrade = $env{'form.NCT'};
 2814:     my $ntstu  = $env{'form.NTSTU'};
 2815:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2816:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2817: 
 2818:     if ($button eq 'Save & Next') {
 2819: 	my $ctr = 0;
 2820: 	while ($ctr < $ngrade) {
 2821: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2822: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2823: 	    if ($errorflag eq 'no_score') {
 2824: 		$ctr++;
 2825: 		next;
 2826: 	    }
 2827: 	    if ($errorflag eq 'not_allowed') {
 2828: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2829: 		$ctr++;
 2830: 		next;
 2831: 	    }
 2832: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2833: 	    my ($subject,$message,$msgstatus) = ('','','');
 2834: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2835:             my ($feedurl,$showsymb) =
 2836: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2837: 	    my $messagetail;
 2838: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2839: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2840: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2841: 		$subject.=' ['.$restitle.']';
 2842: 		my (@msgnum) = split(/,/,$includemsg);
 2843: 		foreach (@msgnum) {
 2844: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2845: 		}
 2846: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2847: 		if ($env{'form.withgrades'.$ctr}) {
 2848: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2849: 		    $messagetail = " for <a href=\"".
 2850: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2851: 		}
 2852: 		$msgstatus = 
 2853:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2854: 						     $message.$messagetail,
 2855:                                                      undef,$feedurl,undef,
 2856:                                                      undef,undef,$showsymb,
 2857:                                                      $restitle);
 2858: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2859: 				$msgstatus.'<br />');
 2860: 	    }
 2861: 	    if ($env{'form.collaborator'.$ctr}) {
 2862: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2863: 		foreach my $collabstr (@collabstrs) {
 2864: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2865: 		    foreach my $collaborator (@collaborators) {
 2866: 			my ($errorflag,$pts,$wgt) = 
 2867: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2868: 					   $env{'form.unamedom'.$ctr},$part);
 2869: 			if ($errorflag eq 'not_allowed') {
 2870: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2871: 			    next;
 2872: 			} elsif ($message ne '') {
 2873: 			    my ($baseurl,$showsymb) = 
 2874: 				&get_feedurl_and_symb($symb,$collaborator,
 2875: 						      $udom);
 2876: 			    if ($env{'form.withgrades'.$ctr}) {
 2877: 				$messagetail = " for <a href=\"".
 2878:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2879: 			    }
 2880: 			    $msgstatus = 
 2881: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2882: 			}
 2883: 		    }
 2884: 		}
 2885: 	    }
 2886: 	    $ctr++;
 2887: 	}
 2888:     }
 2889: 
 2890:     if ($env{'form.handgrade'} eq 'yes') {
 2891: 	# Keywords sorted in alphabatical order
 2892: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2893: 	my %keyhash = ();
 2894: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2895: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2896: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2897: 	$env{'form.keywords'} = join(' ',@keywords);
 2898: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2899: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2900: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2901: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2902: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2903: 
 2904: 	# message center - Order of message gets changed. Blank line is eliminated.
 2905: 	# New messages are saved in env for the next student.
 2906: 	# All messages are saved in nohist_handgrade.db
 2907: 	my ($ctr,$idx) = (1,1);
 2908: 	while ($ctr <= $env{'form.savemsgN'}) {
 2909: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2910: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2911: 		$idx++;
 2912: 	    }
 2913: 	    $ctr++;
 2914: 	}
 2915: 	$ctr = 0;
 2916: 	while ($ctr < $ngrade) {
 2917: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2918: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2919: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2920: 		$idx++;
 2921: 	    }
 2922: 	    $ctr++;
 2923: 	}
 2924: 	$env{'form.savemsgN'} = --$idx;
 2925: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2926: 	my $putresult = &Apache::lonnet::put
 2927: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2928:     }
 2929:     # Called by Save & Refresh from Highlight Attribute Window
 2930:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2931:     if ($env{'form.refresh'} eq 'on') {
 2932: 	my ($ctr,$total) = (0,0);
 2933: 	while ($ctr < $ngrade) {
 2934: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2935: 	    $ctr++;
 2936: 	}
 2937: 	$env{'form.NTSTU'}=$ngrade;
 2938: 	$ctr = 0;
 2939: 	while ($ctr < $total) {
 2940: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2941: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2942: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2943: 	    &submission($request,$ctr,$total-1);
 2944: 	    $ctr++;
 2945: 	}
 2946: 	return '';
 2947:     }
 2948: 
 2949: # Go directly to grade student - from submission or link from chart page
 2950:     if ($button eq 'Grade Student') {
 2951: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2952: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2953: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2954: 	$env{'form.fullname'} = $$fullname{$processUser};
 2955: 	&submission($request,0,0);
 2956: 	return '';
 2957:     }
 2958: 
 2959:     # Get the next/previous one or group of students
 2960:     my $firststu = $env{'form.unamedom0'};
 2961:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2962:     my $ctr = 2;
 2963:     while ($laststu eq '') {
 2964: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2965: 	$ctr++;
 2966: 	$laststu = $firststu if ($ctr > $ngrade);
 2967:     }
 2968: 
 2969:     my (@parsedlist,@nextlist);
 2970:     my ($nextflg) = 0;
 2971:     foreach my $item (sort 
 2972: 	     {
 2973: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2974: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2975: 		 }
 2976: 		 return $a cmp $b;
 2977: 	     } (keys(%$fullname))) {
 2978: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2979: 	    push(@parsedlist,$item);
 2980: 	}
 2981: 	$nextflg = 1 if ($item eq $laststu);
 2982: 	if ($button eq 'Previous') {
 2983: 	    last if ($item eq $firststu);
 2984: 	    push(@parsedlist,$item);
 2985: 	}
 2986:     }
 2987:     $ctr = 0;
 2988:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2989:     my $res_error;
 2990:     my ($partlist) = &response_type($symb,\$res_error);
 2991:     if ($res_error) {
 2992:         $request->print(&navmap_errormsg());
 2993:         return;
 2994:     }
 2995:     foreach my $student (@parsedlist) {
 2996: 	my $submitonly=$env{'form.submitonly'};
 2997: 	my ($uname,$udom) = split(/:/,$student);
 2998: 	
 2999: 	if ($submitonly eq 'queued') {
 3000: 	    my %queue_status = 
 3001: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3002: 							$udom,$uname);
 3003: 	    next if (!defined($queue_status{'gradingqueue'}));
 3004: 	}
 3005: 
 3006: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3007: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3008: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3009: 	    my $submitted = 0;
 3010: 	    my $ungraded = 0;
 3011: 	    my $incorrect = 0;
 3012: 	    foreach my $item (keys(%status)) {
 3013: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3014: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3015: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3016: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3017: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3018: 		    $submitted = 0;
 3019: 		}
 3020: 	    }
 3021: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3022: 				     $submitonly eq 'incorrect' ||
 3023: 				     $submitonly eq 'graded'));
 3024: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3025: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3026: 	}
 3027: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3028: 	last if ($ctr == $ntstu);
 3029: 	$ctr++;
 3030:     }
 3031: 
 3032:     $ctr = 0;
 3033:     my $total = scalar(@nextlist)-1;
 3034: 
 3035:     foreach (sort(@nextlist)) {
 3036: 	my ($uname,$udom,$submitter) = split(/:/);
 3037: 	$env{'form.student'}  = $uname;
 3038: 	$env{'form.userdom'}  = $udom;
 3039: 	$env{'form.fullname'} = $$fullname{$_};
 3040: 	&submission($request,$ctr,$total);
 3041: 	$ctr++;
 3042:     }
 3043:     if ($total < 0) {
 3044: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3045: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3046: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3047: 	$the_end.=&show_grading_menu_form($symb);
 3048: 	$request->print($the_end);
 3049:     }
 3050:     return '';
 3051: }
 3052: 
 3053: #---- Save the score and award for each student, if changed
 3054: sub saveHandGrade {
 3055:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3056:     my @version_parts;
 3057:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3058: 					   $env{'request.course.id'});
 3059:     if (!&canmodify($usec)) { return('not_allowed'); }
 3060:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3061:     my @parts_graded;
 3062:     my %newrecord  = ();
 3063:     my ($pts,$wgt) = ('','');
 3064:     my %aggregate = ();
 3065:     my $aggregateflag = 0;
 3066:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3067:     foreach my $new_part (@parts) {
 3068: 	#collaborator ($submi may vary for different parts
 3069: 	if ($submitter && $new_part ne $part) { next; }
 3070: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3071: 	if ($dropMenu eq 'excused') {
 3072: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3073: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3074: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3075: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3076: 		}
 3077: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3078: 	    }
 3079: 	} elsif ($dropMenu eq 'reset status'
 3080: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3081: 	    foreach my $key (keys(%record)) {
 3082: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3083: 	    }
 3084: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3085: 		"$env{'user.name'}:$env{'user.domain'}";
 3086:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3087: 
 3088:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3089: 					       [$new_part]);
 3090:             my $aggtries =$totaltries;
 3091:             if ($last_resets{$new_part}) {
 3092:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3093: 					   $new_part);
 3094:             }
 3095: 
 3096:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3097:             if ($aggtries > 0) {
 3098:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3099:                 $aggregateflag = 1;
 3100:             }
 3101: 	} elsif ($dropMenu eq '') {
 3102: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3103: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3104: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3105: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3106: 		next;
 3107: 	    }
 3108: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3109: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3110: 	    my $partial= $pts/$wgt;
 3111: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3112: 		#do not update score for part if not changed.
 3113:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3114: 		next;
 3115: 	    } else {
 3116: 	        push(@parts_graded,$new_part);
 3117: 	    }
 3118: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3119: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3120: 	    }
 3121: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3122: 	    if ($partial == 0) {
 3123: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3124: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3125: 		}
 3126: 	    } else {
 3127: 		if ($record{$reckey} ne 'correct_by_override') {
 3128: 		    $newrecord{$reckey} = 'correct_by_override';
 3129: 		}
 3130: 	    }	    
 3131: 	    if ($submitter && 
 3132: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3133: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3134: 	    }
 3135: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3136: 		"$env{'user.name'}:$env{'user.domain'}";
 3137: 	}
 3138: 	# unless problem has been graded, set flag to version the submitted files
 3139: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3140: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3141: 	        $dropMenu eq 'reset status')
 3142: 	   {
 3143: 	    push(@version_parts,$new_part);
 3144: 	}
 3145:     }
 3146:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3147:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3148: 
 3149:     if (%newrecord) {
 3150:         if (@version_parts) {
 3151:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3152:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3153: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3154: 	    foreach my $new_part (@version_parts) {
 3155: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3156: 				$new_part,\%newrecord);
 3157: 	    }
 3158:         }
 3159: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3160: 				$env{'request.course.id'},$domain,$stuname);
 3161: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3162: 				     $cdom,$cnum,$domain,$stuname);
 3163:     }
 3164:     if ($aggregateflag) {
 3165:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3166: 			      $cdom,$cnum);
 3167:     }
 3168:     return ('',$pts,$wgt);
 3169: }
 3170: 
 3171: sub check_and_remove_from_queue {
 3172:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3173:     my @ungraded_parts;
 3174:     foreach my $part (@{$parts}) {
 3175: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3176: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3177: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3178: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3179: 		) {
 3180: 	    push(@ungraded_parts, $part);
 3181: 	}
 3182:     }
 3183:     if ( !@ungraded_parts ) {
 3184: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3185: 					       $cnum,$domain,$stuname);
 3186:     }
 3187: }
 3188: 
 3189: sub handback_files {
 3190:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3191:     my $portfolio_root = '/userfiles/portfolio';
 3192:     my $res_error;
 3193:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3194:     if ($res_error) {
 3195:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3196:         return;
 3197:     }
 3198:     my @handedback;
 3199:     my $file_msg;
 3200:     my @part_response_id = &flatten_responseType($responseType);
 3201:     foreach my $part_response_id (@part_response_id) {
 3202:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3203: 	my $part_resp = join('_',@{ $part_response_id });
 3204:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3205:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3206:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3207: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3208:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3209:                     my ($directory,$answer_file) = 
 3210:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3211:                     my ($answer_name,$answer_ver,$answer_ext) =
 3212: 		        &file_name_version_ext($answer_file);
 3213: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3214:                     my $getpropath = 1;
 3215:                     my ($dir_list,$listerror) =
 3216:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3217:                                                  $domain,$stuname,$getpropath);
 3218: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3219:                     # fix filename
 3220:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3221:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3222:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3223:             	                                $save_file_name);
 3224:                     if ($result !~ m|^/uploaded/|) {
 3225:                         $request->print('<br /><span class="LC_error">'.
 3226:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3227:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3228:                                         '</span>');
 3229:                     } else {
 3230:                         # mark the file as read only
 3231:                         push(@handedback,$save_file_name);
 3232: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3233: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3234: 			}
 3235:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3236: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3237: 
 3238:                     }
 3239:                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 3240:                 }
 3241:             }
 3242:         }
 3243:     }
 3244:     if (@handedback > 0) {
 3245:         $request->print('<br />');
 3246:         my @what = ($symb,$env{'request.course.id'},'handback');
 3247:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3248:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3249:         my ($subject,$message);
 3250:         if (scalar(@handedback) == 1) {
 3251:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3252:         } else {
 3253:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3254:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3255:         }
 3256:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3257:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3258:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3259:         my ($feedurl,$showsymb) =
 3260:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3261:         my $restitle = &Apache::lonnet::gettitle($symb);
 3262:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3263:         my $msgstatus =
 3264:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3265:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3266:                  $restitle);
 3267:         if ($msgstatus) {
 3268:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3269:         }
 3270:     }
 3271:     return;
 3272: }
 3273: 
 3274: sub get_feedurl_and_symb {
 3275:     my ($symb,$uname,$udom) = @_;
 3276:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3277:     $url = &Apache::lonnet::clutter($url);
 3278:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3279: 					$symb,$udom,$uname);
 3280:     if ($encrypturl =~ /^yes$/i) {
 3281: 	&Apache::lonenc::encrypted(\$url,1);
 3282: 	&Apache::lonenc::encrypted(\$symb,1);
 3283:     }
 3284:     return ($url,$symb);
 3285: }
 3286: 
 3287: sub get_submitted_files {
 3288:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3289:     my @files;
 3290:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3291:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3292:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3293:     	    push(@files,$file_url.$file);
 3294:         }
 3295:     }
 3296:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3297:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3298:     }
 3299:     return (\@files);
 3300: }
 3301: 
 3302: # ----------- Provides number of tries since last reset.
 3303: sub get_num_tries {
 3304:     my ($record,$last_reset,$part) = @_;
 3305:     my $timestamp = '';
 3306:     my $num_tries = 0;
 3307:     if ($$record{'version'}) {
 3308:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3309:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3310:                 $timestamp = $$record{$version.':timestamp'};
 3311:                 if ($timestamp > $last_reset) {
 3312:                     $num_tries ++;
 3313:                 } else {
 3314:                     last;
 3315:                 }
 3316:             }
 3317:         }
 3318:     }
 3319:     return $num_tries;
 3320: }
 3321: 
 3322: # ----------- Determine decrements required in aggregate totals 
 3323: sub decrement_aggs {
 3324:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3325:     my %decrement = (
 3326:                         attempts => 0,
 3327:                         users => 0,
 3328:                         correct => 0
 3329:                     );
 3330:     $decrement{'attempts'} = $aggtries;
 3331:     if ($solvedstatus =~ /^correct/) {
 3332:         $decrement{'correct'} = 1;
 3333:     }
 3334:     if ($aggtries == $totaltries) {
 3335:         $decrement{'users'} = 1;
 3336:     }
 3337:     foreach my $type (keys(%decrement)) {
 3338:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3339:     }
 3340:     return;
 3341: }
 3342: 
 3343: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3344: sub get_last_resets {
 3345:     my ($symb,$courseid,$partids) =@_;
 3346:     my %last_resets;
 3347:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3348:     my $cname = $env{'course.'.$courseid.'.num'};
 3349:     my @keys;
 3350:     foreach my $part (@{$partids}) {
 3351: 	push(@keys,"$symb\0$part\0resettime");
 3352:     }
 3353:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3354: 				     $cdom,$cname);
 3355:     foreach my $part (@{$partids}) {
 3356: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3357:     }
 3358:     return %last_resets;
 3359: }
 3360: 
 3361: # ----------- Handles creating versions for portfolio files as answers
 3362: sub version_portfiles {
 3363:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3364:     my $version_parts = join('|',@$v_flag);
 3365:     my @returned_keys;
 3366:     my $parts = join('|', @$parts_graded);
 3367:     my $portfolio_root = '/userfiles/portfolio';
 3368:     foreach my $key (keys(%$record)) {
 3369:         my $new_portfiles;
 3370:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3371:             my @versioned_portfiles;
 3372:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3373:             foreach my $file (@portfiles) {
 3374:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3375:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3376: 		my ($answer_name,$answer_ver,$answer_ext) =
 3377: 		    &file_name_version_ext($answer_file);
 3378:                 my $getpropath = 1;
 3379:                 my ($dir_list,$listerror) =
 3380:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3381:                                              $stu_name,$getpropath);
 3382:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3383:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3384:                 if ($new_answer ne 'problem getting file') {
 3385:                     push(@versioned_portfiles, $directory.$new_answer);
 3386:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3387:                         [$directory.$new_answer],
 3388:                         [$symb,$env{'request.course.id'},'graded']);
 3389:                 }
 3390:             }
 3391:             $$record{$key} = join(',',@versioned_portfiles);
 3392:             push(@returned_keys,$key);
 3393:         }
 3394:     } 
 3395:     return (@returned_keys);   
 3396: }
 3397: 
 3398: sub get_next_version {
 3399:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3400:     my $version;
 3401:     if (ref($dir_list) eq 'ARRAY') {
 3402:         foreach my $row (@{$dir_list}) {
 3403:             my ($file) = split(/\&/,$row,2);
 3404:             my ($file_name,$file_version,$file_ext) =
 3405: 	        &file_name_version_ext($file);
 3406:             if (($file_name eq $answer_name) && 
 3407: 	        ($file_ext eq $answer_ext)) {
 3408:                 # gets here if filename and extension match, 
 3409:                 # regardless of version
 3410:                 if ($file_version ne '') {
 3411:                     # a versioned file is found  so save it for later
 3412:                     if ($file_version > $version) {
 3413: 		        $version = $file_version;
 3414:                     }
 3415: 	        }
 3416:             }
 3417:         }
 3418:     }
 3419:     $version ++;
 3420:     return($version);
 3421: }
 3422: 
 3423: sub version_selected_portfile {
 3424:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3425:     my ($answer_name,$answer_ver,$answer_ext) =
 3426:         &file_name_version_ext($file_name);
 3427:     my $new_answer;
 3428:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3429:     if($env{'form.copy'} eq '-1') {
 3430:         $new_answer = 'problem getting file';
 3431:     } else {
 3432:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3433:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3434:                             $stu_name,$domain,'copy',
 3435: 		        '/portfolio'.$directory.$new_answer);
 3436:     }    
 3437:     return ($new_answer);
 3438: }
 3439: 
 3440: sub file_name_version_ext {
 3441:     my ($file)=@_;
 3442:     my @file_parts = split(/\./, $file);
 3443:     my ($name,$version,$ext);
 3444:     if (@file_parts > 1) {
 3445: 	$ext=pop(@file_parts);
 3446: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3447: 	    $version=pop(@file_parts);
 3448: 	}
 3449: 	$name=join('.',@file_parts);
 3450:     } else {
 3451: 	$name=join('.',@file_parts);
 3452:     }
 3453:     return($name,$version,$ext);
 3454: }
 3455: 
 3456: #--------------------------------------------------------------------------------------
 3457: #
 3458: #-------------------------- Next few routines handles grading by section or whole class
 3459: #
 3460: #--- Javascript to handle grading by section or whole class
 3461: sub viewgrades_js {
 3462:     my ($request) = shift;
 3463: 
 3464:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3465:     $request->print(<<VIEWJAVASCRIPT);
 3466: <script type="text/javascript" language="javascript">
 3467:    function writePoint(partid,weight,point) {
 3468: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3469: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3470: 	if (point == "textval") {
 3471: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3472: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3473: 		alert("$alertmsg"+parseFloat(point));
 3474: 		var resetbox = false;
 3475: 		for (var i=0; i<radioButton.length; i++) {
 3476: 		    if (radioButton[i].checked) {
 3477: 			textbox.value = i;
 3478: 			resetbox = true;
 3479: 		    }
 3480: 		}
 3481: 		if (!resetbox) {
 3482: 		    textbox.value = "";
 3483: 		}
 3484: 		return;
 3485: 	    }
 3486: 	    if (parseFloat(point) > parseFloat(weight)) {
 3487: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3488: 				   ") greater than the weight for the part. Accept?");
 3489: 		if (resp == false) {
 3490: 		    textbox.value = "";
 3491: 		    return;
 3492: 		}
 3493: 	    }
 3494: 	    for (var i=0; i<radioButton.length; i++) {
 3495: 		radioButton[i].checked=false;
 3496: 		if (parseFloat(point) == i) {
 3497: 		    radioButton[i].checked=true;
 3498: 		}
 3499: 	    }
 3500: 
 3501: 	} else {
 3502: 	    textbox.value = parseFloat(point);
 3503: 	}
 3504: 	for (i=0;i<document.classgrade.total.value;i++) {
 3505: 	    var user = document.classgrade["ctr"+i].value;
 3506: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3507: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3508: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3509: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3510: 	    if (saveval != "correct") {
 3511: 		scorename.value = point;
 3512: 		if (selname[0].selected != true) {
 3513: 		    selname[0].selected = true;
 3514: 		}
 3515: 	    }
 3516: 	}
 3517: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3518:     }
 3519: 
 3520:     function writeRadText(partid,weight) {
 3521: 	var selval   = document.classgrade["SELVAL_"+partid];
 3522: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3523:         var override = document.classgrade["FORCE_"+partid].checked;
 3524: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3525: 	if (selval[1].selected || selval[2].selected) {
 3526: 	    for (var i=0; i<radioButton.length; i++) {
 3527: 		radioButton[i].checked=false;
 3528: 
 3529: 	    }
 3530: 	    textbox.value = "";
 3531: 
 3532: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3533: 		var user = document.classgrade["ctr"+i].value;
 3534: 		user = user.replace(new RegExp(':', 'g'),"_");
 3535: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3536: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3537: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3538: 		if ((saveval != "correct") || override) {
 3539: 		    scorename.value = "";
 3540: 		    if (selval[1].selected) {
 3541: 			selname[1].selected = true;
 3542: 		    } else {
 3543: 			selname[2].selected = true;
 3544: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3545: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3546: 		    }
 3547: 		}
 3548: 	    }
 3549: 	} else {
 3550: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3551: 		var user = document.classgrade["ctr"+i].value;
 3552: 		user = user.replace(new RegExp(':', 'g'),"_");
 3553: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3554: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3555: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3556: 		if ((saveval != "correct") || override) {
 3557: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3558: 		    selname[0].selected = true;
 3559: 		}
 3560: 	    }
 3561: 	}	    
 3562:     }
 3563: 
 3564:     function changeSelect(partid,user) {
 3565: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3566: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3567: 	var point  = textbox.value;
 3568: 	var weight = document.classgrade["weight_"+partid].value;
 3569: 
 3570: 	if (isNaN(point) || parseFloat(point) < 0) {
 3571: 	    alert("$alertmsg"+parseFloat(point));
 3572: 	    textbox.value = "";
 3573: 	    return;
 3574: 	}
 3575: 	if (parseFloat(point) > parseFloat(weight)) {
 3576: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3577: 			       ") greater than the weight of the part. Accept?");
 3578: 	    if (resp == false) {
 3579: 		textbox.value = "";
 3580: 		return;
 3581: 	    }
 3582: 	}
 3583: 	selval[0].selected = true;
 3584:     }
 3585: 
 3586:     function changeOneScore(partid,user) {
 3587: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3588: 	if (selval[1].selected || selval[2].selected) {
 3589: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3590: 	    if (selval[2].selected) {
 3591: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3592: 	    }
 3593:         }
 3594:     }
 3595: 
 3596:     function resetEntry(numpart) {
 3597: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3598: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3599: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3600: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3601: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3602: 	    for (var i=0; i<radioButton.length; i++) {
 3603: 		radioButton[i].checked=false;
 3604: 
 3605: 	    }
 3606: 	    textbox.value = "";
 3607: 	    selval[0].selected = true;
 3608: 
 3609: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3610: 		var user = document.classgrade["ctr"+i].value;
 3611: 		user = user.replace(new RegExp(':', 'g'),"_");
 3612: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3613: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3614: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3615: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3616: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3617: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3618: 		if (saveselval == "excused") {
 3619: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3620: 		} else {
 3621: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3622: 		}
 3623: 	    }
 3624: 	}
 3625:     }
 3626: 
 3627: </script>
 3628: VIEWJAVASCRIPT
 3629: }
 3630: 
 3631: #--- show scores for a section or whole class w/ option to change/update a score
 3632: sub viewgrades {
 3633:     my ($request) = shift;
 3634:     &viewgrades_js($request);
 3635: 
 3636:     my ($symb) = &get_symb($request);
 3637:     #need to make sure we have the correct data for later EXT calls, 
 3638:     #thus invalidate the cache
 3639:     &Apache::lonnet::devalidatecourseresdata(
 3640:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3641:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3642:     &Apache::lonnet::clear_EXT_cache_status();
 3643: 
 3644:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3645:     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3646: 
 3647:     #view individual student submission form - called using Javascript viewOneStudent
 3648:     $result.=&jscriptNform($symb);
 3649: 
 3650:     #beginning of class grading form
 3651:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3652:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3653: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3654: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3655: 	&build_section_inputs().
 3656: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3657: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3658: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3659: 
 3660:     my ($common_header,$specific_header);
 3661:     if ($env{'form.section'} eq 'all') {
 3662: 	$common_header = &mt('Assign Common Grade to Class');
 3663:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3664:     } elsif ($env{'form.section'} eq 'none') {
 3665:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3666: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3667:     } else {
 3668:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3669:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3670: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3671:     }
 3672:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3673:     #radio buttons/text box for assigning points for a section or class.
 3674:     #handles different parts of a problem
 3675:     my $res_error;
 3676:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3677:     if ($res_error) {
 3678:         return &navmap_errormsg();
 3679:     }
 3680:     my %weight = ();
 3681:     my $ctsparts = 0;
 3682:     my %seen = ();
 3683:     my @part_response_id = &flatten_responseType($responseType);
 3684:     foreach my $part_response_id (@part_response_id) {
 3685:     	my ($partid,$respid) = @{ $part_response_id };
 3686: 	my $part_resp = join('_',@{ $part_response_id });
 3687: 	next if $seen{$partid};
 3688: 	$seen{$partid}++;
 3689: 	my $handgrade=$$handgrade{$part_resp};
 3690: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3691: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3692: 
 3693: 	my $display_part=&get_display_part($partid,$symb);
 3694: 	my $radio.='<table border="0"><tr>';  
 3695: 	my $ctr = 0;
 3696: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3697: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3698: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3699: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3700: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3701: 	    $ctr++;
 3702: 	}
 3703: 	$radio.='</tr></table>';
 3704: 	my $line = '<input type="text" name="TEXTVAL_'.
 3705: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3706: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3707: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3708: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3709:                 '<select name="SELVAL_'.$partid.'" '.
 3710: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 3711: 		$weight{$partid}.')"> '.
 3712: 	    '<option selected="selected"> </option>'.
 3713: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3714: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3715: 	    '</select></td>'.
 3716:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3717: 	$line.='<input type="hidden" name="partid_'.
 3718: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3719: 	$line.='<input type="hidden" name="weight_'.
 3720: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3721: 
 3722: 	$result.=
 3723: 	    &Apache::loncommon::start_data_table_row()."\n".
 3724: 	    '<td><b>'.&mt('Part:').'</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points:').'</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>'.
 3725: 	    &Apache::loncommon::end_data_table_row()."\n";
 3726: 	$ctsparts++;
 3727:     }
 3728:     $result.=&Apache::loncommon::end_data_table()."\n".
 3729: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3730:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3731: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3732: 
 3733:     #table listing all the students in a section/class
 3734:     #header of table
 3735:     $result.= '<h3>'.$specific_header.'</h3>'.
 3736:               &Apache::loncommon::start_data_table().
 3737: 	      &Apache::loncommon::start_data_table_header_row().
 3738: 	      '<th>'.&mt('No.').'</th>'.
 3739: 	      '<th>'.&nameUserString('header')."</th>\n";
 3740:     my $partserror;
 3741:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3742:     if ($partserror) {
 3743:         return &navmap_errormsg();
 3744:     }
 3745:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3746:     my @partids = ();
 3747:     foreach my $part (@parts) {
 3748: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3749:         my $narrowtext = &mt('Tries');
 3750: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3751: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3752: 	my ($partid) = &split_part_type($part);
 3753:         push(@partids,$partid);
 3754: 	my $display_part=&get_display_part($partid,$symb);
 3755: 	if ($display =~ /^Partial Credit Factor/) {
 3756: 	    $result.='<th>'.
 3757:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3758:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3759: 	    next;
 3760: 	    
 3761: 	} else {
 3762: 	    if ($display =~ /Problem Status/) {
 3763: 		my $grade_status_mt = &mt('Grade Status');
 3764: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3765: 	    }
 3766: 	    my $part_mt = &mt('Part:');
 3767: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3768: 	}
 3769: 
 3770: 	$result.='<th>'.$display.'</th>'."\n";
 3771:     }
 3772:     $result.=&Apache::loncommon::end_data_table_header_row();
 3773: 
 3774:     my %last_resets = 
 3775: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3776: 
 3777:     #get info for each student
 3778:     #list all the students - with points and grade status
 3779:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3780:     my $ctr = 0;
 3781:     foreach (sort 
 3782: 	     {
 3783: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3784: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3785: 		 }
 3786: 		 return $a cmp $b;
 3787: 	     } (keys(%$fullname))) {
 3788: 	$ctr++;
 3789: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3790: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3791:     }
 3792:     $result.=&Apache::loncommon::end_data_table();
 3793:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3794:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3795: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3796:     if (scalar(%$fullname) eq 0) {
 3797: 	my $colspan=3+scalar(@parts);
 3798: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3799:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3800: 	$result='<span class="LC_warning">'.
 3801: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3802: 	        $section_display, $stu_status).
 3803: 	    '</span>';
 3804:     }
 3805:     $result.=&show_grading_menu_form($symb);
 3806:     return $result;
 3807: }
 3808: 
 3809: #--- call by previous routine to display each student
 3810: sub viewstudentgrade {
 3811:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3812:     my ($uname,$udom) = split(/:/,$student);
 3813:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3814:     my %aggregates = (); 
 3815:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3816: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3817: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3818: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3819: 	'\');" target="_self">'.$fullname.'</a> '.
 3820: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3821:     $student=~s/:/_/; # colon doen't work in javascript for names
 3822:     foreach my $apart (@$parts) {
 3823: 	my ($part,$type) = &split_part_type($apart);
 3824: 	my $score=$record{"resource.$part.$type"};
 3825:         $result.='<td align="center">';
 3826:         my ($aggtries,$totaltries);
 3827:         unless (exists($aggregates{$part})) {
 3828: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3829: 
 3830: 	    $aggtries = $totaltries;
 3831:             if ($$last_resets{$part}) {  
 3832:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3833: 					   $part);
 3834:             }
 3835:             $result.='<input type="hidden" name="'.
 3836:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3837:             $result.='<input type="hidden" name="'.
 3838:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3839:             $aggregates{$part} = 1;
 3840:         }
 3841: 	if ($type eq 'awarded') {
 3842: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3843: 	    $result.='<input type="hidden" name="'.
 3844: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3845: 	    $result.='<input type="text" name="'.
 3846: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3847:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3848: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3849: 	} elsif ($type eq 'solved') {
 3850: 	    my ($status,$foo)=split(/_/,$score,2);
 3851: 	    $status = 'nothing' if ($status eq '');
 3852: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3853: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3854: 	    $result.='&nbsp;<select name="'.
 3855: 		'GD_'.$student.'_'.$part.'_solved" '.
 3856:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3857: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3858: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3859: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3860: 	    $result.="</select>&nbsp;</td>\n";
 3861: 	} else {
 3862: 	    $result.='<input type="hidden" name="'.
 3863: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3864: 		    "\n";
 3865: 	    $result.='<input type="text" name="'.
 3866: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3867: 		'value="'.$score.'" size="4" /></td>'."\n";
 3868: 	}
 3869:     }
 3870:     $result.=&Apache::loncommon::end_data_table_row();
 3871:     return $result;
 3872: }
 3873: 
 3874: #--- change scores for all the students in a section/class
 3875: #    record does not get update if unchanged
 3876: sub editgrades {
 3877:     my ($request) = @_;
 3878: 
 3879:     my ($symb)=&get_symb($request);
 3880:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3881:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3882:     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3883:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 3884: 
 3885:     my $result= &Apache::loncommon::start_data_table().
 3886: 	&Apache::loncommon::start_data_table_header_row().
 3887: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3888: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3889:     my %scoreptr = (
 3890: 		    'correct'  =>'correct_by_override',
 3891: 		    'incorrect'=>'incorrect_by_override',
 3892: 		    'excused'  =>'excused',
 3893: 		    'ungraded' =>'ungraded_attempted',
 3894:                     'credited' =>'credit_attempted',
 3895: 		    'nothing'  => '',
 3896: 		    );
 3897:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3898: 
 3899:     my (@partid);
 3900:     my %weight = ();
 3901:     my %columns = ();
 3902:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3903: 
 3904:     my $partserror;
 3905:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3906:     if ($partserror) {
 3907:         return &navmap_errormsg();
 3908:     }
 3909:     my $header;
 3910:     while ($ctr < $env{'form.totalparts'}) {
 3911: 	my $partid = $env{'form.partid_'.$ctr};
 3912: 	push(@partid,$partid);
 3913: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3914: 	$ctr++;
 3915:     }
 3916:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3917:     foreach my $partid (@partid) {
 3918: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3919: 	    '<th align="center">'.&mt('New Score').'</th>';
 3920: 	$columns{$partid}=2;
 3921: 	foreach my $stores (@parts) {
 3922: 	    my ($part,$type) = &split_part_type($stores);
 3923: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3924: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3925: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3926: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3927:             my $narrowtext = &mt('Tries');
 3928: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3929: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3930: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3931: 	    $columns{$partid}+=2;
 3932: 	}
 3933:     }
 3934:     foreach my $partid (@partid) {
 3935: 	my $display_part=&get_display_part($partid,$symb);
 3936: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3937: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3938: 	    '</th>';
 3939: 
 3940:     }
 3941:     $result .= &Apache::loncommon::end_data_table_header_row().
 3942: 	&Apache::loncommon::start_data_table_header_row().
 3943: 	$header.
 3944: 	&Apache::loncommon::end_data_table_header_row();
 3945:     my @noupdate;
 3946:     my ($updateCtr,$noupdateCtr) = (1,1);
 3947:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3948: 	my $line;
 3949: 	my $user = $env{'form.ctr'.$i};
 3950: 	my ($uname,$udom)=split(/:/,$user);
 3951: 	my %newrecord;
 3952: 	my $updateflag = 0;
 3953: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3954: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3955: 	if (!&canmodify($usec)) {
 3956: 	    my $numcols=scalar(@partid)*4+2;
 3957: 	    push(@noupdate,
 3958: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3959: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3960: 	    next;
 3961: 	}
 3962:         my %aggregate = ();
 3963:         my $aggregateflag = 0;
 3964: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3965: 	foreach (@partid) {
 3966: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3967: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3968: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3969: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3970: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3971: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3972: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3973: 	    my $score;
 3974: 	    if ($partial eq '') {
 3975: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3976: 	    } elsif ($partial > 0) {
 3977: 		$score = 'correct_by_override';
 3978: 	    } elsif ($partial == 0) {
 3979: 		$score = 'incorrect_by_override';
 3980: 	    }
 3981: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3982: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3983: 
 3984: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3985: 		"$env{'user.name'}:$env{'user.domain'}";
 3986: 	    if ($dropMenu eq 'reset status' &&
 3987: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3988: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3989: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3990: 		$newrecord{'resource.'.$_.'.award'} = '';
 3991: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3992: 		$updateflag = 1;
 3993:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3994:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3995:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3996:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3997:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3998:                     $aggregateflag = 1;
 3999:                 }
 4000: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4001: 		$updateflag = 1;
 4002: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4003: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4004: 		$rec_update++;
 4005: 	    }
 4006: 
 4007: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4008: 		'<td align="center">'.$awarded.
 4009: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4010: 
 4011: 
 4012: 	    my $partid=$_;
 4013: 	    foreach my $stores (@parts) {
 4014: 		my ($part,$type) = &split_part_type($stores);
 4015: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4016: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4017: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4018: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4019: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4020: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4021: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4022: 		    $updateflag=1;
 4023: 		}
 4024: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4025: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4026: 	    }
 4027: 	}
 4028: 	$line.="\n";
 4029: 
 4030: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4031: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4032: 
 4033: 	if ($updateflag) {
 4034: 	    $count++;
 4035: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4036: 				    $udom,$uname);
 4037: 
 4038: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4039: 					      $cnum,$udom,$uname)) {
 4040: 		# need to figure out if should be in queue.
 4041: 		my %record =  
 4042: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4043: 					     $udom,$uname);
 4044: 		my $all_graded = 1;
 4045: 		my $none_graded = 1;
 4046: 		foreach my $part (@parts) {
 4047: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4048: 			$all_graded = 0;
 4049: 		    } else {
 4050: 			$none_graded = 0;
 4051: 		    }
 4052: 		}
 4053: 
 4054: 		if ($all_graded || $none_graded) {
 4055: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4056: 							   $symb,$cdom,$cnum,
 4057: 							   $udom,$uname);
 4058: 		}
 4059: 	    }
 4060: 
 4061: 	    $result.=&Apache::loncommon::start_data_table_row().
 4062: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4063: 		&Apache::loncommon::end_data_table_row();
 4064: 	    $updateCtr++;
 4065: 	} else {
 4066: 	    push(@noupdate,
 4067: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4068: 	    $noupdateCtr++;
 4069: 	}
 4070:         if ($aggregateflag) {
 4071:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4072: 				  $cdom,$cnum);
 4073:         }
 4074:     }
 4075:     if (@noupdate) {
 4076: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4077: 	my $numcols=scalar(@partid)*4+2;
 4078: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4079: 	    '<td align="center" colspan="'.$numcols.'">'.
 4080: 	    &mt('No Changes Occurred For the Students Below').
 4081: 	    '</td>'.
 4082: 	    &Apache::loncommon::end_data_table_row();
 4083: 	foreach my $line (@noupdate) {
 4084: 	    $result.=
 4085: 		&Apache::loncommon::start_data_table_row().
 4086: 		$line.
 4087: 		&Apache::loncommon::end_data_table_row();
 4088: 	}
 4089:     }
 4090:     $result .= &Apache::loncommon::end_data_table().
 4091: 	&show_grading_menu_form($symb);
 4092:     my $msg = '<p><b>'.
 4093: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4094: 	    $rec_update,$count).'</b><br />'.
 4095: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4096: 	'</b></p>';
 4097:     return $title.$msg.$result;
 4098: }
 4099: 
 4100: sub split_part_type {
 4101:     my ($partstr) = @_;
 4102:     my ($temp,@allparts)=split(/_/,$partstr);
 4103:     my $type=pop(@allparts);
 4104:     my $part=join('_',@allparts);
 4105:     return ($part,$type);
 4106: }
 4107: 
 4108: #------------- end of section for handling grading by section/class ---------
 4109: #
 4110: #----------------------------------------------------------------------------
 4111: 
 4112: 
 4113: #----------------------------------------------------------------------------
 4114: #
 4115: #-------------------------- Next few routines handles grading by csv upload
 4116: #
 4117: #--- Javascript to handle csv upload
 4118: sub csvupload_javascript_reverse_associate {
 4119:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4120:     my $error2=&mt('You need to specify at least one grading field');
 4121:   return(<<ENDPICK);
 4122:   function verify(vf) {
 4123:     var foundsomething=0;
 4124:     var founduname=0;
 4125:     var foundID=0;
 4126:     for (i=0;i<=vf.nfields.value;i++) {
 4127:       tw=eval('vf.f'+i+'.selectedIndex');
 4128:       if (i==0 && tw!=0) { foundID=1; }
 4129:       if (i==1 && tw!=0) { founduname=1; }
 4130:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4131:     }
 4132:     if (founduname==0 && foundID==0) {
 4133: 	alert('$error1');
 4134: 	return;
 4135:     }
 4136:     if (foundsomething==0) {
 4137: 	alert('$error2');
 4138: 	return;
 4139:     }
 4140:     vf.submit();
 4141:   }
 4142:   function flip(vf,tf) {
 4143:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4144:     var i;
 4145:     for (i=0;i<=vf.nfields.value;i++) {
 4146:       //can not pick the same destination field for both name and domain
 4147:       if (((i ==0)||(i ==1)) && 
 4148:           ((tf==0)||(tf==1)) && 
 4149:           (i!=tf) &&
 4150:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4151:         eval('vf.f'+i+'.selectedIndex=0;')
 4152:       }
 4153:     }
 4154:   }
 4155: ENDPICK
 4156: }
 4157: 
 4158: sub csvupload_javascript_forward_associate {
 4159:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4160:     my $error2=&mt('You need to specify at least one grading field');
 4161:   return(<<ENDPICK);
 4162:   function verify(vf) {
 4163:     var foundsomething=0;
 4164:     var founduname=0;
 4165:     var foundID=0;
 4166:     for (i=0;i<=vf.nfields.value;i++) {
 4167:       tw=eval('vf.f'+i+'.selectedIndex');
 4168:       if (tw==1) { foundID=1; }
 4169:       if (tw==2) { founduname=1; }
 4170:       if (tw>3) { foundsomething=1; }
 4171:     }
 4172:     if (founduname==0 && foundID==0) {
 4173: 	alert('$error1');
 4174: 	return;
 4175:     }
 4176:     if (foundsomething==0) {
 4177: 	alert('$error2');
 4178: 	return;
 4179:     }
 4180:     vf.submit();
 4181:   }
 4182:   function flip(vf,tf) {
 4183:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4184:     var i;
 4185:     //can not pick the same destination field twice
 4186:     for (i=0;i<=vf.nfields.value;i++) {
 4187:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4188:         eval('vf.f'+i+'.selectedIndex=0;')
 4189:       }
 4190:     }
 4191:   }
 4192: ENDPICK
 4193: }
 4194: 
 4195: sub csvuploadmap_header {
 4196:     my ($request,$symb,$datatoken,$distotal)= @_;
 4197:     my $javascript;
 4198:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4199: 	$javascript=&csvupload_javascript_reverse_associate();
 4200:     } else {
 4201: 	$javascript=&csvupload_javascript_forward_associate();
 4202:     }
 4203: 
 4204:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4205:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4206:     my $ignore=&mt('Ignore First Line');
 4207:     $symb = &Apache::lonenc::check_encrypt($symb);
 4208:     $request->print(<<ENDPICK);
 4209: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4210: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4211: $result
 4212: <hr />
 4213: <h3>Identify fields</h3>
 4214: Total number of records found in file: $distotal <hr />
 4215: Enter as many fields as you can. The system will inform you and bring you back
 4216: to this page if the data selected is insufficient to run your class.<hr />
 4217: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4218: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4219: <input type="hidden" name="associate"  value="" />
 4220: <input type="hidden" name="phase"      value="three" />
 4221: <input type="hidden" name="datatoken"  value="$datatoken" />
 4222: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4223: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4224: <input type="hidden" name="upfile_associate" 
 4225:                                        value="$env{'form.upfile_associate'}" />
 4226: <input type="hidden" name="symb"       value="$symb" />
 4227: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4228: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4229: <input type="hidden" name="command"    value="csvuploadoptions" />
 4230: <hr />
 4231: <script type="text/javascript" language="Javascript">
 4232: $javascript
 4233: </script>
 4234: ENDPICK
 4235:     return '';
 4236: 
 4237: }
 4238: 
 4239: sub csvupload_fields {
 4240:     my ($symb,$errorref) = @_;
 4241:     my (@parts) = &getpartlist($symb,$errorref);
 4242:     if (ref($errorref)) {
 4243:         if ($$errorref) {
 4244:             return;
 4245:         }
 4246:     }
 4247: 
 4248:     my @fields=(['ID','Student/Employee ID'],
 4249: 		['username','Student Username'],
 4250: 		['domain','Student Domain']);
 4251:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4252:     foreach my $part (sort(@parts)) {
 4253: 	my @datum;
 4254: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4255: 	my $name=$part;
 4256: 	if  (!$display) { $display = $name; }
 4257: 	@datum=($name,$display);
 4258: 	if ($name=~/^stores_(.*)_awarded/) {
 4259: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4260: 	}
 4261: 	push(@fields,\@datum);
 4262:     }
 4263:     return (@fields);
 4264: }
 4265: 
 4266: sub csvuploadmap_footer {
 4267:     my ($request,$i,$keyfields) =@_;
 4268:     $request->print(<<ENDPICK);
 4269: </table>
 4270: <input type="hidden" name="nfields" value="$i" />
 4271: <input type="hidden" name="keyfields" value="$keyfields" />
 4272: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 4273: </form>
 4274: ENDPICK
 4275: }
 4276: 
 4277: sub checkforfile_js {
 4278:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4279:     my $result =<<CSVFORMJS;
 4280: <script type="text/javascript" language="javascript">
 4281:     function checkUpload(formname) {
 4282: 	if (formname.upfile.value == "") {
 4283: 	    alert("$alertmsg");
 4284: 	    return false;
 4285: 	}
 4286: 	formname.submit();
 4287:     }
 4288:     </script>
 4289: CSVFORMJS
 4290:     return $result;
 4291: }
 4292: 
 4293: sub upcsvScores_form {
 4294:     my ($request) = shift;
 4295:     my ($symb)=&get_symb($request);
 4296:     if (!$symb) {return '';}
 4297:     my $result=&checkforfile_js();
 4298:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4299:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4300:     $result.=$table;
 4301:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4302:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4303:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4304: 	'</b></td></tr>'."\n";
 4305:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4306:     my $upload=&mt("Upload Scores");
 4307:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4308:     my $ignore=&mt('Ignore First Line');
 4309:     $symb = &Apache::lonenc::check_encrypt($symb);
 4310:     $result.=<<ENDUPFORM;
 4311: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4312: <input type="hidden" name="symb" value="$symb" />
 4313: <input type="hidden" name="command" value="csvuploadmap" />
 4314: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4315: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4316: $upfile_select
 4317: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4318: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4319: </form>
 4320: ENDUPFORM
 4321:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4322:                            &mt("How do I create a CSV file from a spreadsheet"))
 4323:     .'</td></tr></table>'."\n";
 4324:     $result.='</td></tr></table><br /><br />'."\n";
 4325:     $result.=&show_grading_menu_form($symb);
 4326:     return $result;
 4327: }
 4328: 
 4329: 
 4330: sub csvuploadmap {
 4331:     my ($request)= @_;
 4332:     my ($symb)=&get_symb($request);
 4333:     if (!$symb) {return '';}
 4334: 
 4335:     my $datatoken;
 4336:     if (!$env{'form.datatoken'}) {
 4337: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4338:     } else {
 4339: 	$datatoken=$env{'form.datatoken'};
 4340: 	&Apache::loncommon::load_tmp_file($request);
 4341:     }
 4342:     my @records=&Apache::loncommon::upfile_record_sep();
 4343:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4344:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4345:     my ($i,$keyfields);
 4346:     if (@records) {
 4347:         my $fieldserror;
 4348: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4349:         if ($fieldserror) {
 4350:             $request->print(&navmap_errormsg());
 4351:             return;
 4352:         }
 4353: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4354: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4355: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4356: 							  \@fields);
 4357: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4358: 	    chop($keyfields);
 4359: 	} else {
 4360: 	    unshift(@fields,['none','']);
 4361: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4362: 							    \@fields);
 4363:             foreach my $rec (@records) {
 4364:                 my %temp = &Apache::loncommon::record_sep($rec);
 4365:                 if (%temp) {
 4366:                     $keyfields=join(',',sort(keys(%temp)));
 4367:                     last;
 4368:                 }
 4369:             }
 4370: 	}
 4371:     }
 4372:     &csvuploadmap_footer($request,$i,$keyfields);
 4373:     $request->print(&show_grading_menu_form($symb));
 4374: 
 4375:     return '';
 4376: }
 4377: 
 4378: sub csvuploadoptions {
 4379:     my ($request)= @_;
 4380:     my ($symb)=&get_symb($request);
 4381:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4382:     my $ignore=&mt('Ignore First Line');
 4383:     $request->print(<<ENDPICK);
 4384: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4385: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4386: <input type="hidden" name="command"    value="csvuploadassign" />
 4387: <!--
 4388: <p>
 4389: <label>
 4390:    <input type="checkbox" name="show_full_results" />
 4391:    Show a table of all changes
 4392: </label>
 4393: </p>
 4394: -->
 4395: <p>
 4396: <label>
 4397:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4398:    Overwrite any existing score
 4399: </label>
 4400: </p>
 4401: ENDPICK
 4402:     my %fields=&get_fields();
 4403:     if (!defined($fields{'domain'})) {
 4404: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4405: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4406:     }
 4407:     foreach my $key (sort(keys(%env))) {
 4408: 	if ($key !~ /^form\.(.*)$/) { next; }
 4409: 	my $cleankey=$1;
 4410: 	if ($cleankey eq 'command') { next; }
 4411: 	$request->print('<input type="hidden" name="'.$cleankey.
 4412: 			'"  value="'.$env{$key}.'" />'."\n");
 4413:     }
 4414:     # FIXME do a check for any duplicated user ids...
 4415:     # FIXME do a check for any invalid user ids?...
 4416:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4417: <hr /></form>'."\n");
 4418:     $request->print(&show_grading_menu_form($symb));
 4419:     return '';
 4420: }
 4421: 
 4422: sub get_fields {
 4423:     my %fields;
 4424:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4425:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4426: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4427: 	    if ($env{'form.f'.$i} ne 'none') {
 4428: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4429: 	    }
 4430: 	} else {
 4431: 	    if ($env{'form.f'.$i} ne 'none') {
 4432: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4433: 	    }
 4434: 	}
 4435:     }
 4436:     return %fields;
 4437: }
 4438: 
 4439: sub csvuploadassign {
 4440:     my ($request)= @_;
 4441:     my ($symb)=&get_symb($request);
 4442:     if (!$symb) {return '';}
 4443:     my $error_msg = '';
 4444:     &Apache::loncommon::load_tmp_file($request);
 4445:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4446:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4447:     my %fields=&get_fields();
 4448:     $request->print('<h3>Assigning Grades</h3>');
 4449:     my $courseid=$env{'request.course.id'};
 4450:     my ($classlist) = &getclasslist('all',0);
 4451:     my @notallowed;
 4452:     my @skipped;
 4453:     my @warnings;
 4454:     my $countdone=0;
 4455:     foreach my $grade (@gradedata) {
 4456: 	my %entries=&Apache::loncommon::record_sep($grade);
 4457: 	my $domain;
 4458: 	if ($entries{$fields{'domain'}}) {
 4459: 	    $domain=$entries{$fields{'domain'}};
 4460: 	} else {
 4461: 	    $domain=$env{'form.default_domain'};
 4462: 	}
 4463: 	$domain=~s/\s//g;
 4464: 	my $username=$entries{$fields{'username'}};
 4465: 	$username=~s/\s//g;
 4466: 	if (!$username) {
 4467: 	    my $id=$entries{$fields{'ID'}};
 4468: 	    $id=~s/\s//g;
 4469: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4470: 	    $username=$ids{$id};
 4471: 	}
 4472: 	if (!exists($$classlist{"$username:$domain"})) {
 4473: 	    my $id=$entries{$fields{'ID'}};
 4474: 	    $id=~s/\s//g;
 4475: 	    if ($id) {
 4476: 		push(@skipped,"$id:$domain");
 4477: 	    } else {
 4478: 		push(@skipped,"$username:$domain");
 4479: 	    }
 4480: 	    next;
 4481: 	}
 4482: 	my $usec=$classlist->{"$username:$domain"}[5];
 4483: 	if (!&canmodify($usec)) {
 4484: 	    push(@notallowed,"$username:$domain");
 4485: 	    next;
 4486: 	}
 4487: 	my %points;
 4488: 	my %grades;
 4489: 	foreach my $dest (keys(%fields)) {
 4490: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4491: 		$dest eq 'domain') { next; }
 4492: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4493: 	    if ($dest=~/stores_(.*)_points/) {
 4494: 		my $part=$1;
 4495: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4496: 					      $symb,$domain,$username);
 4497:                 if ($wgt) {
 4498:                     $entries{$fields{$dest}}=~s/\s//g;
 4499:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4500:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4501:                                           : 'correct_by_override';
 4502:                     if ($pcr>1) {
 4503:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4504:                     }
 4505:                     $grades{"resource.$part.awarded"}=$pcr;
 4506:                     $grades{"resource.$part.solved"}=$award;
 4507:                     $points{$part}=1;
 4508:                 } else {
 4509:                     $error_msg = "<br />" .
 4510:                         &mt("Some point values were assigned"
 4511:                             ." for problems with a weight "
 4512:                             ."of zero. These values were "
 4513:                             ."ignored.");
 4514:                 }
 4515: 	    } else {
 4516: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4517: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4518: 		my $store_key=$dest;
 4519: 		$store_key=~s/^stores/resource/;
 4520: 		$store_key=~s/_/\./g;
 4521: 		$grades{$store_key}=$entries{$fields{$dest}};
 4522: 	    }
 4523: 	}
 4524: 	if (! %grades) { 
 4525:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4526:         } else {
 4527: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4528: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4529: 					   $env{'request.course.id'},
 4530: 					   $domain,$username);
 4531: 	   if ($result eq 'ok') {
 4532: 	      $request->print('.');
 4533: # Remove from grading queue
 4534:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4535:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4536:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4537:                                              $domain,$username);
 4538: 	   } else {
 4539: 	      $request->print("<p><span class=\"LC_error\">".
 4540:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4541:                                   "$username:$domain",$result)."</span></p>");
 4542: 	   }
 4543: 	   $request->rflush();
 4544: 	   $countdone++;
 4545:         }
 4546:     }
 4547:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4548:     if (@warnings) {
 4549:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4550:         $request->print(join(', ',@warnings));
 4551:     }
 4552:     if (@skipped) {
 4553: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4554:         $request->print(join(', ',@skipped));
 4555:     }
 4556:     if (@notallowed) {
 4557: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4558: 	$request->print(join(', ',@notallowed));
 4559:     }
 4560:     $request->print("<br />\n");
 4561:     $request->print(&show_grading_menu_form($symb));
 4562:     return $error_msg;
 4563: }
 4564: #------------- end of section for handling csv file upload ---------
 4565: #
 4566: #-------------------------------------------------------------------
 4567: #
 4568: #-------------- Next few routines handle grading by page/sequence
 4569: #
 4570: #--- Select a page/sequence and a student to grade
 4571: sub pickStudentPage {
 4572:     my ($request) = shift;
 4573: 
 4574:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4575:     $request->print(<<LISTJAVASCRIPT);
 4576: <script type="text/javascript" language="javascript">
 4577: 
 4578: function checkPickOne(formname) {
 4579:     if (radioSelection(formname.student) == null) {
 4580: 	alert("$alertmsg");
 4581: 	return;
 4582:     }
 4583:     ptr = pullDownSelection(formname.selectpage);
 4584:     formname.page.value = formname["page"+ptr].value;
 4585:     formname.title.value = formname["title"+ptr].value;
 4586:     formname.submit();
 4587: }
 4588: 
 4589: </script>
 4590: LISTJAVASCRIPT
 4591:     &commonJSfunctions($request);
 4592:     my ($symb) = &get_symb($request);
 4593:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4594:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4595:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4596: 
 4597:     my $result='<h3><span class="LC_info">&nbsp;'.
 4598: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4599: 
 4600:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4601:     my $map_error;
 4602:     my ($titles,$symbx) = &getSymbMap($map_error);
 4603:     if ($map_error) {
 4604:         $request->print(&navmap_errormsg());
 4605:         return; 
 4606:     }
 4607:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4608: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4609: #    my $type=($curpage =~ /\.(page|sequence)/);
 4610:     my $select = '<select name="selectpage">'."\n";
 4611:     my $ctr=0;
 4612:     foreach (@$titles) {
 4613: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4614: 	$select.='<option value="'.$ctr.'" '.
 4615: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4616: 	    '>'.$showtitle.'</option>'."\n";
 4617: 	$ctr++;
 4618:     }
 4619:     $select.= '</select>';
 4620:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4621: 
 4622:     $ctr=0;
 4623:     foreach (@$titles) {
 4624: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4625: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4626: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4627: 	$ctr++;
 4628:     }
 4629:     $result.='<input type="hidden" name="page" />'."\n".
 4630: 	'<input type="hidden" name="title" />'."\n";
 4631: 
 4632:     my $options =
 4633: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4634: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4635:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4636: 
 4637:     $options =
 4638: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4639: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4640: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4641:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4642:     
 4643:     $result.=&build_section_inputs();
 4644:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4645:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4646: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4647: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4648: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4649: 
 4650:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4651: 
 4652:     $result.='&nbsp;<input type="button" '.
 4653:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4654: 
 4655:     $request->print($result);
 4656: 
 4657:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4658: 	&Apache::loncommon::start_data_table().
 4659: 	&Apache::loncommon::start_data_table_header_row().
 4660: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4661: 	'<th>'.&nameUserString('header').'</th>'.
 4662: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4663: 	'<th>'.&nameUserString('header').'</th>'.
 4664: 	&Apache::loncommon::end_data_table_header_row();
 4665:  
 4666:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4667:     my $ptr = 1;
 4668:     foreach my $student (sort 
 4669: 			 {
 4670: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4671: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4672: 			     }
 4673: 			     return $a cmp $b;
 4674: 			 } (keys(%$fullname))) {
 4675: 	my ($uname,$udom) = split(/:/,$student);
 4676: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4677:                                   : '</td>');
 4678: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4679: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4680: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4681: 	$studentTable.=
 4682: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4683:                          : '');
 4684: 	$ptr++;
 4685:     }
 4686:     if ($ptr%2 == 0) {
 4687: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4688: 	    &Apache::loncommon::end_data_table_row();
 4689:     }
 4690:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4691:     $studentTable.='<input type="button" '.
 4692:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4693: 
 4694:     $studentTable.=&show_grading_menu_form($symb);
 4695:     $request->print($studentTable);
 4696: 
 4697:     return '';
 4698: }
 4699: 
 4700: sub getSymbMap {
 4701:     my ($map_error) = @_;
 4702:     my $navmap = Apache::lonnavmaps::navmap->new();
 4703:     unless (ref($navmap)) {
 4704:         if (ref($map_error)) {
 4705:             $$map_error = 'navmap';
 4706:         }
 4707:         return;
 4708:     }
 4709:     my %symbx = ();
 4710:     my @titles = ();
 4711:     my $minder = 0;
 4712: 
 4713:     # Gather every sequence that has problems.
 4714:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4715: 					       1,0,1);
 4716:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4717: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4718: 	    my $title = $minder.'.'.
 4719: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4720: 	    push(@titles, $title); # minder in case two titles are identical
 4721: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4722: 	    $minder++;
 4723: 	}
 4724:     }
 4725:     return \@titles,\%symbx;
 4726: }
 4727: 
 4728: #
 4729: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4730: sub displayPage {
 4731:     my ($request) = shift;
 4732: 
 4733:     my ($symb) = &get_symb($request);
 4734:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4735:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4736:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4737:     my $pageTitle = $env{'form.page'};
 4738:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4739:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4740:     my $usec=$classlist->{$env{'form.student'}}[5];
 4741: 
 4742:     #need to make sure we have the correct data for later EXT calls, 
 4743:     #thus invalidate the cache
 4744:     &Apache::lonnet::devalidatecourseresdata(
 4745:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4746:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4747:     &Apache::lonnet::clear_EXT_cache_status();
 4748: 
 4749:     if (!&canview($usec)) {
 4750: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4751: 	$request->print(&show_grading_menu_form($symb));
 4752: 	return;
 4753:     }
 4754:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4755:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4756: 	'</h3>'."\n";
 4757:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4758:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4759: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4760:     } else {
 4761: 	delete($env{'form.CODE'});
 4762:     }
 4763:     &sub_page_js($request);
 4764:     $request->print($result);
 4765: 
 4766:     my $navmap = Apache::lonnavmaps::navmap->new();
 4767:     unless (ref($navmap)) {
 4768:         $request->print(&navmap_errormsg());
 4769:         $request->print(&show_grading_menu_form($symb));
 4770:         return;
 4771:     }
 4772:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4773:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4774:     if (!$map) {
 4775: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4776: 	$request->print(&show_grading_menu_form($symb));
 4777: 	return; 
 4778:     }
 4779:     my $iterator = $navmap->getIterator($map->map_start(),
 4780: 					$map->map_finish());
 4781: 
 4782:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4783: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4784: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4785: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4786: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4787: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4788: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4789: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4790: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4791: 
 4792:     if (defined($env{'form.CODE'})) {
 4793: 	$studentTable.=
 4794: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4795:     }
 4796:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4797: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4798: 
 4799:     $studentTable.='&nbsp;<span class="LC_info">'.
 4800:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4801:         '</span>'."\n".
 4802: 	&Apache::loncommon::start_data_table().
 4803: 	&Apache::loncommon::start_data_table_header_row().
 4804: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4805: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4806: 	&Apache::loncommon::end_data_table_header_row();
 4807: 
 4808:     &Apache::lonxml::clear_problem_counter();
 4809:     my ($depth,$question,$prob) = (1,1,1);
 4810:     $iterator->next(); # skip the first BEGIN_MAP
 4811:     my $curRes = $iterator->next(); # for "current resource"
 4812:     while ($depth > 0) {
 4813:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4814:         if($curRes == $iterator->END_MAP) { $depth--; }
 4815: 
 4816:         if (ref($curRes) && $curRes->is_problem()) {
 4817: 	    my $parts = $curRes->parts();
 4818:             my $title = $curRes->compTitle();
 4819: 	    my $symbx = $curRes->symb();
 4820: 	    $studentTable.=
 4821: 		&Apache::loncommon::start_data_table_row().
 4822: 		'<td align="center" valign="top" >'.$prob.
 4823: 		(scalar(@{$parts}) == 1 ? '' 
 4824: 		                        : '<br />('.&mt('[_1]parts',
 4825: 							scalar(@{$parts}).'&nbsp;').')'
 4826: 		 ).
 4827: 		 '</td>';
 4828: 	    $studentTable.='<td valign="top">';
 4829: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4830: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4831: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4832: 					     undef,'both',\%form);
 4833: 	    } else {
 4834: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4835: 		$companswer =~ s|<form(.*?)>||g;
 4836: 		$companswer =~ s|</form>||g;
 4837: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4838: #		    $companswer =~ s/$1/ /ms;
 4839: #		    $request->print('match='.$1."<br />\n");
 4840: #		}
 4841: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4842: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4843: 	    }
 4844: 
 4845: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4846: 
 4847: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4848: 		if ($record{'version'} eq '') {
 4849: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4850: 		} else {
 4851: 		    my %responseType = ();
 4852: 		    foreach my $partid (@{$parts}) {
 4853: 			my @responseIds =$curRes->responseIds($partid);
 4854: 			my @responseType =$curRes->responseType($partid);
 4855: 			my %responseIds;
 4856: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4857: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4858: 			}
 4859: 			$responseType{$partid} = \%responseIds;
 4860: 		    }
 4861: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4862: 
 4863: 		}
 4864: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4865: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4866: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4867: 									$env{'request.course.id'},
 4868: 									'','.submission');
 4869:  
 4870: 	    }
 4871: 	    if (&canmodify($usec)) {
 4872:             $studentTable.=&gradeBox_start();
 4873: 		foreach my $partid (@{$parts}) {
 4874: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4875: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4876: 		    $question++;
 4877: 		}
 4878:             $studentTable.=&gradeBox_end();
 4879: 		$prob++;
 4880: 	    }
 4881: 	    $studentTable.='</td></tr>';
 4882: 
 4883: 	}
 4884:         $curRes = $iterator->next();
 4885:     }
 4886: 
 4887:     $studentTable.=
 4888:         '</table>'."\n".
 4889:         '<input type="button" value="'.&mt('Save').'" '.
 4890:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4891:         '</form>'."\n";
 4892:     $studentTable.=&show_grading_menu_form($symb);
 4893:     $request->print($studentTable);
 4894: 
 4895:     return '';
 4896: }
 4897: 
 4898: sub displaySubByDates {
 4899:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4900:     my $isCODE=0;
 4901:     my $isTask = ($symb =~/\.task$/);
 4902:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4903:     my $studentTable=&Apache::loncommon::start_data_table().
 4904: 	&Apache::loncommon::start_data_table_header_row().
 4905: 	'<th>'.&mt('Date/Time').'</th>'.
 4906: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4907:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4908: 	'<th>'.&mt('Submission').'</th>'.
 4909: 	'<th>'.&mt('Status').'</th>'.
 4910: 	&Apache::loncommon::end_data_table_header_row();
 4911:     my ($version);
 4912:     my %mark;
 4913:     my %orders;
 4914:     $mark{'correct_by_student'} = $checkIcon;
 4915:     if (!exists($$record{'1:timestamp'})) {
 4916: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4917:     }
 4918: 
 4919:     my $interaction;
 4920:     my $no_increment = 1;
 4921:     my %lastrndseed;
 4922:     for ($version=1;$version<=$$record{'version'};$version++) {
 4923: 	my $timestamp = 
 4924: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4925: 	if (exists($$record{$version.':resource.0.version'})) {
 4926: 	    $interaction = $$record{$version.':resource.0.version'};
 4927: 	}
 4928:         if ($isTask && $env{'form.previousversion'}) {
 4929:             next unless ($interaction == $env{'form.previousversion'});
 4930:         }
 4931: 	my $where = ($isTask ? "$version:resource.$interaction"
 4932: 		             : "$version:resource");
 4933: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4934: 	    '<td>'.$timestamp.'</td>';
 4935: 	if ($isCODE) {
 4936: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4937: 	}
 4938:         if ($isTask) {
 4939:             $studentTable.='<td>'.$interaction.'</td>';
 4940:         }
 4941: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4942: 	my @displaySub = ();
 4943: 	foreach my $partid (@{$parts}) {
 4944:             my ($hidden,$type);
 4945:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4946:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4947:                 $hidden = 1;
 4948:             }
 4949: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4950: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4951: 	    
 4952: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4953: 	    my $display_part=&get_display_part($partid,$symb);
 4954: 	    foreach my $matchKey (@matchKey) {
 4955: 		if (exists($$record{$version.':'.$matchKey}) &&
 4956: 		    $$record{$version.':'.$matchKey} ne '') {
 4957:                     
 4958: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4959: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4960:                     $displaySub[0].='<span class="LC_nobreak">';
 4961:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4962:                                    .' <span class="LC_internal_info">'
 4963:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4964:                                    .'</span>'
 4965:                                    .' <b>';
 4966:                     if ($hidden) {
 4967:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4968:                     } else {
 4969:                         my ($trial,$rndseed,$newvariation);
 4970:                         if ($type eq 'randomizetry') {
 4971:                             $trial = $$record{"$where.$partid.tries"};
 4972:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4973:                         }
 4974: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4975: 			    $displaySub[0].=&mt('Trial not counted');
 4976: 		        } else {
 4977: 			    $displaySub[0].=&mt('Trial: [_1]',
 4978: 					    $$record{"$where.$partid.tries"});
 4979:                             if ($rndseed || $lastrndseed{$partid}) {
 4980:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4981:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4982:                                 }
 4983:                             }
 4984: 		        }
 4985: 		        my $responseType=($isTask ? 'Task'
 4986:                                               : $responseType->{$partid}->{$responseId});
 4987: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4988: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4989: 			    $orders{$partid}->{$responseId}=
 4990: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4991:                                            $no_increment,$type,$trial,$rndseed);
 4992: 		        }
 4993: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4994: 		        $displaySub[0].='&nbsp; '.
 4995: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4996:                     }
 4997: 		}
 4998: 	    }
 4999: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5000: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5001: 				    $$record{"$where.$partid.checkedin"},
 5002: 				    $$record{"$where.$partid.checkedin.slot"}).
 5003: 					'<br />';
 5004: 	    }
 5005: 	    if (exists $$record{"$where.$partid.award"}) {
 5006: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5007: 		    lc($$record{"$where.$partid.award"}).' '.
 5008: 		    $mark{$$record{"$where.$partid.solved"}}.
 5009: 		    '<br />';
 5010: 	    }
 5011: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5012: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5013: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5014: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5015: 		$displaySub[2].=
 5016: 		    $$record{"$version:resource.$partid.regrader"}.
 5017: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5018: 	    }
 5019: 	}
 5020: 	# needed because old essay regrader has not parts info
 5021: 	if (exists $$record{"$version:resource.regrader"}) {
 5022: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5023: 	}
 5024: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5025: 	if ($displaySub[2]) {
 5026: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5027: 	}
 5028: 	$studentTable.='&nbsp;</td>'.
 5029: 	    &Apache::loncommon::end_data_table_row();
 5030:     }
 5031:     $studentTable.=&Apache::loncommon::end_data_table();
 5032:     return $studentTable;
 5033: }
 5034: 
 5035: sub updateGradeByPage {
 5036:     my ($request) = shift;
 5037: 
 5038:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5039:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5040:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5041:     my $pageTitle = $env{'form.page'};
 5042:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5043:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5044:     my $usec=$classlist->{$env{'form.student'}}[5];
 5045:     if (!&canmodify($usec)) {
 5046: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5047: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5048: 	return;
 5049:     }
 5050:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5051:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5052: 	'</h3>'."\n";
 5053: 
 5054:     $request->print($result);
 5055: 
 5056: 
 5057:     my $navmap = Apache::lonnavmaps::navmap->new();
 5058:     unless (ref($navmap)) {
 5059:         $request->print(&navmap_errormsg());
 5060:         return;
 5061:     }
 5062:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5063:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5064:     if (!$map) {
 5065: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5066: 	my ($symb)=&get_symb($request);
 5067: 	$request->print(&show_grading_menu_form($symb));
 5068: 	return; 
 5069:     }
 5070:     my $iterator = $navmap->getIterator($map->map_start(),
 5071: 					$map->map_finish());
 5072: 
 5073:     my $studentTable=
 5074: 	&Apache::loncommon::start_data_table().
 5075: 	&Apache::loncommon::start_data_table_header_row().
 5076: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5077: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5078: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5079: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5080: 	&Apache::loncommon::end_data_table_header_row();
 5081: 
 5082:     $iterator->next(); # skip the first BEGIN_MAP
 5083:     my $curRes = $iterator->next(); # for "current resource"
 5084:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 5085:     while ($depth > 0) {
 5086:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5087:         if($curRes == $iterator->END_MAP) { $depth--; }
 5088: 
 5089:         if (ref($curRes) && $curRes->is_problem()) {
 5090: 	    my $parts = $curRes->parts();
 5091:             my $title = $curRes->compTitle();
 5092: 	    my $symbx = $curRes->symb();
 5093: 	    $studentTable.=
 5094: 		&Apache::loncommon::start_data_table_row().
 5095: 		'<td align="center" valign="top" >'.$prob.
 5096: 		(scalar(@{$parts}) == 1 ? '' 
 5097:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5098: 		.')').'</td>';
 5099: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5100: 
 5101: 	    my %newrecord=();
 5102: 	    my @displayPts=();
 5103:             my %aggregate = ();
 5104:             my $aggregateflag = 0;
 5105: 	    foreach my $partid (@{$parts}) {
 5106: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5107: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5108: 
 5109: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5110: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5111: 		my $partial = $newpts/$wgt;
 5112: 		my $score;
 5113: 		if ($partial > 0) {
 5114: 		    $score = 'correct_by_override';
 5115: 		} elsif ($newpts ne '') { #empty is taken as 0
 5116: 		    $score = 'incorrect_by_override';
 5117: 		}
 5118: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5119: 		if ($dropMenu eq 'excused') {
 5120: 		    $partial = '';
 5121: 		    $score = 'excused';
 5122: 		} elsif ($dropMenu eq 'reset status'
 5123: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5124: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5125: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5126: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5127: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5128: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5129: 		    $changeflag++;
 5130: 		    $newpts = '';
 5131:                     
 5132:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5133:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5134:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5135:                     if ($aggtries > 0) {
 5136:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5137:                         $aggregateflag = 1;
 5138:                     }
 5139: 		}
 5140: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5141: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5142: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5143: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5144: 		    '&nbsp;<br />';
 5145: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5146: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5147: 		    '&nbsp;<br />';
 5148: 		$question++;
 5149: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5150: 
 5151: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5152: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5153: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5154: 		    if (scalar(keys(%newrecord)) > 0);
 5155: 
 5156: 		$changeflag++;
 5157: 	    }
 5158: 	    if (scalar(keys(%newrecord)) > 0) {
 5159: 		my %record = 
 5160: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5161: 					     $udom,$uname);
 5162: 
 5163: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5164: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5165: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5166: 		    $newrecord{'resource.CODE'} = '';
 5167: 		}
 5168: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5169: 					$udom,$uname);
 5170: 		%record = &Apache::lonnet::restore($symbx,
 5171: 						   $env{'request.course.id'},
 5172: 						   $udom,$uname);
 5173: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5174: 					     $cdom,$cnum,$udom,$uname);
 5175: 	    }
 5176: 	    
 5177:             if ($aggregateflag) {
 5178:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5179:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5180:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5181:             }
 5182: 
 5183: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5184: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5185: 		&Apache::loncommon::end_data_table_row();
 5186: 
 5187: 	    $prob++;
 5188: 	}
 5189:         $curRes = $iterator->next();
 5190:     }
 5191: 
 5192:     $studentTable.=&Apache::loncommon::end_data_table();
 5193:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5194:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5195: 		  &mt('The scores were changed for [quant,_1,problem].',
 5196: 		  $changeflag));
 5197:     $request->print($grademsg.$studentTable);
 5198: 
 5199:     return '';
 5200: }
 5201: 
 5202: #-------- end of section for handling grading by page/sequence ---------
 5203: #
 5204: #-------------------------------------------------------------------
 5205: 
 5206: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5207: #
 5208: #------ start of section for handling grading by page/sequence ---------
 5209: 
 5210: =pod
 5211: 
 5212: =head1 Bubble sheet grading routines
 5213: 
 5214:   For this documentation:
 5215: 
 5216:    'scanline' refers to the full line of characters
 5217:    from the file that we are parsing that represents one entire sheet
 5218: 
 5219:    'bubble line' refers to the data
 5220:    representing the line of bubbles that are on the physical bubblesheet
 5221: 
 5222: 
 5223: The overall process is that a scanned in bubblesheet data is uploaded
 5224: into a course. When a user wants to grade, they select a
 5225: sequence/folder of resources, a file of bubblesheet info, and pick
 5226: one of the predefined configurations for what each scanline looks
 5227: like.
 5228: 
 5229: Next each scanline is checked for any errors of either 'missing
 5230: bubbles' (it's an error because it may have been mis-scanned
 5231: because too light bubbling), 'double bubble' (each bubble line should
 5232: have no more that one letter picked), invalid or duplicated CODE,
 5233: invalid student/employee ID
 5234: 
 5235: If the CODE option is used that determines the randomization of the
 5236: homework problems, either way the student/employee ID is looked up into a
 5237: username:domain.
 5238: 
 5239: During the validation phase the instructor can choose to skip scanlines. 
 5240: 
 5241: After the validation phase, there are now 3 bubblesheet files
 5242: 
 5243:   scantron_original_filename (unmodified original file)
 5244:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5245:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5246: 
 5247: Also there is a separate hash nohist_scantrondata that contains extra
 5248: correction information that isn't representable in the bubblesheet
 5249: file (see &scantron_getfile() for more information)
 5250: 
 5251: After all scanlines are either valid, marked as valid or skipped, then
 5252: foreach line foreach problem in the picked sequence, an ssi request is
 5253: made that simulates a user submitting their selected letter(s) against
 5254: the homework problem.
 5255: 
 5256: =over 4
 5257: 
 5258: 
 5259: 
 5260: =item defaultFormData
 5261: 
 5262:   Returns html hidden inputs used to hold context/default values.
 5263: 
 5264:  Arguments:
 5265:   $symb - $symb of the current resource 
 5266: 
 5267: =cut
 5268: 
 5269: sub defaultFormData {
 5270:     my ($symb)=@_;
 5271:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5272:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5273:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5274: }
 5275: 
 5276: 
 5277: =pod 
 5278: 
 5279: =item getSequenceDropDown
 5280: 
 5281:    Return html dropdown of possible sequences to grade
 5282:  
 5283:  Arguments:
 5284:    $symb - $symb of the current resource
 5285:    $map_error - ref to scalar which will container error if
 5286:                 $navmap object is unavailable in &getSymbMap().
 5287: 
 5288: =cut
 5289: 
 5290: sub getSequenceDropDown {
 5291:     my ($symb,$map_error)=@_;
 5292:     my $result='<select name="selectpage">'."\n";
 5293:     my ($titles,$symbx) = &getSymbMap($map_error);
 5294:     if (ref($map_error)) {
 5295:         return if ($$map_error);
 5296:     }
 5297:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5298:     my $ctr=0;
 5299:     foreach (@$titles) {
 5300: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5301: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5302: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5303: 	    '>'.$showtitle.'</option>'."\n";
 5304: 	$ctr++;
 5305:     }
 5306:     $result.= '</select>';
 5307:     return $result;
 5308: }
 5309: 
 5310: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5311:                                    # key is zero-based index - 0, 1, 2 ...
 5312: 
 5313: my %first_bubble_line;             # First bubble line no. for each bubble.
 5314: 
 5315: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5316:                                    # matchresponse or rankresponse, where 
 5317:                                    # an individual response can have multiple 
 5318:                                    # lines
 5319: 
 5320: my %responsetype_per_response;     # responsetype for each response
 5321: 
 5322: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5323:                                    # numbered response. Needed when randomorder
 5324:                                    # or randompick are in use. Key is ID, value 
 5325:                                    # is response number.
 5326: 
 5327: # Save and restore the bubble lines array to the form env.
 5328: 
 5329: 
 5330: sub save_bubble_lines {
 5331:     foreach my $line (keys(%bubble_lines_per_response)) {
 5332: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5333: 	$env{"form.scantron.first_bubble_line.$line"} =
 5334: 	    $first_bubble_line{$line};
 5335:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5336:             $subdivided_bubble_lines{$line};
 5337:         $env{"form.scantron.responsetype.$line"} =
 5338:             $responsetype_per_response{$line};
 5339:     }
 5340:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5341:         my $line = $masterseq_id_responsenum{$resid};
 5342:         $env{"form.scantron.residpart.$line"} = $resid;
 5343:     }
 5344: }
 5345: 
 5346: 
 5347: sub restore_bubble_lines {
 5348:     my $line = 0;
 5349:     %bubble_lines_per_response = ();
 5350:     %masterseq_id_responsenum = ();
 5351:     while ($env{"form.scantron.bubblelines.$line"}) {
 5352: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5353: 	$bubble_lines_per_response{$line} = $value;
 5354: 	$first_bubble_line{$line}  =
 5355: 	    $env{"form.scantron.first_bubble_line.$line"};
 5356:         $subdivided_bubble_lines{$line} =
 5357:             $env{"form.scantron.sub_bubblelines.$line"};
 5358:         $responsetype_per_response{$line} =
 5359:             $env{"form.scantron.responsetype.$line"};
 5360:         my $id = $env{"form.scantron.residpart.$line"};
 5361:         $masterseq_id_responsenum{$id} = $line;
 5362: 	$line++;
 5363:     }
 5364: }
 5365: 
 5366: =pod 
 5367: 
 5368: =item scantron_filenames
 5369: 
 5370:    Returns a list of the scantron files in the current course 
 5371: 
 5372: =cut
 5373: 
 5374: sub scantron_filenames {
 5375:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5376:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5377:     my $getpropath = 1;
 5378:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5379:                                                         $cname,$getpropath);
 5380:     my @possiblenames;
 5381:     if (ref($dirlist) eq 'ARRAY') {
 5382:         foreach my $filename (sort(@{$dirlist})) {
 5383: 	    ($filename)=split(/&/,$filename);
 5384: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5385: 	    $filename=~s/^scantron_orig_//;
 5386: 	    push(@possiblenames,$filename);
 5387:         }
 5388:     }
 5389:     return @possiblenames;
 5390: }
 5391: 
 5392: =pod 
 5393: 
 5394: =item scantron_uploads
 5395: 
 5396:    Returns  html drop-down list of scantron files in current course.
 5397: 
 5398:  Arguments:
 5399:    $file2grade - filename to set as selected in the dropdown
 5400: 
 5401: =cut
 5402: 
 5403: sub scantron_uploads {
 5404:     my ($file2grade) = @_;
 5405:     my $result=	'<select name="scantron_selectfile">';
 5406:     $result.="<option></option>";
 5407:     foreach my $filename (sort(&scantron_filenames())) {
 5408: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5409:     }
 5410:     $result.="</select>";
 5411:     return $result;
 5412: }
 5413: 
 5414: =pod 
 5415: 
 5416: =item scantron_scantab
 5417: 
 5418:   Returns html drop down of the scantron formats in the scantronformat.tab
 5419:   file.
 5420: 
 5421: =cut
 5422: 
 5423: sub scantron_scantab {
 5424:     my $result='<select name="scantron_format">'."\n";
 5425:     $result.='<option></option>'."\n";
 5426:     my @lines = &get_scantronformat_file();
 5427:     if (@lines > 0) {
 5428:         foreach my $line (@lines) {
 5429:             next if (($line =~ /^\#/) || ($line eq ''));
 5430: 	    my ($name,$descrip)=split(/:/,$line);
 5431: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5432:         }
 5433:     }
 5434:     $result.='</select>'."\n";
 5435:     return $result;
 5436: }
 5437: 
 5438: =pod
 5439: 
 5440: =item get_scantronformat_file
 5441: 
 5442:   Returns an array containing lines from the scantron format file for
 5443:   the domain of the course.
 5444: 
 5445:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5446:   lines are from this file.
 5447: 
 5448:   Otherwise, if a default.tab has been published in RES space by the 
 5449:   domainconfig user, lines are from this file.
 5450: 
 5451:   Otherwise, fall back to getting lines from the legacy file on the
 5452:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5453: 
 5454: =cut
 5455: 
 5456: sub get_scantronformat_file {
 5457:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5458:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5459:     my $gottab = 0;
 5460:     my @lines;
 5461:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5462:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5463:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5464:             if ($formatfile ne '-1') {
 5465:                 @lines = split("\n",$formatfile,-1);
 5466:                 $gottab = 1;
 5467:             }
 5468:         }
 5469:     }
 5470:     if (!$gottab) {
 5471:         my $confname = $cdom.'-domainconfig';
 5472:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5473:         my $formatfile =  &Apache::lonnet::getfile($default);
 5474:         if ($formatfile ne '-1') {
 5475:             @lines = split("\n",$formatfile,-1);
 5476:             $gottab = 1;
 5477:         }
 5478:     }
 5479:     if (!$gottab) {
 5480:         my @domains = &Apache::lonnet::current_machine_domains();
 5481:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5482:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5483:             @lines = <$fh>;
 5484:             close($fh);
 5485:         } else {
 5486:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5487:             @lines = <$fh>;
 5488:             close($fh);
 5489:         }
 5490:     }
 5491:     return @lines;
 5492: }
 5493: 
 5494: =pod 
 5495: 
 5496: =item scantron_CODElist
 5497: 
 5498:   Returns html drop down of the saved CODE lists from current course,
 5499:   generated from earlier printings.
 5500: 
 5501: =cut
 5502: 
 5503: sub scantron_CODElist {
 5504:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5505:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5506:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5507:     my $namechoice='<option></option>';
 5508:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5509: 	if ($name =~ /^error: 2 /) { next; }
 5510: 	if ($name =~ /^type\0/) { next; }
 5511: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5512:     }
 5513:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5514:     return $namechoice;
 5515: }
 5516: 
 5517: =pod 
 5518: 
 5519: =item scantron_CODEunique
 5520: 
 5521:   Returns the html for "Each CODE to be used once" radio.
 5522: 
 5523: =cut
 5524: 
 5525: sub scantron_CODEunique {
 5526:     my $result='<span class="LC_nobreak">
 5527:                  <label><input type="radio" name="scantron_CODEunique"
 5528:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5529:                 </span>
 5530:                 <span class="LC_nobreak">
 5531:                  <label><input type="radio" name="scantron_CODEunique"
 5532:                         value="no" />'.&mt('No').' </label>
 5533:                 </span>';
 5534:     return $result;
 5535: }
 5536: 
 5537: =pod 
 5538: 
 5539: =item scantron_selectphase
 5540: 
 5541:   Generates the initial screen to start the bubblesheet process.
 5542:   Allows for - starting a grading run.
 5543:              - downloading existing scan data (original, corrected
 5544:                                                 or skipped info)
 5545: 
 5546:              - uploading new scan data
 5547: 
 5548:  Arguments:
 5549:   $r          - The Apache request object
 5550:   $file2grade - name of the file that contain the scanned data to score
 5551: 
 5552: =cut
 5553: 
 5554: sub scantron_selectphase {
 5555:     my ($r,$file2grade) = @_;
 5556:     my ($symb)=&get_symb($r);
 5557:     if (!$symb) {return '';}
 5558:     my $map_error;
 5559:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5560:     if ($map_error) {
 5561:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5562:         return;
 5563:     }
 5564:     my $default_form_data=&defaultFormData($symb);
 5565:     my $grading_menu_button=&show_grading_menu_form($symb);
 5566:     my $file_selector=&scantron_uploads($file2grade);
 5567:     my $format_selector=&scantron_scantab();
 5568:     my $CODE_selector=&scantron_CODElist();
 5569:     my $CODE_unique=&scantron_CODEunique();
 5570:     my $result;
 5571: 
 5572:     $ssi_error = 0;
 5573: 
 5574:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5575:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5576: 
 5577:         # Chunk of form to prompt for a scantron file upload.
 5578: 
 5579:         $r->print('
 5580:     <br />
 5581:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5582:        '.&Apache::loncommon::start_data_table_header_row().'
 5583:             <th>
 5584:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5585:             </th>
 5586:        '.&Apache::loncommon::end_data_table_header_row().'
 5587:        '.&Apache::loncommon::start_data_table_row().'
 5588:             <td>
 5589: ');
 5590:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5591:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5592:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5593:     $r->print('
 5594:               <script type="text/javascript" language="javascript">
 5595:     function checkUpload(formname) {
 5596:         if (formname.upfile.value == "") {
 5597:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5598:             return false;
 5599:         }
 5600:         formname.submit();
 5601:     }
 5602:               </script>
 5603: 
 5604:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5605:                 '.$default_form_data.'
 5606:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5607:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5608:                 <input name="command" value="scantronupload_save" type="hidden" />
 5609:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5610:                 <br />
 5611:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5612:               </form>
 5613: ');
 5614: 
 5615:         $r->print('
 5616:             </td>
 5617:        '.&Apache::loncommon::end_data_table_row().'
 5618:        '.&Apache::loncommon::end_data_table().'
 5619: ');
 5620:     }
 5621: 
 5622:     # Chunk of form to prompt for a file to grade and how:
 5623: 
 5624:     $result.= '
 5625:     <br />
 5626:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5627:     <input type="hidden" name="command" value="scantron_warning" />
 5628:     '.$default_form_data.'
 5629:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5630:        '.&Apache::loncommon::start_data_table_header_row().'
 5631:             <th colspan="2">
 5632:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5633:             </th>
 5634:        '.&Apache::loncommon::end_data_table_header_row().'
 5635:        '.&Apache::loncommon::start_data_table_row().'
 5636:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5637:        '.&Apache::loncommon::end_data_table_row().'
 5638:        '.&Apache::loncommon::start_data_table_row().'
 5639:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5640:        '.&Apache::loncommon::end_data_table_row().'
 5641:        '.&Apache::loncommon::start_data_table_row().'
 5642:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5643:        '.&Apache::loncommon::end_data_table_row().'
 5644:        '.&Apache::loncommon::start_data_table_row().'
 5645:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5646:        '.&Apache::loncommon::end_data_table_row().'
 5647:        '.&Apache::loncommon::start_data_table_row().'
 5648:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5649:        '.&Apache::loncommon::end_data_table_row().'
 5650:        '.&Apache::loncommon::start_data_table_row().'
 5651: 	    <td> '.&mt('Options:').' </td>
 5652:             <td>
 5653: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5654:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5655:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5656: 	    </td>
 5657:        '.&Apache::loncommon::end_data_table_row().'
 5658:        '.&Apache::loncommon::start_data_table_row().'
 5659:             <td colspan="2">
 5660:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5661:             </td>
 5662:        '.&Apache::loncommon::end_data_table_row().'
 5663:     '.&Apache::loncommon::end_data_table().'
 5664:     </form>
 5665: ';
 5666:    
 5667:     $r->print($result);
 5668: 
 5669:     # Chunk of the form that prompts to view a scoring office file,
 5670:     # corrected file, skipped records in a file.
 5671: 
 5672:     $r->print('
 5673:    <br />
 5674:    <form action="/adm/grades" name="scantron_download">
 5675:      '.$default_form_data.'
 5676:      <input type="hidden" name="command" value="scantron_download" />
 5677:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5678:        '.&Apache::loncommon::start_data_table_header_row().'
 5679:               <th>
 5680:                 &nbsp;'.&mt('Download a scoring office file').'
 5681:               </th>
 5682:        '.&Apache::loncommon::end_data_table_header_row().'
 5683:        '.&Apache::loncommon::start_data_table_row().'
 5684:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5685:                 <br />
 5686:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5687:        '.&Apache::loncommon::end_data_table_row().'
 5688:      '.&Apache::loncommon::end_data_table().'
 5689:    </form>
 5690:    <br />
 5691: ');
 5692: 
 5693:     &Apache::lonpickcode::code_list($r,2);
 5694: 
 5695:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5696:              $default_form_data."\n".
 5697:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5698:              &Apache::loncommon::start_data_table_header_row()."\n".
 5699:              '<th colspan="2">
 5700:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5701:              '</th>'."\n".
 5702:               &Apache::loncommon::end_data_table_header_row()."\n".
 5703:               &Apache::loncommon::start_data_table_row()."\n".
 5704:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5705:               '<td> '.$sequence_selector.' </td>'.
 5706:               &Apache::loncommon::end_data_table_row()."\n".
 5707:               &Apache::loncommon::start_data_table_row()."\n".
 5708:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5709:               '<td> '.$file_selector.' </td>'."\n".
 5710:               &Apache::loncommon::end_data_table_row()."\n".
 5711:               &Apache::loncommon::start_data_table_row()."\n".
 5712:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5713:               '<td> '.$format_selector.' </td>'."\n".
 5714:               &Apache::loncommon::end_data_table_row()."\n".
 5715:               &Apache::loncommon::start_data_table_row()."\n".
 5716:               '<td> '.&mt('Options').' </td>'."\n".
 5717:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5718:               &Apache::loncommon::end_data_table_row()."\n".
 5719:               &Apache::loncommon::start_data_table_row()."\n".
 5720:               '<td colspan="2">'."\n".
 5721:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5722:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5723:               '</td>'."\n".
 5724:               &Apache::loncommon::end_data_table_row()."\n".
 5725:               &Apache::loncommon::end_data_table()."\n".
 5726:               '</form><br />');
 5727:     $r->print($grading_menu_button);
 5728:     return;
 5729: }
 5730: 
 5731: =pod
 5732: 
 5733: =item get_scantron_config
 5734: 
 5735:    Parse and return the scantron configuration line selected as a
 5736:    hash of configuration file fields.
 5737: 
 5738:  Arguments:
 5739:     which - the name of the configuration to parse from the file.
 5740: 
 5741: 
 5742:  Returns:
 5743:             If the named configuration is not in the file, an empty
 5744:             hash is returned.
 5745:     a hash with the fields
 5746:       name         - internal name for the this configuration setup
 5747:       description  - text to display to operator that describes this config
 5748:       CODElocation - if 0 or the string 'none'
 5749:                           - no CODE exists for this config
 5750:                      if -1 || the string 'letter'
 5751:                           - a CODE exists for this config and is
 5752:                             a string of letters
 5753:                      Unsupported value (but planned for future support)
 5754:                           if a positive integer
 5755:                                - The CODE exists as the first n items from
 5756:                                  the question section of the form
 5757:                           if the string 'number'
 5758:                                - The CODE exists for this config and is
 5759:                                  a string of numbers
 5760:       CODEstart   - (only matter if a CODE exists) column in the line where
 5761:                      the CODE starts
 5762:       CODElength  - length of the CODE
 5763:       IDstart     - column where the student/employee ID starts
 5764:       IDlength    - length of the student/employee ID info
 5765:       Qstart      - column where the information from the bubbled
 5766:                     'questions' start
 5767:       Qlength     - number of columns comprising a single bubble line from
 5768:                     the sheet. (usually either 1 or 10)
 5769:       Qon         - either a single character representing the character used
 5770:                     to signal a bubble was chosen in the positional setup, or
 5771:                     the string 'letter' if the letter of the chosen bubble is
 5772:                     in the final, or 'number' if a number representing the
 5773:                     chosen bubble is in the file (1->A 0->J)
 5774:       Qoff        - the character used to represent that a bubble was
 5775:                     left blank
 5776:       PaperID     - if the scanning process generates a unique number for each
 5777:                     sheet scanned the column that this ID number starts in
 5778:       PaperIDlength - number of columns that comprise the unique ID number
 5779:                       for the sheet of paper
 5780:       FirstName   - column that the first name starts in
 5781:       FirstNameLength - number of columns that the first name spans
 5782:  
 5783:       LastName    - column that the last name starts in
 5784:       LastNameLength - number of columns that the last name spans
 5785:       BubblesPerRow - number of bubbles available in each row used to
 5786:                       bubble an answer. (If not specified, 10 assumed).
 5787: 
 5788: =cut
 5789: 
 5790: sub get_scantron_config {
 5791:     my ($which) = @_;
 5792:     my @lines = &get_scantronformat_file();
 5793:     my %config;
 5794:     #FIXME probably should move to XML it has already gotten a bit much now
 5795:     foreach my $line (@lines) {
 5796: 	my ($name,$descrip)=split(/:/,$line);
 5797: 	if ($name ne $which ) { next; }
 5798: 	chomp($line);
 5799: 	my @config=split(/:/,$line);
 5800: 	$config{'name'}=$config[0];
 5801: 	$config{'description'}=$config[1];
 5802: 	$config{'CODElocation'}=$config[2];
 5803: 	$config{'CODEstart'}=$config[3];
 5804: 	$config{'CODElength'}=$config[4];
 5805: 	$config{'IDstart'}=$config[5];
 5806: 	$config{'IDlength'}=$config[6];
 5807: 	$config{'Qstart'}=$config[7];
 5808:  	$config{'Qlength'}=$config[8];
 5809: 	$config{'Qoff'}=$config[9];
 5810: 	$config{'Qon'}=$config[10];
 5811: 	$config{'PaperID'}=$config[11];
 5812: 	$config{'PaperIDlength'}=$config[12];
 5813: 	$config{'FirstName'}=$config[13];
 5814: 	$config{'FirstNamelength'}=$config[14];
 5815: 	$config{'LastName'}=$config[15];
 5816: 	$config{'LastNamelength'}=$config[16];
 5817:         $config{'BubblesPerRow'}=$config[17];
 5818: 	last;
 5819:     }
 5820:     return %config;
 5821: }
 5822: 
 5823: =pod 
 5824: 
 5825: =item username_to_idmap
 5826: 
 5827:     creates a hash keyed by student/employee ID with values of the corresponding
 5828:     student username:domain.
 5829: 
 5830:   Arguments:
 5831: 
 5832:     $classlist - reference to the class list hash. This is a hash
 5833:                  keyed by student name:domain  whose elements are references
 5834:                  to arrays containing various chunks of information
 5835:                  about the student. (See loncoursedata for more info).
 5836: 
 5837:   Returns
 5838:     %idmap - the constructed hash
 5839: 
 5840: =cut
 5841: 
 5842: sub username_to_idmap {
 5843:     my ($classlist)= @_;
 5844:     my %idmap;
 5845:     foreach my $student (keys(%$classlist)) {
 5846: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5847: 	    $student;
 5848:     }
 5849:     return %idmap;
 5850: }
 5851: 
 5852: =pod
 5853: 
 5854: =item scantron_fixup_scanline
 5855: 
 5856:    Process a requested correction to a scanline.
 5857: 
 5858:   Arguments:
 5859:     $scantron_config   - hash from &get_scantron_config()
 5860:     $scan_data         - hash of correction information 
 5861:                           (see &scantron_getfile())
 5862:     $line              - existing scanline
 5863:     $whichline         - line number of the passed in scanline
 5864:     $field             - type of change to process 
 5865:                          (either 
 5866:                           'ID'     -> correct the student/employee ID
 5867:                           'CODE'   -> correct the CODE
 5868:                           'answer' -> fixup the submitted answers)
 5869:     
 5870:    $args               - hash of additional info,
 5871:                           - 'ID' 
 5872:                                'newid' -> studentID to use in replacement
 5873:                                           of existing one
 5874:                           - 'CODE' 
 5875:                                'CODE_ignore_dup' - set to true if duplicates
 5876:                                                    should be ignored.
 5877: 	                       'CODE' - is new code or 'use_unfound'
 5878:                                         if the existing unfound code should
 5879:                                         be used as is
 5880:                           - 'answer'
 5881:                                'response' - new answer or 'none' if blank
 5882:                                'question' - the bubble line to change
 5883:                                'questionnum' - the question identifier,
 5884:                                                may include subquestion. 
 5885: 
 5886:   Returns:
 5887:     $line - the modified scanline
 5888: 
 5889:   Side effects: 
 5890:     $scan_data - may be updated
 5891: 
 5892: =cut
 5893: 
 5894: 
 5895: sub scantron_fixup_scanline {
 5896:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5897:     if ($field eq 'ID') {
 5898: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5899: 	    return ($line,1,'New value too large');
 5900: 	}
 5901: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5902: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5903: 				     $args->{'newid'});
 5904: 	}
 5905: 	substr($line,$$scantron_config{'IDstart'}-1,
 5906: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5907: 	if ($args->{'newid'}=~/^\s*$/) {
 5908: 	    &scan_data($scan_data,"$whichline.user",
 5909: 		       $args->{'username'}.':'.$args->{'domain'});
 5910: 	}
 5911:     } elsif ($field eq 'CODE') {
 5912: 	if ($args->{'CODE_ignore_dup'}) {
 5913: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5914: 	}
 5915: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5916: 	if ($args->{'CODE'} ne 'use_unfound') {
 5917: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5918: 		return ($line,1,'New CODE value too large');
 5919: 	    }
 5920: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5921: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5922: 	    }
 5923: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5924: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5925: 	}
 5926:     } elsif ($field eq 'answer') {
 5927: 	my $length=$scantron_config->{'Qlength'};
 5928: 	my $off=$scantron_config->{'Qoff'};
 5929: 	my $on=$scantron_config->{'Qon'};
 5930: 	my $answer=${off}x$length;
 5931: 	if ($args->{'response'} eq 'none') {
 5932: 	    &scan_data($scan_data,
 5933: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5934: 	} else {
 5935: 	    if ($on eq 'letter') {
 5936: 		my @alphabet=('A'..'Z');
 5937: 		$answer=$alphabet[$args->{'response'}];
 5938: 	    } elsif ($on eq 'number') {
 5939: 		$answer=$args->{'response'}+1;
 5940: 		if ($answer == 10) { $answer = '0'; }
 5941: 	    } else {
 5942: 		substr($answer,$args->{'response'},1)=$on;
 5943: 	    }
 5944: 	    &scan_data($scan_data,
 5945: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5946: 	}
 5947: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5948: 	substr($line,$where-1,$length)=$answer;
 5949:     }
 5950:     return $line;
 5951: }
 5952: 
 5953: =pod
 5954: 
 5955: =item scan_data
 5956: 
 5957:     Edit or look up  an item in the scan_data hash.
 5958: 
 5959:   Arguments:
 5960:     $scan_data  - The hash (see scantron_getfile)
 5961:     $key        - shorthand of the key to edit (actual key is
 5962:                   scantronfilename_key).
 5963:     $data        - New value of the hash entry.
 5964:     $delete      - If true, the entry is removed from the hash.
 5965: 
 5966:   Returns:
 5967:     The new value of the hash table field (undefined if deleted).
 5968: 
 5969: =cut
 5970: 
 5971: 
 5972: sub scan_data {
 5973:     my ($scan_data,$key,$value,$delete)=@_;
 5974:     my $filename=$env{'form.scantron_selectfile'};
 5975:     if (defined($value)) {
 5976: 	$scan_data->{$filename.'_'.$key} = $value;
 5977:     }
 5978:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5979:     return $scan_data->{$filename.'_'.$key};
 5980: }
 5981: 
 5982: # ----- These first few routines are general use routines.----
 5983: 
 5984: # Return the number of occurences of a pattern in a string.
 5985: 
 5986: sub occurence_count {
 5987:     my ($string, $pattern) = @_;
 5988: 
 5989:     my @matches = ($string =~ /$pattern/g);
 5990: 
 5991:     return scalar(@matches);
 5992: }
 5993: 
 5994: 
 5995: # Take a string known to have digits and convert all the
 5996: # digits into letters in the range J,A..I.
 5997: 
 5998: sub digits_to_letters {
 5999:     my ($input) = @_;
 6000: 
 6001:     my @alphabet = ('J', 'A'..'I');
 6002: 
 6003:     my @input    = split(//, $input);
 6004:     my $output ='';
 6005:     for (my $i = 0; $i < scalar(@input); $i++) {
 6006: 	if ($input[$i] =~ /\d/) {
 6007: 	    $output .= $alphabet[$input[$i]];
 6008: 	} else {
 6009: 	    $output .= $input[$i];
 6010: 	}
 6011:     }
 6012:     return $output;
 6013: }
 6014: 
 6015: =pod 
 6016: 
 6017: =item scantron_parse_scanline
 6018: 
 6019:   Decodes a scanline from the selected scantron file
 6020: 
 6021:  Arguments:
 6022:     line             - The text of the scantron file line to process
 6023:     whichline        - Line number
 6024:     scantron_config  - Hash describing the format of the scantron lines.
 6025:     scan_data        - Hash of extra information about the scanline
 6026:                        (see scantron_getfile for more information)
 6027:     just_header      - True if should not process question answers but only
 6028:                        the stuff to the left of the answers.
 6029:     randomorder      - True if randomorder in use
 6030:     randompick       - True if randompick in use
 6031:     sequence         - Exam folder URL
 6032:     master_seq       - Ref to array containing symbs in exam folder
 6033:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6034:                        (corresponding values are resource objects)
 6035:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6036:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6037:                        are refs to an array of resource objects, ordered
 6038:                        according to order used for CODE, when randomorder
 6039:                        and or randompick are in use.
 6040:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6041:                        for current line to question number used for same question
 6042:                         in "Master Sequence" (as seen by Course Coordinator).
 6043:     startline        - Ref to hash where key is question number (0 is first)
 6044:                        and value is number of first bubble line for current 
 6045:                        student or code-based randompick and/or randomorder.
 6046:     totalref         - Ref of scalar used to score total number of bubble
 6047:                        lines needed for responses in a scan line (used when
 6048:                        randompick in use. 
 6049: 
 6050:  Returns:
 6051:    Hash containing the result of parsing the scanline
 6052: 
 6053:    Keys are all proceeded by the string 'scantron.'
 6054: 
 6055:        CODE    - the CODE in use for this scanline
 6056:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6057:                  by the operator
 6058:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6059:                             CODEs were selected, but the usage has been
 6060:                             forced by the operator
 6061:        ID  - student/employee ID
 6062:        PaperID - if used, the ID number printed on the sheet when the 
 6063:                  paper was scanned
 6064:        FirstName - first name from the sheet
 6065:        LastName  - last name from the sheet
 6066: 
 6067:      if just_header was not true these key may also exist
 6068: 
 6069:        missingerror - a list of bubble ranges that are considered to be answers
 6070:                       to a single question that don't have any bubbles filled in.
 6071:                       Of the form questionnumber:firstbubblenumber:count.
 6072:        doubleerror  - a list of bubble ranges that are considered to be answers
 6073:                       to a single question that have more than one bubble filled in.
 6074:                       Of the form questionnumber::firstbubblenumber:count
 6075:    
 6076:                 In the above, count is the number of bubble responses in the
 6077:                 input line needed to represent the possible answers to the question.
 6078:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6079:                 per line would have count = 2.
 6080: 
 6081:        maxquest     - the number of the last bubble line that was parsed
 6082: 
 6083:        (<number> starts at 1)
 6084:        <number>.answer - zero or more letters representing the selected
 6085:                          letters from the scanline for the bubble line 
 6086:                          <number>.
 6087:                          if blank there was either no bubble or there where
 6088:                          multiple bubbles, (consult the keys missingerror and
 6089:                          doubleerror if this is an error condition)
 6090: 
 6091: =cut
 6092: 
 6093: sub scantron_parse_scanline {
 6094:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6095:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6096:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6097: 
 6098:     my %record;
 6099:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6100:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6101: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6102: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6103: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6104: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6105: 	    $record{'scantron.CODE'}=substr($data,
 6106: 					    $$scantron_config{'CODEstart'}-1,
 6107: 					    $$scantron_config{'CODElength'});
 6108: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6109: 		$record{'scantron.useCODE'}=1;
 6110: 	    }
 6111: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6112: 		$record{'scantron.CODE_ignore_dup'}=1;
 6113: 	    }
 6114: 	} else {
 6115: 	    #FIXME interpret first N questions
 6116: 	}
 6117:     }
 6118:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6119: 				  $$scantron_config{'IDlength'});
 6120:     $record{'scantron.PaperID'}=
 6121: 	substr($data,$$scantron_config{'PaperID'}-1,
 6122: 	       $$scantron_config{'PaperIDlength'});
 6123:     $record{'scantron.FirstName'}=
 6124: 	substr($data,$$scantron_config{'FirstName'}-1,
 6125: 	       $$scantron_config{'FirstNamelength'});
 6126:     $record{'scantron.LastName'}=
 6127: 	substr($data,$$scantron_config{'LastName'}-1,
 6128: 	       $$scantron_config{'LastNamelength'});
 6129:     if ($just_header) { return \%record; }
 6130: 
 6131:     my @alphabet=('A'..'Z');
 6132:     my $questnum=0;
 6133:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6134: 
 6135:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6136:     if ($randompick || $randomorder) {
 6137:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6138:                                          $master_seq,$symb_to_resource,
 6139:                                          $partids_by_symb,$orderedforcode,
 6140:                                          $respnumlookup,$startline);
 6141:         if ($total) {
 6142:             $lastpos = $total*$$scantron_config{'Qlength'};
 6143:         }
 6144:         if (ref($totalref)) {
 6145:             $$totalref = $total;
 6146:         }
 6147:     }
 6148:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6149:     chomp($questions);		# Get rid of any trailing \n.
 6150:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6151:     while (length($questions)) {
 6152:         my $answers_needed;
 6153:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6154:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6155:         } else {
 6156:             $answers_needed = $bubble_lines_per_response{$questnum};
 6157:         }
 6158:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6159:                              || 1;
 6160:         $questnum++;
 6161:         my $quest_id = $questnum;
 6162:         my $currentquest = substr($questions,0,$answer_length);
 6163:         $questions       = substr($questions,$answer_length);
 6164:         if (length($currentquest) < $answer_length) { next; }
 6165: 
 6166:         my $subdivided;
 6167:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6168:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6169:         } else {
 6170:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6171:         }
 6172:         if ($subdivided =~ /,/) {
 6173:             my $subquestnum = 1;
 6174:             my $subquestions = $currentquest;
 6175:             my @subanswers_needed = split(/,/,$subdivided);
 6176:             foreach my $subans (@subanswers_needed) {
 6177:                 my $subans_length =
 6178:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6179:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6180:                 $subquestions   = substr($subquestions,$subans_length);
 6181:                 $quest_id = "$questnum.$subquestnum";
 6182:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6183:                     ($$scantron_config{'Qon'} eq 'number')) {
 6184:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6185:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6186:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6187:                         $randomorder,$randompick,$respnumlookup);
 6188:                 } else {
 6189:                     $ansnum = &scantron_validator_positional($ansnum,
 6190:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6191:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6192:                         $randomorder,$randompick,$respnumlookup);
 6193:                 }
 6194:                 $subquestnum ++;
 6195:             }
 6196:         } else {
 6197:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6198:                 ($$scantron_config{'Qon'} eq 'number')) {
 6199:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6200:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6201:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6202:                     $randomorder,$randompick,$respnumlookup);
 6203:             } else {
 6204:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6205:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6206:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6207:                     $randomorder,$randompick,$respnumlookup);
 6208:             }
 6209:         }
 6210:     }
 6211:     $record{'scantron.maxquest'}=$questnum;
 6212:     return \%record;
 6213: }
 6214: 
 6215: sub get_master_seq {
 6216:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6217:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6218:                    (ref($symb_to_resource) eq 'HASH'));
 6219:     my $resource_error;
 6220:     foreach my $resource (@{$resources}) {
 6221:         my $ressymb;
 6222:         if (ref($resource)) {
 6223:             $ressymb = $resource->symb();
 6224:             push(@{$master_seq},$ressymb);
 6225:             $symb_to_resource->{$ressymb} = $resource;
 6226:         } else {
 6227:             $resource_error = 1;
 6228:             last;
 6229:         }
 6230:     }
 6231:     return $resource_error;
 6232: }
 6233: 
 6234: sub get_respnum_lookups {
 6235:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6236:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6237:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6238:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6239:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6240:                    (ref($startline) eq 'HASH'));
 6241:     my ($user,$scancode);
 6242:     if ((exists($record->{'scantron.CODE'})) &&
 6243:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6244:         $scancode = $record->{'scantron.CODE'};
 6245:     } else {
 6246:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6247:     }
 6248:     my @mapresources =
 6249:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6250:                      $orderedforcode);
 6251:     my $total = 0;
 6252:     my $count = 0;
 6253:     foreach my $resource (@mapresources) {
 6254:         my $id = $resource->id();
 6255:         my $symb = $resource->symb();
 6256:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6257:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6258:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6259:                 if ($respnum ne '') {
 6260:                     $respnumlookup->{$count} = $respnum;
 6261:                     $startline->{$count} = $total;
 6262:                     $total += $bubble_lines_per_response{$respnum};
 6263:                     $count ++;
 6264:                 }
 6265:             }
 6266:         }
 6267:     }
 6268:     return $total;
 6269: }
 6270: 
 6271: sub scantron_validator_lettnum {
 6272:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6273:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6274:         $randompick,$respnumlookup) = @_;
 6275: 
 6276:     # Qon 'letter' implies for each slot in currquest we have:
 6277:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6278:     #    about anything else (esp. a value of Qoff) for missing
 6279:     #    bubbles.
 6280:     #
 6281:     # Qon 'number' implies each slot gives a digit that indexes the
 6282:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6283:     #    and * or ? for double bubbles on a single line.
 6284:     #
 6285: 
 6286:     my $matchon;
 6287:     if ($$scantron_config{'Qon'} eq 'letter') {
 6288:         $matchon = '[A-Z]';
 6289:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6290:         $matchon = '\d';
 6291:     }
 6292:     my $occurrences = 0;
 6293:     my $responsenum = $questnum-1;
 6294:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6295:        $responsenum = $respnumlookup->{$questnum-1}
 6296:     }
 6297:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6298:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6299:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6300:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6301:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6302:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6303:         my @singlelines = split('',$currquest);
 6304:         foreach my $entry (@singlelines) {
 6305:             $occurrences = &occurence_count($entry,$matchon);
 6306:             if ($occurrences > 1) {
 6307:                 last;
 6308:             }
 6309:         }
 6310:     } else {
 6311:         $occurrences = &occurence_count($currquest,$matchon); 
 6312:     }
 6313:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6314:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6315:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6316:             my $bubble = substr($currquest,$ans,1);
 6317:             if ($bubble =~ /$matchon/ ) {
 6318:                 if ($$scantron_config{'Qon'} eq 'number') {
 6319:                     if ($bubble == 0) {
 6320:                         $bubble = 10; 
 6321:                     }
 6322:                     $record->{"scantron.$ansnum.answer"} = 
 6323:                         $alphabet->[$bubble-1];
 6324:                 } else {
 6325:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6326:                 }
 6327:             } else {
 6328:                 $record->{"scantron.$ansnum.answer"}='';
 6329:             }
 6330:             $ansnum++;
 6331:         }
 6332:     } elsif (!defined($currquest)
 6333:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6334:             || (&occurence_count($currquest,$matchon) == 0)) {
 6335:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6336:             $record->{"scantron.$ansnum.answer"}='';
 6337:             $ansnum++;
 6338:         }
 6339:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6340:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6341:         }
 6342:     } else {
 6343:         if ($$scantron_config{'Qon'} eq 'number') {
 6344:             $currquest = &digits_to_letters($currquest);            
 6345:         }
 6346:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6347:             my $bubble = substr($currquest,$ans,1);
 6348:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6349:             $ansnum++;
 6350:         }
 6351:     }
 6352:     return $ansnum;
 6353: }
 6354: 
 6355: sub scantron_validator_positional {
 6356:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6357:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6358:         $randomorder,$randompick,$respnumlookup) = @_;
 6359: 
 6360:     # Otherwise there's a positional notation;
 6361:     # each bubble line requires Qlength items, and there are filled in
 6362:     # bubbles for each case where there 'Qon' characters.
 6363:     #
 6364: 
 6365:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6366: 
 6367:     # If the split only gives us one element.. the full length of the
 6368:     # answer string, no bubbles are filled in:
 6369: 
 6370:     if ($answers_needed eq '') {
 6371:         return;
 6372:     }
 6373: 
 6374:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6375:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6376:             $record->{"scantron.$ansnum.answer"}='';
 6377:             $ansnum++;
 6378:         }
 6379:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6380:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6381:         }
 6382:     } elsif (scalar(@array) == 2) {
 6383:         my $location = length($array[0]);
 6384:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6385:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6386:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6387:             if ($ans eq $line_num) {
 6388:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6389:             } else {
 6390:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6391:             }
 6392:             $ansnum++;
 6393:          }
 6394:     } else {
 6395:         #  If there's more than one instance of a bubble character
 6396:         #  That's a double bubble; with positional notation we can
 6397:         #  record all the bubbles filled in as well as the
 6398:         #  fact this response consists of multiple bubbles.
 6399:         #
 6400:         my $responsenum = $questnum-1;
 6401:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6402:             $responsenum = $respnumlookup->{$questnum-1}
 6403:         }
 6404:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6405:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6406:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6407:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6408:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6409:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6410:             my $doubleerror = 0;
 6411:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6412:                    (!$doubleerror)) {
 6413:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6414:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6415:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6416:                if (length(@currarray) > 2) {
 6417:                    $doubleerror = 1;
 6418:                } 
 6419:             }
 6420:             if ($doubleerror) {
 6421:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6422:             }
 6423:         } else {
 6424:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6425:         }
 6426:         my $item = $ansnum;
 6427:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6428:             $record->{"scantron.$item.answer"} = '';
 6429:             $item ++;
 6430:         }
 6431: 
 6432:         my @ans=@array;
 6433:         my $i=0;
 6434:         my $increment = 0;
 6435:         while ($#ans) {
 6436:             $i+=length($ans[0]) + $increment;
 6437:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6438:             my $bubble = $i%$$scantron_config{'Qlength'};
 6439:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6440:             shift(@ans);
 6441:             $increment = 1;
 6442:         }
 6443:         $ansnum += $answers_needed;
 6444:     }
 6445:     return $ansnum;
 6446: }
 6447: 
 6448: =pod
 6449: 
 6450: =item scantron_add_delay
 6451: 
 6452:    Adds an error message that occurred during the grading phase to a
 6453:    queue of messages to be shown after grading pass is complete
 6454: 
 6455:  Arguments:
 6456:    $delayqueue  - arrary ref of hash ref of error messages
 6457:    $scanline    - the scanline that caused the error
 6458:    $errormesage - the error message
 6459:    $errorcode   - a numeric code for the error
 6460: 
 6461:  Side Effects:
 6462:    updates the $delayqueue to have a new hash ref of the error
 6463: 
 6464: =cut
 6465: 
 6466: sub scantron_add_delay {
 6467:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6468:     push(@$delayqueue,
 6469: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6470: 	  'ecode' => $errorcode }
 6471: 	 );
 6472: }
 6473: 
 6474: =pod
 6475: 
 6476: =item scantron_find_student
 6477: 
 6478:    Finds the username for the current scanline
 6479: 
 6480:   Arguments:
 6481:    $scantron_record - hash result from scantron_parse_scanline
 6482:    $scan_data       - hash of correction information 
 6483:                       (see &scantron_getfile() form more information)
 6484:    $idmap           - hash from &username_to_idmap()
 6485:    $line            - number of current scanline
 6486:  
 6487:   Returns:
 6488:    Either 'username:domain' or undef if unknown
 6489: 
 6490: =cut
 6491: 
 6492: sub scantron_find_student {
 6493:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6494:     my $scanID=$$scantron_record{'scantron.ID'};
 6495:     if ($scanID =~ /^\s*$/) {
 6496:  	return &scan_data($scan_data,"$line.user");
 6497:     }
 6498:     foreach my $id (keys(%$idmap)) {
 6499:  	if (lc($id) eq lc($scanID)) {
 6500:  	    return $$idmap{$id};
 6501:  	}
 6502:     }
 6503:     return undef;
 6504: }
 6505: 
 6506: =pod
 6507: 
 6508: =item scantron_filter
 6509: 
 6510:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6511:    hidden resources was selected
 6512: 
 6513: =cut
 6514: 
 6515: sub scantron_filter {
 6516:     my ($curres)=@_;
 6517: 
 6518:     if (ref($curres) && $curres->is_problem()) {
 6519: 	# if the user has asked to not have either hidden
 6520: 	# or 'randomout' controlled resources to be graded
 6521: 	# don't include them
 6522: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6523: 	    && $curres->randomout) {
 6524: 	    return 0;
 6525: 	}
 6526: 	return 1;
 6527:     }
 6528:     return 0;
 6529: }
 6530: 
 6531: =pod
 6532: 
 6533: =item scantron_process_corrections
 6534: 
 6535:    Gets correction information out of submitted form data and corrects
 6536:    the scanline
 6537: 
 6538: =cut
 6539: 
 6540: sub scantron_process_corrections {
 6541:     my ($r) = @_;
 6542:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6543:     my ($scanlines,$scan_data)=&scantron_getfile();
 6544:     my $classlist=&Apache::loncoursedata::get_classlist();
 6545:     my $which=$env{'form.scantron_line'};
 6546:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6547:     my ($skip,$err,$errmsg);
 6548:     if ($env{'form.scantron_skip_record'}) {
 6549: 	$skip=1;
 6550:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6551: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6552: 	    $env{'form.scantron_domain'};
 6553: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6554: 	($line,$err,$errmsg)=
 6555: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6556: 				     'ID',{'newid'=>$newid,
 6557: 				    'username'=>$env{'form.scantron_username'},
 6558: 				    'domain'=>$env{'form.scantron_domain'}});
 6559:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6560: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6561: 	my $newCODE;
 6562: 	my %args;
 6563: 	if      ($resolution eq 'use_unfound') {
 6564: 	    $newCODE='use_unfound';
 6565: 	} elsif ($resolution eq 'use_found') {
 6566: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6567: 	} elsif ($resolution eq 'use_typed') {
 6568: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6569: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6570: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6571: 	}
 6572: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6573: 	    $args{'CODE_ignore_dup'}=1;
 6574: 	}
 6575: 	$args{'CODE'}=$newCODE;
 6576: 	($line,$err,$errmsg)=
 6577: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6578: 				     'CODE',\%args);
 6579:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6580: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6581: 	    ($line,$err,$errmsg)=
 6582: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6583: 					 $which,'answer',
 6584: 					 { 'question'=>$question,
 6585: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6586:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6587: 	    if ($err) { last; }
 6588: 	}
 6589:     }
 6590:     if ($err) {
 6591: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6592:     } else {
 6593: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6594: 	&scantron_putfile($scanlines,$scan_data);
 6595:     }
 6596: }
 6597: 
 6598: =pod
 6599: 
 6600: =item reset_skipping_status
 6601: 
 6602:    Forgets the current set of remember skipped scanlines (and thus
 6603:    reverts back to considering all lines in the
 6604:    scantron_skipped_<filename> file)
 6605: 
 6606: =cut
 6607: 
 6608: sub reset_skipping_status {
 6609:     my ($scanlines,$scan_data)=&scantron_getfile();
 6610:     &scan_data($scan_data,'remember_skipping',undef,1);
 6611:     &scantron_putfile(undef,$scan_data);
 6612: }
 6613: 
 6614: =pod
 6615: 
 6616: =item start_skipping
 6617: 
 6618:    Marks a scanline to be skipped. 
 6619: 
 6620: =cut
 6621: 
 6622: sub start_skipping {
 6623:     my ($scan_data,$i)=@_;
 6624:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6625:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6626: 	$remembered{$i}=2;
 6627:     } else {
 6628: 	$remembered{$i}=1;
 6629:     }
 6630:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6631: }
 6632: 
 6633: =pod
 6634: 
 6635: =item should_be_skipped
 6636: 
 6637:    Checks whether a scanline should be skipped.
 6638: 
 6639: =cut
 6640: 
 6641: sub should_be_skipped {
 6642:     my ($scanlines,$scan_data,$i)=@_;
 6643:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6644: 	# not redoing old skips
 6645: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6646: 	return 0;
 6647:     }
 6648:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6649: 
 6650:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6651: 	return 0;
 6652:     }
 6653:     return 1;
 6654: }
 6655: 
 6656: =pod
 6657: 
 6658: =item remember_current_skipped
 6659: 
 6660:    Discovers what scanlines are in the scantron_skipped_<filename>
 6661:    file and remembers them into scan_data for later use.
 6662: 
 6663: =cut
 6664: 
 6665: sub remember_current_skipped {
 6666:     my ($scanlines,$scan_data)=&scantron_getfile();
 6667:     my %to_remember;
 6668:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6669: 	if ($scanlines->{'skipped'}[$i]) {
 6670: 	    $to_remember{$i}=1;
 6671: 	}
 6672:     }
 6673: 
 6674:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6675:     &scantron_putfile(undef,$scan_data);
 6676: }
 6677: 
 6678: =pod
 6679: 
 6680: =item check_for_error
 6681: 
 6682:     Checks if there was an error when attempting to remove a specific
 6683:     scantron_.. bubblesheet data file. Prints out an error if
 6684:     something went wrong.
 6685: 
 6686: =cut
 6687: 
 6688: sub check_for_error {
 6689:     my ($r,$result)=@_;
 6690:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6691: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6692:     }
 6693: }
 6694: 
 6695: =pod
 6696: 
 6697: =item scantron_warning_screen
 6698: 
 6699:    Interstitial screen to make sure the operator has selected the
 6700:    correct options before we start the validation phase.
 6701: 
 6702: =cut
 6703: 
 6704: sub scantron_warning_screen {
 6705:     my ($button_text)=@_;
 6706:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6707:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6708:     my $CODElist;
 6709:     if ($scantron_config{'CODElocation'} &&
 6710: 	$scantron_config{'CODEstart'} &&
 6711: 	$scantron_config{'CODElength'}) {
 6712: 	$CODElist=$env{'form.scantron_CODElist'};
 6713: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6714: 	$CODElist=
 6715: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6716: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6717:     }
 6718:     my $lastbubblepoints;
 6719:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6720:         $lastbubblepoints =
 6721:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6722:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6723:     }
 6724:     return ('
 6725: <p>
 6726: <span class="LC_warning">
 6727: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6728: </p>
 6729: <table>
 6730: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6731: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6732: '.$CODElist.$lastbubblepoints.'
 6733: </table>
 6734: <br />
 6735: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 6736: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 6737: 
 6738: <br />
 6739: ');
 6740: }
 6741: 
 6742: =pod
 6743: 
 6744: =item scantron_do_warning
 6745: 
 6746:    Check if the operator has picked something for all required
 6747:    fields. Error out if something is missing.
 6748: 
 6749: =cut
 6750: 
 6751: sub scantron_do_warning {
 6752:     my ($r)=@_;
 6753:     my ($symb)=&get_symb($r);
 6754:     if (!$symb) {return '';}
 6755:     my $default_form_data=&defaultFormData($symb);
 6756:     $r->print(&scantron_form_start().$default_form_data);
 6757:     if ( $env{'form.selectpage'} eq '' ||
 6758: 	 $env{'form.scantron_selectfile'} eq '' ||
 6759: 	 $env{'form.scantron_format'} eq '' ) {
 6760: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6761: 	if ( $env{'form.selectpage'} eq '') {
 6762: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6763: 	} 
 6764: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6765: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6766: 	} 
 6767: 	if ( $env{'form.scantron_format'} eq '') {
 6768: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6769: 	} 
 6770:     } else {
 6771: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6772:         my $bubbledbyhand=&hand_bubble_option();
 6773: 	$r->print('
 6774: '.$warning.$bubbledbyhand.'
 6775: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6776: <input type="hidden" name="command" value="scantron_validate" />
 6777: ');
 6778:     }
 6779:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6780:     return '';
 6781: }
 6782: 
 6783: =pod
 6784: 
 6785: =item scantron_form_start
 6786: 
 6787:     html hidden input for remembering all selected grading options
 6788: 
 6789: =cut
 6790: 
 6791: sub scantron_form_start {
 6792:     my ($max_bubble)=@_;
 6793:     my $result= <<SCANTRONFORM;
 6794: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6795:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6796:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6797:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6798:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6799:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6800:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6801:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6802:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6803:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6804: SCANTRONFORM
 6805: 
 6806:   my $line = 0;
 6807:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6808:        my $chunk =
 6809: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6810:        $chunk .=
 6811: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6812:        $chunk .= 
 6813:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6814:        $chunk .=
 6815:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6816:        $chunk .=
 6817:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6818:        $result .= $chunk;
 6819:        $line++;
 6820:     }
 6821:     return $result;
 6822: }
 6823: 
 6824: =pod
 6825: 
 6826: =item scantron_validate_file
 6827: 
 6828:     Dispatch routine for doing validation of a bubblesheet data file.
 6829: 
 6830:     Also processes any necessary information resets that need to
 6831:     occur before validation begins (ignore previous corrections,
 6832:     restarting the skipped records processing)
 6833: 
 6834: =cut
 6835: 
 6836: sub scantron_validate_file {
 6837:     my ($r) = @_;
 6838:     my ($symb)=&get_symb($r);
 6839:     if (!$symb) {return '';}
 6840:     my $default_form_data=&defaultFormData($symb);
 6841:     
 6842:     # do the detection of only doing skipped records first befroe we delete
 6843:     # them when doing the corrections reset
 6844:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6845: 	&reset_skipping_status();
 6846:     }
 6847:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6848: 	&remember_current_skipped();
 6849: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6850:     }
 6851: 
 6852:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6853: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6854: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6855: 	&check_for_error($r,&scantron_remove_scan_data());
 6856: 	$env{'form.scantron_options_ignore'}='done';
 6857:     }
 6858: 
 6859:     if ($env{'form.scantron_corrections'}) {
 6860: 	&scantron_process_corrections($r);
 6861:     }
 6862:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6863:     #get the student pick code ready
 6864:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6865:     my $nav_error;
 6866:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6867:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6868:     if ($nav_error) {
 6869:         $r->print(&navmap_errormsg());
 6870:         return '';
 6871:     }
 6872:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6873:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6874:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6875:     }
 6876:     $r->print($result);
 6877:     
 6878:     my @validate_phases=( 'sequence',
 6879: 			  'ID',
 6880: 			  'CODE',
 6881: 			  'doublebubble',
 6882: 			  'missingbubbles');
 6883:     if (!$env{'form.validatepass'}) {
 6884: 	$env{'form.validatepass'} = 0;
 6885:     }
 6886:     my $currentphase=$env{'form.validatepass'};
 6887: 
 6888: 
 6889:     my $stop=0;
 6890:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6891: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6892: 	$r->rflush();
 6893: 
 6894: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6895: 	{
 6896: 	    no strict 'refs';
 6897: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6898: 	}
 6899:     }
 6900:     if (!$stop) {
 6901: 	my $warning=&scantron_warning_screen('Start Grading');
 6902: 	$r->print(&mt('Validation process complete.').'<br />'.
 6903:                   $warning.
 6904:                   &mt('Perform verification for each student after storage of submissions?').
 6905:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6906:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6907:                   ('&nbsp;'x3).'<label>'.
 6908:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6909:                   '</label></span><br />'.
 6910:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6911:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6912:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6913:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6914:     } else {
 6915: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6916: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6917:     }
 6918:     if ($stop) {
 6919: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6920: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6921: 	    $r->print(' '.&mt('this error').' <br />');
 6922: 
 6923: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6924: 	} else {
 6925:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6926: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6927:             } else {
 6928:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6929:             }
 6930: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6931: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6932: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6933: 	}
 6934:     }
 6935:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6936:     return '';
 6937: }
 6938: 
 6939: 
 6940: =pod
 6941: 
 6942: =item scantron_remove_file
 6943: 
 6944:    Removes the requested bubblesheet data file, makes sure that
 6945:    scantron_original_<filename> is never removed
 6946: 
 6947: 
 6948: =cut
 6949: 
 6950: sub scantron_remove_file {
 6951:     my ($which)=@_;
 6952:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6953:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6954:     my $file='scantron_';
 6955:     if ($which eq 'corrected' || $which eq 'skipped') {
 6956: 	$file.=$which.'_';
 6957:     } else {
 6958: 	return 'refused';
 6959:     }
 6960:     $file.=$env{'form.scantron_selectfile'};
 6961:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6962: }
 6963: 
 6964: 
 6965: =pod
 6966: 
 6967: =item scantron_remove_scan_data
 6968: 
 6969:    Removes all scan_data correction for the requested bubblesheet
 6970:    data file.  (In the case that both the are doing skipped records we need
 6971:    to remember the old skipped lines for the time being so that element
 6972:    persists for a while.)
 6973: 
 6974: =cut
 6975: 
 6976: sub scantron_remove_scan_data {
 6977:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6978:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6979:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6980:     my @todelete;
 6981:     my $filename=$env{'form.scantron_selectfile'};
 6982:     foreach my $key (@keys) {
 6983: 	if ($key=~/^\Q$filename\E_/) {
 6984: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6985: 		$key=~/remember_skipping/) {
 6986: 		next;
 6987: 	    }
 6988: 	    push(@todelete,$key);
 6989: 	}
 6990:     }
 6991:     my $result;
 6992:     if (@todelete) {
 6993: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6994: 				       \@todelete,$cdom,$cname);
 6995:     } else {
 6996: 	$result = 'ok';
 6997:     }
 6998:     return $result;
 6999: }
 7000: 
 7001: 
 7002: =pod
 7003: 
 7004: =item scantron_getfile
 7005: 
 7006:     Fetches the requested bubblesheet data file (all 3 versions), and
 7007:     the scan_data hash
 7008:   
 7009:   Arguments:
 7010:     None
 7011: 
 7012:   Returns:
 7013:     2 hash references
 7014: 
 7015:      - first one has 
 7016:          orig      -
 7017:          corrected -
 7018:          skipped   -  each of which points to an array ref of the specified
 7019:                       file broken up into individual lines
 7020:          count     - number of scanlines
 7021:  
 7022:      - second is the scan_data hash possible keys are
 7023:        ($number refers to scanline numbered $number and thus the key affects
 7024:         only that scanline
 7025:         $bubline refers to the specific bubble line element and the aspects
 7026:         refers to that specific bubble line element)
 7027: 
 7028:        $number.user - username:domain to use
 7029:        $number.CODE_ignore_dup 
 7030:                     - ignore the duplicate CODE error 
 7031:        $number.useCODE
 7032:                     - use the CODE in the scanline as is
 7033:        $number.no_bubble.$bubline
 7034:                     - it is valid that there is no bubbled in bubble
 7035:                       at $number $bubline
 7036:        remember_skipping
 7037:                     - a frozen hash containing keys of $number and values
 7038:                       of either 
 7039:                         1 - we are on a 'do skipped records pass' and plan
 7040:                             on processing this line
 7041:                         2 - we are on a 'do skipped records pass' and this
 7042:                             scanline has been marked to skip yet again
 7043: 
 7044: =cut
 7045: 
 7046: sub scantron_getfile {
 7047:     #FIXME really would prefer a scantron directory
 7048:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7049:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7050:     my $lines;
 7051:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7052: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7053:     my %scanlines;
 7054:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7055:     my $temp=$scanlines{'orig'};
 7056:     $scanlines{'count'}=$#$temp;
 7057: 
 7058:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7059: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7060:     if ($lines eq '-1') {
 7061: 	$scanlines{'corrected'}=[];
 7062:     } else {
 7063: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7064:     }
 7065:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7066: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7067:     if ($lines eq '-1') {
 7068: 	$scanlines{'skipped'}=[];
 7069:     } else {
 7070: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7071:     }
 7072:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7073:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7074:     my %scan_data = @tmp;
 7075:     return (\%scanlines,\%scan_data);
 7076: }
 7077: 
 7078: =pod
 7079: 
 7080: =item lonnet_putfile
 7081: 
 7082:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7083: 
 7084:  Arguments:
 7085:    $contents - data to store
 7086:    $filename - filename to store $contents into
 7087: 
 7088:  Returns:
 7089:    result value from &Apache::lonnet::finishuserfileupload
 7090: 
 7091: =cut
 7092: 
 7093: sub lonnet_putfile {
 7094:     my ($contents,$filename)=@_;
 7095:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7096:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7097:     $env{'form.sillywaytopassafilearound'}=$contents;
 7098:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7099: 
 7100: }
 7101: 
 7102: =pod
 7103: 
 7104: =item scantron_putfile
 7105: 
 7106:     Stores the current version of the bubblesheet data files, and the
 7107:     scan_data hash. (Does not modify the original version only the
 7108:     corrected and skipped versions.
 7109: 
 7110:  Arguments:
 7111:     $scanlines - hash ref that looks like the first return value from
 7112:                  &scantron_getfile()
 7113:     $scan_data - hash ref that looks like the second return value from
 7114:                  &scantron_getfile()
 7115: 
 7116: =cut
 7117: 
 7118: sub scantron_putfile {
 7119:     my ($scanlines,$scan_data) = @_;
 7120:     #FIXME really would prefer a scantron directory
 7121:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7122:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7123:     if ($scanlines) {
 7124: 	my $prefix='scantron_';
 7125: # no need to update orig, shouldn't change
 7126: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7127: #		    $env{'form.scantron_selectfile'});
 7128: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7129: 			$prefix.'corrected_'.
 7130: 			$env{'form.scantron_selectfile'});
 7131: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7132: 			$prefix.'skipped_'.
 7133: 			$env{'form.scantron_selectfile'});
 7134:     }
 7135:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7136: }
 7137: 
 7138: =pod
 7139: 
 7140: =item scantron_get_line
 7141: 
 7142:    Returns the correct version of the scanline
 7143: 
 7144:  Arguments:
 7145:     $scanlines - hash ref that looks like the first return value from
 7146:                  &scantron_getfile()
 7147:     $scan_data - hash ref that looks like the second return value from
 7148:                  &scantron_getfile()
 7149:     $i         - number of the requested line (starts at 0)
 7150: 
 7151:  Returns:
 7152:    A scanline, (either the original or the corrected one if it
 7153:    exists), or undef if the requested scanline should be
 7154:    skipped. (Either because it's an skipped scanline, or it's an
 7155:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7156:    pass.
 7157: 
 7158: =cut
 7159: 
 7160: sub scantron_get_line {
 7161:     my ($scanlines,$scan_data,$i)=@_;
 7162:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7163:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7164:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7165:     return $scanlines->{'orig'}[$i]; 
 7166: }
 7167: 
 7168: =pod
 7169: 
 7170: =item scantron_todo_count
 7171: 
 7172:     Counts the number of scanlines that need processing.
 7173: 
 7174:  Arguments:
 7175:     $scanlines - hash ref that looks like the first return value from
 7176:                  &scantron_getfile()
 7177:     $scan_data - hash ref that looks like the second return value from
 7178:                  &scantron_getfile()
 7179: 
 7180:  Returns:
 7181:     $count - number of scanlines to process
 7182: 
 7183: =cut
 7184: 
 7185: sub get_todo_count {
 7186:     my ($scanlines,$scan_data)=@_;
 7187:     my $count=0;
 7188:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7189: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7190: 	if ($line=~/^[\s\cz]*$/) { next; }
 7191: 	$count++;
 7192:     }
 7193:     return $count;
 7194: }
 7195: 
 7196: =pod
 7197: 
 7198: =item scantron_put_line
 7199: 
 7200:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7201:     data file.
 7202: 
 7203:  Arguments:
 7204:     $scanlines - hash ref that looks like the first return value from
 7205:                  &scantron_getfile()
 7206:     $scan_data - hash ref that looks like the second return value from
 7207:                  &scantron_getfile()
 7208:     $i         - line number to update
 7209:     $newline   - contents of the updated scanline
 7210:     $skip      - if true make the line for skipping and update the
 7211:                  'skipped' file
 7212: 
 7213: =cut
 7214: 
 7215: sub scantron_put_line {
 7216:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7217:     if ($skip) {
 7218: 	$scanlines->{'skipped'}[$i]=$newline;
 7219: 	&start_skipping($scan_data,$i);
 7220: 	return;
 7221:     }
 7222:     $scanlines->{'corrected'}[$i]=$newline;
 7223: }
 7224: 
 7225: =pod
 7226: 
 7227: =item scantron_clear_skip
 7228: 
 7229:    Remove a line from the 'skipped' file
 7230: 
 7231:  Arguments:
 7232:     $scanlines - hash ref that looks like the first return value from
 7233:                  &scantron_getfile()
 7234:     $scan_data - hash ref that looks like the second return value from
 7235:                  &scantron_getfile()
 7236:     $i         - line number to update
 7237: 
 7238: =cut
 7239: 
 7240: sub scantron_clear_skip {
 7241:     my ($scanlines,$scan_data,$i)=@_;
 7242:     if (exists($scanlines->{'skipped'}[$i])) {
 7243: 	undef($scanlines->{'skipped'}[$i]);
 7244: 	return 1;
 7245:     }
 7246:     return 0;
 7247: }
 7248: 
 7249: =pod
 7250: 
 7251: =item scantron_filter_not_exam
 7252: 
 7253:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7254:    filter out resources that are not marked as 'exam' mode
 7255: 
 7256: =cut
 7257: 
 7258: sub scantron_filter_not_exam {
 7259:     my ($curres)=@_;
 7260:     
 7261:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7262: 	# if the user has asked to not have either hidden
 7263: 	# or 'randomout' controlled resources to be graded
 7264: 	# don't include them
 7265: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7266: 	    && $curres->randomout) {
 7267: 	    return 0;
 7268: 	}
 7269: 	return 1;
 7270:     }
 7271:     return 0;
 7272: }
 7273: 
 7274: =pod
 7275: 
 7276: =item scantron_validate_sequence
 7277: 
 7278:     Validates the selected sequence, checking for resource that are
 7279:     not set to exam mode.
 7280: 
 7281: =cut
 7282: 
 7283: sub scantron_validate_sequence {
 7284:     my ($r,$currentphase) = @_;
 7285: 
 7286:     my $navmap=Apache::lonnavmaps::navmap->new();
 7287:     unless (ref($navmap)) {
 7288:         $r->print(&navmap_errormsg());
 7289:         return (1,$currentphase);
 7290:     }
 7291:     my (undef,undef,$sequence)=
 7292: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7293: 
 7294:     my $map=$navmap->getResourceByUrl($sequence);
 7295: 
 7296:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7297:                                     value="ignore" />');
 7298:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7299: 	my @resources=
 7300: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7301: 	if (@resources) {
 7302: 	    $r->print('<p class="LC_warning">'
 7303:                .&mt('Some resources in the sequence currently are not set to'
 7304:                    .' exam mode. Grading these resources currently may not'
 7305:                    .' work correctly.')
 7306:                .'</p>'
 7307:             );
 7308: 	    return (1,$currentphase);
 7309: 	}
 7310:     }
 7311: 
 7312:     return (0,$currentphase+1);
 7313: }
 7314: 
 7315: 
 7316: 
 7317: sub scantron_validate_ID {
 7318:     my ($r,$currentphase) = @_;
 7319:     
 7320:     #get student info
 7321:     my $classlist=&Apache::loncoursedata::get_classlist();
 7322:     my %idmap=&username_to_idmap($classlist);
 7323: 
 7324:     #get scantron line setup
 7325:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7326:     my ($scanlines,$scan_data)=&scantron_getfile();
 7327: 
 7328:     my $nav_error;
 7329:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7330:     if ($nav_error) {
 7331:         $r->print(&navmap_errormsg());
 7332:         return(1,$currentphase);
 7333:     }
 7334: 
 7335:     my %found=('ids'=>{},'usernames'=>{});
 7336:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7337: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7338: 	if ($line=~/^[\s\cz]*$/) { next; }
 7339: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7340: 						 $scan_data);
 7341: 	my $id=$$scan_record{'scantron.ID'};
 7342: 	my $found;
 7343: 	foreach my $checkid (keys(%idmap)) {
 7344: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7345: 	}
 7346: 	if ($found) {
 7347: 	    my $username=$idmap{$found};
 7348: 	    if ($found{'ids'}{$found}) {
 7349: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7350: 					 $line,'duplicateID',$found);
 7351: 		return(1,$currentphase);
 7352: 	    } elsif ($found{'usernames'}{$username}) {
 7353: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7354: 					 $line,'duplicateID',$username);
 7355: 		return(1,$currentphase);
 7356: 	    }
 7357: 	    #FIXME store away line we previously saw the ID on to use above
 7358: 	    $found{'ids'}{$found}++;
 7359: 	    $found{'usernames'}{$username}++;
 7360: 	} else {
 7361: 	    if ($id =~ /^\s*$/) {
 7362: 		my $username=&scan_data($scan_data,"$i.user");
 7363: 		if (defined($username) && $found{'usernames'}{$username}) {
 7364: 		    &scantron_get_correction($r,$i,$scan_record,
 7365: 					     \%scantron_config,
 7366: 					     $line,'duplicateID',$username);
 7367: 		    return(1,$currentphase);
 7368: 		} elsif (!defined($username)) {
 7369: 		    &scantron_get_correction($r,$i,$scan_record,
 7370: 					     \%scantron_config,
 7371: 					     $line,'incorrectID');
 7372: 		    return(1,$currentphase);
 7373: 		}
 7374: 		$found{'usernames'}{$username}++;
 7375: 	    } else {
 7376: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7377: 					 $line,'incorrectID');
 7378: 		return(1,$currentphase);
 7379: 	    }
 7380: 	}
 7381:     }
 7382: 
 7383:     return (0,$currentphase+1);
 7384: }
 7385: 
 7386: 
 7387: sub scantron_get_correction {
 7388:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7389:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7390: #FIXME in the case of a duplicated ID the previous line, probably need
 7391: #to show both the current line and the previous one and allow skipping
 7392: #the previous one or the current one
 7393: 
 7394:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7395:         $r->print(
 7396:             '<p class="LC_warning">'
 7397:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7398:                 "<b>$error</b>",
 7399:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7400:            ."</p> \n");
 7401:     } else {
 7402:         $r->print(
 7403:             '<p class="LC_warning">'
 7404:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7405:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7406:            ."</p> \n");
 7407:     }
 7408:     my $message =
 7409:         '<p>'
 7410:        .&mt('The ID on the form is [_1]',
 7411:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7412:        .'<br />'
 7413:        .&mt('The name on the paper is [_1], [_2]',
 7414:             $$scan_record{'scantron.LastName'},
 7415:             $$scan_record{'scantron.FirstName'})
 7416:        .'</p>';
 7417: 
 7418:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7419:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7420:                            # Array populated for doublebubble or
 7421:     my @lines_to_correct;  # missingbubble errors to build javascript
 7422:                            # to validate radio button checking   
 7423: 
 7424:     if ($error =~ /ID$/) {
 7425: 	if ($error eq 'incorrectID') {
 7426: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7427: 		      "</p>\n");
 7428: 	} elsif ($error eq 'duplicateID') {
 7429: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7430: 	}
 7431: 	$r->print($message);
 7432: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7433: 	$r->print("\n<ul><li> ");
 7434: 	#FIXME it would be nice if this sent back the user ID and
 7435: 	#could do partial userID matches
 7436: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7437: 				       'scantron_username','scantron_domain'));
 7438: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7439: 	$r->print("\n:\n".
 7440: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7441: 
 7442: 	$r->print('</li>');
 7443:     } elsif ($error =~ /CODE$/) {
 7444: 	if ($error eq 'incorrectCODE') {
 7445: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7446: 	} elsif ($error eq 'duplicateCODE') {
 7447: 	    $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");
 7448: 	}
 7449:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7450:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7451:                  ."</p>\n");
 7452: 	$r->print($message);
 7453: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7454: 	$r->print("\n<br /> ");
 7455: 	my $i=0;
 7456: 	if ($error eq 'incorrectCODE' 
 7457: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7458: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7459: 	    if ($closest > 0) {
 7460: 		foreach my $testcode (@{$closest}) {
 7461: 		    my $checked='';
 7462: 		    if (!$i) { $checked=' checked="checked"'; }
 7463: 		    $r->print("
 7464:    <label>
 7465:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7466:        ".&mt("Use the similar CODE [_1] instead.",
 7467: 	    "<b><tt>".$testcode."</tt></b>")."
 7468:     </label>
 7469:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7470: 		    $r->print("\n<br />");
 7471: 		    $i++;
 7472: 		}
 7473: 	    }
 7474: 	}
 7475: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7476: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7477: 	    $r->print("
 7478:     <label>
 7479:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7480:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7481: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7482:     </label>");
 7483: 	    $r->print("\n<br />");
 7484: 	}
 7485: 
 7486: 	$r->print(<<ENDSCRIPT);
 7487: <script type="text/javascript">
 7488: function change_radio(field) {
 7489:     var slct=document.scantronupload.scantron_CODE_resolution;
 7490:     var i;
 7491:     for (i=0;i<slct.length;i++) {
 7492:         if (slct[i].value==field) { slct[i].checked=true; }
 7493:     }
 7494: }
 7495: </script>
 7496: ENDSCRIPT
 7497: 	my $href="/adm/pickcode?".
 7498: 	   "form=".&escape("scantronupload").
 7499: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7500: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7501: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7502: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7503: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7504: 	    $r->print("
 7505:     <label>
 7506:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7507:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7508: 	     "<a target='_blank' href='$href'>","</a>")."
 7509:     </label> 
 7510:     ".&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\')" />'));
 7511: 	    $r->print("\n<br />");
 7512: 	}
 7513: 	$r->print("
 7514:     <label>
 7515:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7516:        ".&mt("Use [_1] as the CODE.",
 7517: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7518: 	$r->print("\n<br /><br />");
 7519:     } elsif ($error eq 'doublebubble') {
 7520: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7521: 
 7522: 	# The form field scantron_questions is acutally a list of line numbers.
 7523: 	# represented by this form so:
 7524: 
 7525: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7526:                                                 $respnumlookup,$startline);
 7527: 
 7528: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7529: 		  $line_list.'" />');
 7530: 	$r->print($message);
 7531: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7532: 	foreach my $question (@{$arg}) {
 7533: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7534:                                                    $scan_record, $error,
 7535:                                                    $randomorder,$randompick,
 7536:                                                    $respnumlookup,$startline);
 7537:             push(@lines_to_correct,@linenums);
 7538: 	}
 7539:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7540:     } elsif ($error eq 'missingbubble') {
 7541: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7542: 	$r->print($message);
 7543: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7544: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7545: 
 7546: 	# The form field scantron_questions is actually a list of line numbers not
 7547: 	# a list of question numbers. Therefore:
 7548: 	#
 7549: 	
 7550: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7551:                                                 $respnumlookup,$startline);
 7552: 
 7553: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7554: 		  $line_list.'" />');
 7555: 	foreach my $question (@{$arg}) {
 7556: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7557:                                                    $scan_record, $error,
 7558:                                                    $randomorder,$randompick,
 7559:                                                    $respnumlookup,$startline);
 7560:             push(@lines_to_correct,@linenums);
 7561: 	}
 7562:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7563:     } else {
 7564: 	$r->print("\n<ul>");
 7565:     }
 7566:     $r->print("\n</li></ul>");
 7567: }
 7568: 
 7569: sub verify_bubbles_checked {
 7570:     my (@ansnums) = @_;
 7571:     my $ansnumstr = join('","',@ansnums);
 7572:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7573:     my $output = (<<ENDSCRIPT);
 7574: <script type="text/javascript">
 7575: function verify_bubble_radio(form) {
 7576:     var ansnumArray = new Array ("$ansnumstr");
 7577:     var need_bubble_count = 0;
 7578:     for (var i=0; i<ansnumArray.length; i++) {
 7579:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7580:             var bubble_picked = 0; 
 7581:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7582:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7583:                     bubble_picked = 1;
 7584:                 }
 7585:             }
 7586:             if (bubble_picked == 0) {
 7587:                 need_bubble_count ++;
 7588:             }
 7589:         }
 7590:     }
 7591:     if (need_bubble_count) {
 7592:         alert("$warning");
 7593:         return;
 7594:     }
 7595:     form.submit(); 
 7596: }
 7597: </script>
 7598: ENDSCRIPT
 7599:     return $output;
 7600: }
 7601: 
 7602: =pod
 7603: 
 7604: =item  questions_to_line_list
 7605: 
 7606: Converts a list of questions into a string of comma separated
 7607: line numbers in the answer sheet used by the questions.  This is
 7608: used to fill in the scantron_questions form field.
 7609: 
 7610:   Arguments:
 7611:      questions    - Reference to an array of questions.
 7612:      randomorder  - True if randomorder in use.
 7613:      randompick   - True if randompick in use.
 7614:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7615:                      for current line to question number used for same question
 7616:                      in "Master Seqence" (as seen by Course Coordinator).
 7617:      startline    - Reference to hash where key is question number (0 is first)
 7618:                     and key is number of first bubble line for current student
 7619:                     or code-based randompick and/or randomorder.
 7620: 
 7621: =cut
 7622: 
 7623: 
 7624: sub questions_to_line_list {
 7625:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7626:     my @lines;
 7627: 
 7628:     foreach my $item (@{$questions}) {
 7629:         my $question = $item;
 7630:         my ($first,$count,$last);
 7631:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7632:             $question = $1;
 7633:             my $subquestion = $2;
 7634:             my $responsenum = $question-1;
 7635:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7636:                 $responsenum = $respnumlookup->{$question-1};
 7637:                 if (ref($startline) eq 'HASH') {
 7638:                     $first = $startline->{$question-1} + 1;
 7639:                 }
 7640:             } else {
 7641:                 $first = $first_bubble_line{$responsenum} + 1;
 7642:             }
 7643:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7644:             my $subcount = 1;
 7645:             while ($subcount<$subquestion) {
 7646:                 $first += $subans[$subcount-1];
 7647:                 $subcount ++;
 7648:             }
 7649:             $count = $subans[$subquestion-1];
 7650:         } else {
 7651:             my $responsenum = $question-1;
 7652:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7653:                 $responsenum = $respnumlookup->{$question-1};
 7654:                 if (ref($startline) eq 'HASH') {
 7655:                     $first = $startline->{$question-1} + 1;
 7656:                 }
 7657:             } else {
 7658:                 $first = $first_bubble_line{$responsenum} + 1;
 7659:             }
 7660:             $count   = $bubble_lines_per_response{$responsenum};
 7661:         }
 7662:         $last = $first+$count-1;
 7663:         push(@lines, ($first..$last));
 7664:     }
 7665:     return join(',', @lines);
 7666: }
 7667: 
 7668: =pod 
 7669: 
 7670: =item prompt_for_corrections
 7671: 
 7672: Prompts for a potentially multiline correction to the
 7673: user's bubbling (factors out common code from scantron_get_correction
 7674: for multi and missing bubble cases).
 7675: 
 7676:  Arguments:
 7677:    $r           - Apache request object.
 7678:    $question    - The question number to prompt for.
 7679:    $scan_config - The scantron file configuration hash.
 7680:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7681:    $error       - Type of error
 7682:    $randomorder - True if randomorder in use.
 7683:    $randompick  - True if randompick in use.
 7684:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7685:                     for current line to question number used for same question
 7686:                     in "Master Seqence" (as seen by Course Coordinator).
 7687:    $startline   - Reference to hash where key is question number (0 is first)
 7688:                   and value is number of first bubble line for current student
 7689:                   or code-based randompick and/or randomorder.
 7690: 
 7691:  Implicit inputs:
 7692:    %bubble_lines_per_response   - Starting line numbers for each question.
 7693:                                   Numbered from 0 (but question numbers are from
 7694:                                   1.
 7695:    %first_bubble_line           - Starting bubble line for each question.
 7696:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7697:                                   type problems render as separate sub-questions, 
 7698:                                   in exam mode. This hash contains a 
 7699:                                   comma-separated list of the lines per 
 7700:                                   sub-question.
 7701:    %responsetype_per_response   - essayresponse, formularesponse,
 7702:                                   stringresponse, imageresponse, reactionresponse,
 7703:                                   and organicresponse type problem parts can have
 7704:                                   multiple lines per response if the weight
 7705:                                   assigned exceeds 10.  In this case, only
 7706:                                   one bubble per line is permitted, but more 
 7707:                                   than one line might contain bubbles, e.g.
 7708:                                   bubbling of: line 1 - J, line 2 - J, 
 7709:                                   line 3 - B would assign 22 points.  
 7710: 
 7711: =cut
 7712: 
 7713: sub prompt_for_corrections {
 7714:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7715:         $randompick, $respnumlookup, $startline) = @_;
 7716:     my ($current_line,$lines);
 7717:     my @linenums;
 7718:     my $questionnum = $question;
 7719:     my ($first,$responsenum);
 7720:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7721:         $question = $1;
 7722:         my $subquestion = $2;
 7723:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7724:             $responsenum = $respnumlookup->{$question-1};
 7725:             if (ref($startline) eq 'HASH') {
 7726:                 $first = $startline->{$question-1};
 7727:             }
 7728:         } else {
 7729:             $responsenum = $question-1;
 7730:             $first = $first_bubble_line{$responsenum} + 1;
 7731:         }
 7732:         $current_line = $first + 1 ;
 7733:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7734:         my $subcount = 1;
 7735:         while ($subcount<$subquestion) {
 7736:             $current_line += $subans[$subcount-1];
 7737:             $subcount ++;
 7738:         }
 7739:         $lines = $subans[$subquestion-1];
 7740:     } else {
 7741:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7742:             $responsenum = $respnumlookup->{$question-1};
 7743:             if (ref($startline) eq 'HASH') {
 7744:                 $first = $startline->{$question-1};
 7745:             }
 7746:         } else {
 7747:             $responsenum = $question-1;
 7748:             $first = $first_bubble_line{$responsenum};
 7749:         }
 7750:         $current_line = $first + 1;
 7751:         $lines        = $bubble_lines_per_response{$responsenum};
 7752:     }
 7753:     if ($lines > 1) {
 7754:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7755:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7756:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7757:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7758:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7759:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7760:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7761:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 7762:         } else {
 7763:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7764:         }
 7765:     }
 7766:     for (my $i =0; $i < $lines; $i++) {
 7767:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7768: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7769: 	        		  $questionnum,$error,split('', $selected));
 7770:         push(@linenums,$current_line);
 7771: 	$current_line++;
 7772:     }
 7773:     if ($lines > 1) {
 7774: 	$r->print("<hr /><br />");
 7775:     }
 7776:     return @linenums;
 7777: }
 7778: 
 7779: =pod
 7780: 
 7781: =item scantron_bubble_selector
 7782:   
 7783:    Generates the html radiobuttons to correct a single bubble line
 7784:    possibly showing the existing the selected bubbles if known
 7785: 
 7786:  Arguments:
 7787:     $r           - Apache request object
 7788:     $scan_config - hash from &get_scantron_config()
 7789:     $line        - Number of the line being displayed.
 7790:     $questionnum - Question number (may include subquestion)
 7791:     $error       - Type of error.
 7792:     @selected    - Array of bubbles picked on this line.
 7793: 
 7794: =cut
 7795: 
 7796: sub scantron_bubble_selector {
 7797:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7798:     my $max=$$scan_config{'Qlength'};
 7799: 
 7800:     my $scmode=$$scan_config{'Qon'};
 7801:     if ($scmode eq 'number' || $scmode eq 'letter') {
 7802:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7803:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7804:             $max=$$scan_config{'BubblesPerRow'};
 7805:             if (($scmode eq 'number') && ($max > 10)) {
 7806:                 $max = 10;
 7807:             } elsif (($scmode eq 'letter') && $max > 26) {
 7808:                 $max = 26;
 7809:             }
 7810:         } else {
 7811:             $max = 10;
 7812:         }
 7813:     }
 7814: 
 7815:     my @alphabet=('A'..'Z');
 7816:     $r->print(&Apache::loncommon::start_data_table().
 7817:               &Apache::loncommon::start_data_table_row());
 7818:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7819:     for (my $i=0;$i<$max+1;$i++) {
 7820: 	$r->print("\n".'<td align="center">');
 7821: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7822: 	else { $r->print('&nbsp;'); }
 7823: 	$r->print('</td>');
 7824:     }
 7825:     $r->print(&Apache::loncommon::end_data_table_row().
 7826:               &Apache::loncommon::start_data_table_row());
 7827:     for (my $i=0;$i<$max;$i++) {
 7828: 	$r->print("\n".
 7829: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7830: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7831:     }
 7832:     my $nobub_checked = ' ';
 7833:     if ($error eq 'missingbubble') {
 7834:         $nobub_checked = ' checked = "checked" ';
 7835:     }
 7836:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7837: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7838:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7839:               $line.'" value="'.$questionnum.'" /></td>');
 7840:     $r->print(&Apache::loncommon::end_data_table_row().
 7841:               &Apache::loncommon::end_data_table());
 7842: }
 7843: 
 7844: =pod
 7845: 
 7846: =item num_matches
 7847: 
 7848:    Counts the number of characters that are the same between the two arguments.
 7849: 
 7850:  Arguments:
 7851:    $orig - CODE from the scanline
 7852:    $code - CODE to match against
 7853: 
 7854:  Returns:
 7855:    $count - integer count of the number of same characters between the
 7856:             two arguments
 7857: 
 7858: =cut
 7859: 
 7860: sub num_matches {
 7861:     my ($orig,$code) = @_;
 7862:     my @code=split(//,$code);
 7863:     my @orig=split(//,$orig);
 7864:     my $same=0;
 7865:     for (my $i=0;$i<scalar(@code);$i++) {
 7866: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7867:     }
 7868:     return $same;
 7869: }
 7870: 
 7871: =pod
 7872: 
 7873: =item scantron_get_closely_matching_CODEs
 7874: 
 7875:    Cycles through all CODEs and finds the set that has the greatest
 7876:    number of same characters as the provided CODE
 7877: 
 7878:  Arguments:
 7879:    $allcodes - hash ref returned by &get_codes()
 7880:    $CODE     - CODE from the current scanline
 7881: 
 7882:  Returns:
 7883:    2 element list
 7884:     - first elements is number of how closely matching the best fit is 
 7885:       (5 means best set has 5 matching characters)
 7886:     - second element is an arrary ref containing the set of valid CODEs
 7887:       that best fit the passed in CODE
 7888: 
 7889: =cut
 7890: 
 7891: sub scantron_get_closely_matching_CODEs {
 7892:     my ($allcodes,$CODE)=@_;
 7893:     my @CODEs;
 7894:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7895: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7896:     }
 7897: 
 7898:     return ($#CODEs,$CODEs[-1]);
 7899: }
 7900: 
 7901: =pod
 7902: 
 7903: =item get_codes
 7904: 
 7905:    Builds a hash which has keys of all of the valid CODEs from the selected
 7906:    set of remembered CODEs.
 7907: 
 7908:  Arguments:
 7909:   $old_name - name of the set of remembered CODEs
 7910:   $cdom     - domain of the course
 7911:   $cnum     - internal course name
 7912: 
 7913:  Returns:
 7914:   %allcodes - keys are the valid CODEs, values are all 1
 7915: 
 7916: =cut
 7917: 
 7918: sub get_codes {
 7919:     my ($old_name, $cdom, $cnum) = @_;
 7920:     if (!$old_name) {
 7921: 	$old_name=$env{'form.scantron_CODElist'};
 7922:     }
 7923:     if (!$cdom) {
 7924: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7925:     }
 7926:     if (!$cnum) {
 7927: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7928:     }
 7929:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7930: 				    $cdom,$cnum);
 7931:     my %allcodes;
 7932:     if ($result{"type\0$old_name"} eq 'number') {
 7933: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7934:     } else {
 7935: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7936:     }
 7937:     return %allcodes;
 7938: }
 7939: 
 7940: =pod
 7941: 
 7942: =item scantron_validate_CODE
 7943: 
 7944:    Validates all scanlines in the selected file to not have any
 7945:    invalid or underspecified CODEs and that none of the codes are
 7946:    duplicated if this was requested.
 7947: 
 7948: =cut
 7949: 
 7950: sub scantron_validate_CODE {
 7951:     my ($r,$currentphase) = @_;
 7952:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7953:     if ($scantron_config{'CODElocation'} &&
 7954: 	$scantron_config{'CODEstart'} &&
 7955: 	$scantron_config{'CODElength'}) {
 7956: 	if (!defined($env{'form.scantron_CODElist'})) {
 7957: 	    &FIXME_blow_up()
 7958: 	}
 7959:     } else {
 7960: 	return (0,$currentphase+1);
 7961:     }
 7962:     
 7963:     my %usedCODEs;
 7964: 
 7965:     my %allcodes=&get_codes();
 7966: 
 7967:     my $nav_error;
 7968:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7969:     if ($nav_error) {
 7970:         $r->print(&navmap_errormsg());
 7971:         return(1,$currentphase);
 7972:     }
 7973: 
 7974:     my ($scanlines,$scan_data)=&scantron_getfile();
 7975:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7976: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7977: 	if ($line=~/^[\s\cz]*$/) { next; }
 7978: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7979: 						 $scan_data);
 7980: 	my $CODE=$$scan_record{'scantron.CODE'};
 7981: 	my $error=0;
 7982: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7983: 	    &scantron_get_correction($r,$i,$scan_record,
 7984: 				     \%scantron_config,
 7985: 				     $line,'incorrectCODE',\%allcodes);
 7986: 	    return(1,$currentphase);
 7987: 	}
 7988: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7989: 	    && !$$scan_record{'scantron.useCODE'}) {
 7990: 	    &scantron_get_correction($r,$i,$scan_record,
 7991: 				     \%scantron_config,
 7992: 				     $line,'incorrectCODE',\%allcodes);
 7993: 	    return(1,$currentphase);
 7994: 	}
 7995: 	if (exists($usedCODEs{$CODE}) 
 7996: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7997: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7998: 	    &scantron_get_correction($r,$i,$scan_record,
 7999: 				     \%scantron_config,
 8000: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8001: 	    return(1,$currentphase);
 8002: 	}
 8003: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8004:     }
 8005:     return (0,$currentphase+1);
 8006: }
 8007: 
 8008: =pod
 8009: 
 8010: =item scantron_validate_doublebubble
 8011: 
 8012:    Validates all scanlines in the selected file to not have any
 8013:    bubble lines with multiple bubbles marked.
 8014: 
 8015: =cut
 8016: 
 8017: sub scantron_validate_doublebubble {
 8018:     my ($r,$currentphase) = @_;
 8019:     #get student info
 8020:     my $classlist=&Apache::loncoursedata::get_classlist();
 8021:     my %idmap=&username_to_idmap($classlist);
 8022:     my (undef,undef,$sequence)=
 8023:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8024: 
 8025:     #get scantron line setup
 8026:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8027:     my ($scanlines,$scan_data)=&scantron_getfile();
 8028: 
 8029:     my $navmap = Apache::lonnavmaps::navmap->new();
 8030:     unless (ref($navmap)) {
 8031:         $r->print(&navmap_errormsg());
 8032:         return(1,$currentphase);
 8033:     }
 8034:     my $map=$navmap->getResourceByUrl($sequence);
 8035:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8036:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8037:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8038:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8039: 
 8040:     my $nav_error;
 8041:     if (ref($map)) {
 8042:         $randomorder = $map->randomorder();
 8043:         $randompick = $map->randompick();
 8044:         if ($randomorder || $randompick) {
 8045:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8046:             if ($nav_error) {
 8047:                 $r->print(&navmap_errormsg());
 8048:                 return(1,$currentphase);
 8049:             }
 8050:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8051:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8052:         }
 8053:     } else {
 8054:         $r->print(&navmap_errormsg());
 8055:         return(1,$currentphase);
 8056:     }
 8057: 
 8058:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8059:     if ($nav_error) {
 8060:         $r->print(&navmap_errormsg());
 8061:         return(1,$currentphase);
 8062:     }
 8063: 
 8064:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8065: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8066: 	if ($line=~/^[\s\cz]*$/) { next; }
 8067: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8068: 						 $scan_data,undef,\%idmap,$randomorder,
 8069:                                                  $randompick,$sequence,\@master_seq,
 8070:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8071:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8072: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8073: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8074: 				 'doublebubble',
 8075: 				 $$scan_record{'scantron.doubleerror'},
 8076:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8077:     	return (1,$currentphase);
 8078:     }
 8079:     return (0,$currentphase+1);
 8080: }
 8081: 
 8082: 
 8083: sub scantron_get_maxbubble {
 8084:     my ($nav_error,$scantron_config) = @_;
 8085:     if (defined($env{'form.scantron_maxbubble'}) &&
 8086: 	$env{'form.scantron_maxbubble'}) {
 8087: 	&restore_bubble_lines();
 8088: 	return $env{'form.scantron_maxbubble'};
 8089:     }
 8090: 
 8091:     my (undef, undef, $sequence) =
 8092: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8093: 
 8094:     my $navmap=Apache::lonnavmaps::navmap->new();
 8095:     unless (ref($navmap)) {
 8096:         if (ref($nav_error)) {
 8097:             $$nav_error = 1;
 8098:         }
 8099:         return;
 8100:     }
 8101:     my $map=$navmap->getResourceByUrl($sequence);
 8102:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8103:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8104: 
 8105:     &Apache::lonxml::clear_problem_counter();
 8106: 
 8107:     my $uname       = $env{'user.name'};
 8108:     my $udom        = $env{'user.domain'};
 8109:     my $cid         = $env{'request.course.id'};
 8110:     my $total_lines = 0;
 8111:     %bubble_lines_per_response = ();
 8112:     %first_bubble_line         = ();
 8113:     %subdivided_bubble_lines   = ();
 8114:     %responsetype_per_response = ();
 8115:     %masterseq_id_responsenum  = ();
 8116: 
 8117:     my $response_number = 0;
 8118:     my $bubble_line     = 0;
 8119:     foreach my $resource (@resources) {
 8120:         my $resid = $resource->id();
 8121:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8122:                                                           $udom,undef,$bubbles_per_row);
 8123:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8124: 	    foreach my $part_id (@{$parts}) {
 8125:                 my $lines;
 8126: 
 8127: 	        # TODO - make this a persistent hash not an array.
 8128: 
 8129:                 # optionresponse, matchresponse and rankresponse type items 
 8130:                 # render as separate sub-questions in exam mode.
 8131:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8132:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8133:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8134:                     my ($numbub,$numshown);
 8135:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8136:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8137:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8138:                         }
 8139:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8140:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8141:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8142:                         }
 8143:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8144:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8145:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8146:                         }
 8147:                     }
 8148:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8149:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8150:                     }
 8151:                     my $bubbles_per_row =
 8152:                         &bubblesheet_bubbles_per_row($scantron_config);
 8153:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8154:                     if (($numbub % $bubbles_per_row) != 0) {
 8155:                         $inner_bubble_lines++;
 8156:                     }
 8157:                     for (my $i=0; $i<$numshown; $i++) {
 8158:                         $subdivided_bubble_lines{$response_number} .= 
 8159:                             $inner_bubble_lines.',';
 8160:                     }
 8161:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8162:                     $lines = $numshown * $inner_bubble_lines;
 8163:                 } else {
 8164:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8165:                 }
 8166: 
 8167:                 $first_bubble_line{$response_number} = $bubble_line;
 8168: 	        $bubble_lines_per_response{$response_number} = $lines;
 8169:                 $responsetype_per_response{$response_number} = 
 8170:                     $analysis->{$part_id.'.type'};
 8171:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8172: 	        $response_number++;
 8173: 
 8174: 	        $bubble_line +=  $lines;
 8175: 	        $total_lines +=  $lines;
 8176: 	    }
 8177:         }
 8178:     }
 8179:     &Apache::lonnet::delenv('scantron.');
 8180: 
 8181:     &save_bubble_lines();
 8182:     $env{'form.scantron_maxbubble'} =
 8183: 	$total_lines;
 8184:     return $env{'form.scantron_maxbubble'};
 8185: }
 8186: 
 8187: sub bubblesheet_bubbles_per_row {
 8188:     my ($scantron_config) = @_;
 8189:     my $bubbles_per_row;
 8190:     if (ref($scantron_config) eq 'HASH') {
 8191:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8192:     }
 8193:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8194:         $bubbles_per_row = 10;
 8195:     }
 8196:     return $bubbles_per_row;
 8197: }
 8198: 
 8199: sub scantron_validate_missingbubbles {
 8200:     my ($r,$currentphase) = @_;
 8201:     #get student info
 8202:     my $classlist=&Apache::loncoursedata::get_classlist();
 8203:     my %idmap=&username_to_idmap($classlist);
 8204:     my (undef,undef,$sequence)=
 8205:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8206: 
 8207:     #get scantron line setup
 8208:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8209:     my ($scanlines,$scan_data)=&scantron_getfile();
 8210: 
 8211:     my $navmap = Apache::lonnavmaps::navmap->new();
 8212:     unless (ref($navmap)) {
 8213:         $r->print(&navmap_errormsg());
 8214:         return(1,$currentphase);
 8215:     }
 8216: 
 8217:     my $map=$navmap->getResourceByUrl($sequence);
 8218:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8219:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8220:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8221:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8222: 
 8223:     my $nav_error;
 8224:     if (ref($map)) {
 8225:         $randomorder = $map->randomorder();
 8226:         $randompick = $map->randompick();
 8227:         if ($randomorder || $randompick) {
 8228:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8229:             if ($nav_error) {
 8230:                 $r->print(&navmap_errormsg());
 8231:                 return(1,$currentphase);
 8232:             }
 8233:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8234:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8235:         }
 8236:     } else {
 8237:         $r->print(&navmap_errormsg());
 8238:         return(1,$currentphase);
 8239:     }
 8240: 
 8241: 
 8242:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8243:     if ($nav_error) {
 8244:         $r->print(&navmap_errormsg());
 8245:         return(1,$currentphase);
 8246:     }
 8247: 
 8248:     if (!$max_bubble) { $max_bubble=2**31; }
 8249:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8250: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8251: 	if ($line=~/^[\s\cz]*$/) { next; }
 8252:         my $scan_record =
 8253:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8254:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8255:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8256:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8257: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8258: 	my @to_correct;
 8259: 	
 8260: 	# Probably here's where the error is...
 8261: 
 8262: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8263:             my $lastbubble;
 8264:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8265:                 my $question = $1;
 8266:                 my $subquestion = $2;
 8267:                 my ($first,$responsenum);
 8268:                 if ($randomorder || $randompick) {
 8269:                     $responsenum = $respnumlookup{$question-1};
 8270:                     $first = $startline{$question-1};
 8271:                 } else {
 8272:                     $responsenum = $question-1;
 8273:                     $first = $first_bubble_line{$responsenum};
 8274:                 }
 8275:                 if (!defined($first)) { next; }
 8276:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8277:                 my $subcount = 1;
 8278:                 while ($subcount<$subquestion) {
 8279:                     $first += $subans[$subcount-1];
 8280:                     $subcount ++;
 8281:                 }
 8282:                 my $count = $subans[$subquestion-1];
 8283:                 $lastbubble = $first + $count;
 8284:             } else {
 8285:                 my ($first,$responsenum);
 8286:                 if ($randomorder || $randompick) {
 8287:                     $responsenum = $respnumlookup{$missing-1};
 8288:                     $first = $startline{$missing-1};
 8289:                 } else {
 8290:                     $responsenum = $missing-1;
 8291:                     $first = $first_bubble_line{$responsenum};
 8292:                 }
 8293:                 if (!defined($first)) { next; }
 8294:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8295:             }
 8296:             if ($lastbubble > $max_bubble) { next; }
 8297: 	    push(@to_correct,$missing);
 8298: 	}
 8299: 	if (@to_correct) {
 8300: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8301: 				     $line,'missingbubble',\@to_correct,
 8302:                                      $randomorder,$randompick,\%respnumlookup,
 8303:                                      \%startline);
 8304: 	    return (1,$currentphase);
 8305: 	}
 8306: 
 8307:     }
 8308:     return (0,$currentphase+1);
 8309: }
 8310: 
 8311: sub hand_bubble_option {
 8312:     my (undef, undef, $sequence) =
 8313:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8314:     return if ($sequence eq '');
 8315:     my $navmap = Apache::lonnavmaps::navmap->new();
 8316:     unless (ref($navmap)) {
 8317:         return;
 8318:     }
 8319:     my $needs_hand_bubbles;
 8320:     my $map=$navmap->getResourceByUrl($sequence);
 8321:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8322:     foreach my $res (@resources) {
 8323:         if (ref($res)) {
 8324:             if ($res->is_problem()) {
 8325:                 my $partlist = $res->parts();
 8326:                 foreach my $part (@{ $partlist }) {
 8327:                     my @types = $res->responseType($part);
 8328:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8329:                         $needs_hand_bubbles = 1;
 8330:                         last;
 8331:                     }
 8332:                 }
 8333:             }
 8334:         }
 8335:     }
 8336:     if ($needs_hand_bubbles) {
 8337:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8338:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8339:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8340:                &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 />').
 8341:                '<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;'.
 8342:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
 8343:     }
 8344:     return;
 8345: }
 8346: 
 8347: sub scantron_process_students {
 8348:     my ($r) = @_;
 8349: 
 8350:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8351:     my ($symb)=&get_symb($r);
 8352:     if (!$symb) {
 8353: 	return '';
 8354:     }
 8355:     my $default_form_data=&defaultFormData($symb);
 8356: 
 8357:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8358:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8359:     my ($scanlines,$scan_data)=&scantron_getfile();
 8360:     my $classlist=&Apache::loncoursedata::get_classlist();
 8361:     my %idmap=&username_to_idmap($classlist);
 8362:     my $navmap=Apache::lonnavmaps::navmap->new();
 8363:     unless (ref($navmap)) {
 8364:         $r->print(&navmap_errormsg());
 8365:         return '';
 8366:     }
 8367:     my $map=$navmap->getResourceByUrl($sequence);
 8368:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8369:         %grader_randomlists_by_symb);
 8370:     if (ref($map)) {
 8371:         $randomorder = $map->randomorder();
 8372:         $randompick = $map->randompick();
 8373:     } else {
 8374:         $r->print(&navmap_errormsg());
 8375:         return '';
 8376:     }
 8377:     my $nav_error;
 8378:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8379:     my (%grader_partids_by_symb,%grader_randomlists_by_symb,%ordered);
 8380:     if ($randomorder || $randompick) {
 8381:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8382:         if ($nav_error) {
 8383:             $r->print(&navmap_errormsg());
 8384:             return '';
 8385:         }
 8386:     }
 8387:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8388:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8389: 
 8390:     my ($uname,$udom);
 8391:     my $result= <<SCANTRONFORM;
 8392: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8393:   <input type="hidden" name="command" value="scantron_configphase" />
 8394:   $default_form_data
 8395: SCANTRONFORM
 8396:     $r->print($result);
 8397: 
 8398:     my @delayqueue;
 8399:     my (%completedstudents,%scandata);
 8400:     
 8401:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8402:     my $count=&get_todo_count($scanlines,$scan_data);
 8403:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8404:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8405: 					  'Processing first student');
 8406:     $r->print('<br />');
 8407:     my $start=&Time::HiRes::time();
 8408:     my $i=-1;
 8409:     my $started;
 8410: 
 8411:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8412:     if ($nav_error) {
 8413:         $r->print(&navmap_errormsg());
 8414:         return '';
 8415:     }
 8416: 
 8417:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8418:     # the user and return.
 8419: 
 8420:     if ($ssi_error) {
 8421: 	$r->print("</form>");
 8422: 	&ssi_print_error($r);
 8423: 	$r->print(&show_grading_menu_form($symb));
 8424:         &Apache::lonnet::remove_lock($lock);
 8425: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8426:     }
 8427: 
 8428:     my %lettdig = &letter_to_digits();
 8429:     my $numletts = scalar(keys(%lettdig));
 8430:     my %orderedforcode;
 8431: 
 8432:     while ($i<$scanlines->{'count'}) {
 8433:  	($uname,$udom)=('','');
 8434:  	$i++;
 8435:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8436:  	if ($line=~/^[\s\cz]*$/) { next; }
 8437: 	if ($started) {
 8438: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8439: 						     'last student');
 8440: 	}
 8441: 	$started=1;
 8442:         my %respnumlookup = ();
 8443:         my %startline = ();
 8444:         my $total;
 8445:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8446:  						 $scan_data,undef,\%idmap,$randomorder,
 8447:                                                  $randompick,$sequence,\@master_seq,
 8448:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8449:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8450:                                                  \$total);
 8451:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8452:  					      \%idmap,$i)) {
 8453:   	    &scantron_add_delay(\@delayqueue,$line,
 8454:  				'Unable to find a student that matches',1);
 8455:  	    next;
 8456:   	}
 8457:  	if (exists $completedstudents{$uname}) {
 8458:  	    &scantron_add_delay(\@delayqueue,$line,
 8459:  				'Student '.$uname.' has multiple sheets',2);
 8460:  	    next;
 8461:  	}
 8462:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8463:         my $user = $uname.':'.$usec;
 8464:   	($uname,$udom)=split(/:/,$uname);
 8465: 
 8466:         my $scancode;
 8467:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8468:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8469:             $scancode = $scan_record->{'scantron.CODE'};
 8470:         } else {
 8471:             $scancode = '';
 8472:         }
 8473: 
 8474:         my @mapresources = @resources;
 8475:         if ($randomorder || $randompick) {
 8476:             @mapresources =
 8477:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8478:                              \%orderedforcode);
 8479:         }
 8480:         my (%partids_by_symb,$res_error);
 8481:         foreach my $resource (@mapresources) {
 8482:             my $ressymb;
 8483:             if (ref($resource)) {
 8484:                 $ressymb = $resource->symb();
 8485:             } else {
 8486:                 $res_error = 1;
 8487:                 last;
 8488:             }
 8489:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8490:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8491:                 my ($analysis,$parts) =
 8492:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8493:                                               $uname,$udom,undef,$bubbles_per_row);
 8494:                 $partids_by_symb{$ressymb} = $parts;
 8495:             } else {
 8496:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8497:             }
 8498:         }
 8499: 
 8500:         if ($res_error) {
 8501:             &scantron_add_delay(\@delayqueue,$line,
 8502:                                 'An error occurred while grading student '.$uname,2);
 8503:             next;
 8504:         }
 8505: 
 8506: 	&Apache::lonxml::clear_problem_counter();
 8507:   	&Apache::lonnet::appenv($scan_record);
 8508: 
 8509: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8510: 	    &scantron_putfile($scanlines,$scan_data);
 8511: 	}
 8512: 	
 8513:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8514:                                    \@mapresources,\%partids_by_symb,
 8515:                                    $bubbles_per_row,$randomorder,$randompick,
 8516:                                    \%respnumlookup,\%startline) 
 8517:             eq 'ssi_error') {
 8518:             $ssi_error = 0; # So end of handler error message does not trigger.
 8519:             $r->print("</form>");
 8520:             &ssi_print_error($r);
 8521:             $r->print(&show_grading_menu_form($symb));
 8522:             &Apache::lonnet::remove_lock($lock);
 8523:             return '';      # Why return ''?  Beats me.
 8524:         }
 8525: 
 8526:         if (($scancode) && ($randomorder || $randompick)) {
 8527:             my $parmresult =
 8528:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8529:                                                        '0_examcode',2,$scancode,
 8530:                                                        'string_examcode',$uname,
 8531:                                                        $udom);
 8532:         }
 8533: 	$completedstudents{$uname}={'line'=>$line};
 8534:         if ($env{'form.verifyrecord'}) {
 8535:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8536:             if ($randompick) {
 8537:                 if ($total) {
 8538:                     $lastpos = $total*$scantron_config{'Qlength'};
 8539:                 }
 8540:             }
 8541: 
 8542:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8543:             chomp($studentdata);
 8544:             $studentdata =~ s/\r$//;
 8545:             my $studentrecord = '';
 8546:             my $counter = -1;
 8547:             foreach my $resource (@mapresources) {
 8548:                 my $ressymb = $resource->symb();
 8549:                 ($counter,my $recording) =
 8550:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8551:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8552:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8553:                                              $randompick,\%respnumlookup,\%startline);
 8554:                 $studentrecord .= $recording;
 8555:             }
 8556:             if ($studentrecord ne $studentdata) {
 8557:                 &Apache::lonxml::clear_problem_counter();
 8558:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8559:                                            \@mapresources,\%partids_by_symb,
 8560:                                            $bubbles_per_row,$randomorder,$randompick,
 8561:                                            \%respnumlookup,\%startline)
 8562:                     eq 'ssi_error') {
 8563:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8564:                     $r->print("</form>");
 8565:                     &ssi_print_error($r);
 8566:                     $r->print(&show_grading_menu_form($symb));
 8567:                     &Apache::lonnet::remove_lock($lock);
 8568:                     delete($completedstudents{$uname});
 8569:                     return '';
 8570:                 }
 8571:                 $counter = -1;
 8572:                 $studentrecord = '';
 8573:                 foreach my $resource (@mapresources) {
 8574:                     my $ressymb = $resource->symb();
 8575:                     ($counter,my $recording) =
 8576:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8577:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8578:                                                  \%scantron_config,\%lettdig,$numletts,
 8579:                                                  $randomorder,$randompick,\%respnumlookup,
 8580:                                                  \%startline);
 8581:                     $studentrecord .= $recording;
 8582:                 }
 8583:                 if ($studentrecord ne $studentdata) {
 8584:                     $r->print('<p><span class="LC_warning">');
 8585:                     if ($scancode eq '') {
 8586:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8587:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8588:                     } else {
 8589:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8590:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8591:                     }
 8592:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8593:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8594:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8595:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8596:                               &Apache::loncommon::start_data_table_row().
 8597:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8598:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 8599:                               &Apache::loncommon::end_data_table_row().
 8600:                               &Apache::loncommon::start_data_table_row().
 8601:                               '<td>'.&mt('Stored submissions').'</td>'.
 8602:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 8603:                               &Apache::loncommon::end_data_table_row().
 8604:                               &Apache::loncommon::end_data_table().'</p>');
 8605:                 } else {
 8606:                     $r->print('<br /><span class="LC_warning">'.
 8607:                              &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 />'.
 8608:                              &mt("As a consequence, this user's submission history records two tries.").
 8609:                                  '</span><br />');
 8610:                 }
 8611:             }
 8612:         }
 8613:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8614:     } continue {
 8615: 	&Apache::lonxml::clear_problem_counter();
 8616: 	&Apache::lonnet::delenv('scantron.');
 8617:     }
 8618:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8619:     &Apache::lonnet::remove_lock($lock);
 8620: #    my $lasttime = &Time::HiRes::time()-$start;
 8621: #    $r->print("<p>took $lasttime</p>");
 8622: 
 8623:     $r->print("</form>");
 8624:     $r->print(&show_grading_menu_form($symb));
 8625:     return '';
 8626: }
 8627: 
 8628: sub graders_resources_pass {
 8629:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8630:         $bubbles_per_row) = @_;
 8631:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8632:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8633:         foreach my $resource (@{$resources}) {
 8634:             my $ressymb = $resource->symb();
 8635:             my ($analysis,$parts) =
 8636:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8637:                                           $env{'user.name'},$env{'user.domain'},
 8638:                                           1,$bubbles_per_row);
 8639:             $grader_partids_by_symb->{$ressymb} = $parts;
 8640:             if (ref($analysis) eq 'HASH') {
 8641:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8642:                     $grader_randomlists_by_symb->{$ressymb} =
 8643:                         $analysis->{'parts_withrandomlist'};
 8644:                 }
 8645:             }
 8646:         }
 8647:     }
 8648:     return;
 8649: }
 8650: 
 8651: =pod
 8652: 
 8653: =item users_order
 8654: 
 8655:   Returns array of resources in current map, ordered based on either CODE,
 8656:   if this is a CODEd exam, or based on student's identity if this is a
 8657:   "NAMEd" exam.
 8658: 
 8659:   Should be used when randomorder and/or randompick applied when the 
 8660:   corresponding exam was printed, prior to students completing bubblesheets 
 8661:   for the version of the exam the student received.
 8662: 
 8663: =cut
 8664: 
 8665: sub users_order  {
 8666:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8667:     my @mapresources;
 8668:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8669:         return @mapresources;
 8670:     }
 8671:     if ($scancode) {
 8672:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8673:             @mapresources = @{$orderedforcode->{$scancode}};
 8674:         } else {
 8675:             $env{'form.CODE'} = $scancode;
 8676:             my $actual_seq =
 8677:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8678:                                                                $master_seq,
 8679:                                                                $user,$scancode,1);
 8680:             if (ref($actual_seq) eq 'ARRAY') {
 8681:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8682:                 if (ref($orderedforcode) eq 'HASH') {
 8683:                     if (@mapresources > 0) {
 8684:                         $orderedforcode->{$scancode} = \@mapresources;
 8685:                     }
 8686:                 }
 8687:             }
 8688:             delete($env{'form.CODE'});
 8689:         }
 8690:     } else {
 8691:         my $actual_seq =
 8692:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8693:                                                            $master_seq,
 8694:                                                            $user,undef,1);
 8695:         if (ref($actual_seq) eq 'ARRAY') {
 8696:             @mapresources =
 8697:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8698:         }
 8699:     }
 8700:     return @mapresources;
 8701: }
 8702: 
 8703: sub grade_student_bubbles {
 8704:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8705:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8706:     my $uselookup = 0;
 8707:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8708:         (ref($startline) eq 'HASH')) {
 8709:         $uselookup = 1;
 8710:     }
 8711: 
 8712:     if (ref($resources) eq 'ARRAY') {
 8713:         my $count = 0;
 8714:         foreach my $resource (@{$resources}) {
 8715:             my $ressymb = $resource->symb();
 8716:             my %form = ('submitted'      => 'scantron',
 8717:                         'grade_target'   => 'grade',
 8718:                         'grade_username' => $uname,
 8719:                         'grade_domain'   => $udom,
 8720:                         'grade_courseid' => $env{'request.course.id'},
 8721:                         'grade_symb'     => $ressymb,
 8722:                         'CODE'           => $scancode
 8723:                        );
 8724:             if ($bubbles_per_row ne '') {
 8725:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8726:             }
 8727:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8728:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8729:             }
 8730:             if (ref($parts) eq 'HASH') {
 8731:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8732:                     foreach my $part (@{$parts->{$ressymb}}) {
 8733:                         if ($uselookup) {
 8734:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8735:                         } else {
 8736:                             $form{'scantron_questnum_start.'.$part} =
 8737:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8738:                         }
 8739:                         $count++;
 8740:                     }
 8741:                 }
 8742:             }
 8743:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8744:             return 'ssi_error' if ($ssi_error);
 8745:             last if (&Apache::loncommon::connection_aborted($r));
 8746:         }
 8747:     }
 8748:     return;
 8749: }
 8750: 
 8751: sub scantron_upload_scantron_data {
 8752:     my ($r)=@_;
 8753:     my $dom = $env{'request.role.domain'};
 8754:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8755:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8756:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8757: 							  'domainid',
 8758: 							  'coursename',$dom);
 8759:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8760:                        ('&nbsp'x2).&mt('(shows course personnel)');
 8761:     my ($symb) = &get_symb($r,1);
 8762:     my $default_form_data=&defaultFormData($symb);
 8763:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8764:     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.");
 8765:     $r->print('
 8766: <script type="text/javascript" language="javascript">
 8767:     function checkUpload(formname) {
 8768: 	if (formname.upfile.value == "") {
 8769: 	    alert("'.$nofile_alert.'");
 8770: 	    return false;
 8771: 	}
 8772:         if (formname.courseid.value == "") {
 8773:             alert("'.$nocourseid_alert.'");
 8774:             return false;
 8775:         }
 8776: 	formname.submit();
 8777:     }
 8778: 
 8779:     function ToSyllabus() {
 8780:         var cdom = '."'$dom'".';
 8781:         var cnum = document.rules.courseid.value;
 8782:         if (cdom == "" || cdom == null) {
 8783:             return;
 8784:         }
 8785:         if (cnum == "" || cnum == null) {
 8786:            return;
 8787:         }
 8788:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8789:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8790:         return;
 8791:     }
 8792: 
 8793: </script>
 8794: 
 8795: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8796: 
 8797: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8798: '.$default_form_data.
 8799:   &Apache::lonhtmlcommon::start_pick_box().
 8800:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8801:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8802:   &Apache::lonhtmlcommon::row_closure().
 8803:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8804:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8805:   &Apache::lonhtmlcommon::row_closure().
 8806:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8807:   '<input name="domainid" type="hidden" />'.$domdesc.
 8808:   &Apache::lonhtmlcommon::row_closure().
 8809:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8810:   '<input type="file" name="upfile" size="50" />'.
 8811:   &Apache::lonhtmlcommon::row_closure(1).
 8812:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8813: 
 8814: <input name="command" value="scantronupload_save" type="hidden" />
 8815: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8816: </form>
 8817: ');
 8818:     return '';
 8819: }
 8820: 
 8821: 
 8822: sub scantron_upload_scantron_data_save {
 8823:     my($r)=@_;
 8824:     my ($symb)=&get_symb($r,1);
 8825:     my $doanotherupload=
 8826: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8827: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8828: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8829: 	'</form>'."\n";
 8830:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8831: 	!&Apache::lonnet::allowed('usc',
 8832: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8833: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8834: 	if ($symb) {
 8835: 	    $r->print(&show_grading_menu_form($symb));
 8836: 	} else {
 8837: 	    $r->print($doanotherupload);
 8838: 	}
 8839: 	return '';
 8840:     }
 8841:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8842:     my $uploadedfile;
 8843:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8844:     if (length($env{'form.upfile'}) < 2) {
 8845:         $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>'));
 8846:     } else {
 8847:         my $result = 
 8848:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8849:                                             $env{'form.courseid'},$env{'form.domainid'});
 8850: 	if ($result =~ m{^/uploaded/}) {
 8851: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8852:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8853: 			  '<span class="LC_filename">'.$result.'</span>'));
 8854:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8855:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8856:                                                        $env{'form.courseid'},$uploadedfile));
 8857: 	} else {
 8858: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8859:                           '<span class="LC_error">','</span>',$result,
 8860: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8861: 	}
 8862:     }
 8863:     if ($symb) {
 8864: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8865:     } else {
 8866: 	$r->print($doanotherupload);
 8867:     }
 8868:     return '';
 8869: }
 8870: 
 8871: sub validate_uploaded_scantron_file {
 8872:     my ($cdom,$cname,$fname) = @_;
 8873:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8874:     my @lines;
 8875:     if ($scanlines ne '-1') {
 8876:         @lines=split("\n",$scanlines,-1);
 8877:     }
 8878:     my $output;
 8879:     if (@lines) {
 8880:         my (%counts,$max_match_format);
 8881:         my ($max_match_count,$max_match_pct) = (0,0);
 8882:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8883:         my %idmap = &username_to_idmap($classlist);
 8884:         foreach my $key (keys(%idmap)) {
 8885:             my $lckey = lc($key);
 8886:             $idmap{$lckey} = $idmap{$key};
 8887:         }
 8888:         my %unique_formats;
 8889:         my @formatlines = &get_scantronformat_file();
 8890:         foreach my $line (@formatlines) {
 8891:             chomp($line);
 8892:             my @config = split(/:/,$line);
 8893:             my $idstart = $config[5];
 8894:             my $idlength = $config[6];
 8895:             if (($idstart ne '') && ($idlength > 0)) {
 8896:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8897:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8898:                 } else {
 8899:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8900:                 }
 8901:             }
 8902:         }
 8903:         foreach my $key (keys(%unique_formats)) {
 8904:             my ($idstart,$idlength) = split(':',$key);
 8905:             %{$counts{$key}} = (
 8906:                                'found'   => 0,
 8907:                                'total'   => 0,
 8908:                               );
 8909:             foreach my $line (@lines) {
 8910:                 next if ($line =~ /^#/);
 8911:                 next if ($line =~ /^[\s\cz]*$/);
 8912:                 my $id = substr($line,$idstart-1,$idlength);
 8913:                 $id = lc($id);
 8914:                 if (exists($idmap{$id})) {
 8915:                     $counts{$key}{'found'} ++;
 8916:                 }
 8917:                 $counts{$key}{'total'} ++;
 8918:             }
 8919:             if ($counts{$key}{'total'}) {
 8920:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8921:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8922:                     $max_match_pct = $percent_match;
 8923:                     $max_match_format = $key;
 8924:                     $max_match_count = $counts{$key}{'total'};
 8925:                 }
 8926:             }
 8927:         }
 8928:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8929:             my $format_descs;
 8930:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8931:             for (my $i=0; $i<$numwithformat; $i++) {
 8932:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8933:                 if ($i<$numwithformat-2) {
 8934:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8935:                 } elsif ($i==$numwithformat-2) {
 8936:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8937:                 } elsif ($i==$numwithformat-1) {
 8938:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8939:                 }
 8940:             }
 8941:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8942:             $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).
 8943:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8944:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8945:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8946:                                   '<i>'.$cdom.'</i>').'</li>'.
 8947:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8948:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8949:                        '</ul>';
 8950:         }
 8951:     } else {
 8952:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8953:     }
 8954:     return $output;
 8955: }
 8956: 
 8957: sub valid_file {
 8958:     my ($requested_file)=@_;
 8959:     foreach my $filename (sort(&scantron_filenames())) {
 8960: 	if ($requested_file eq $filename) { return 1; }
 8961:     }
 8962:     return 0;
 8963: }
 8964: 
 8965: sub scantron_download_scantron_data {
 8966:     my ($r)=@_;
 8967:     my ($symb) = &get_symb($r,1);
 8968:     my $default_form_data=&defaultFormData($symb);
 8969:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8970:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8971:     my $file=$env{'form.scantron_selectfile'};
 8972:     if (! &valid_file($file)) {
 8973: 	$r->print('
 8974: 	<p>
 8975: 	    '.&mt('The requested filename was invalid.').'
 8976:         </p>
 8977: ');
 8978: 	$r->print(&show_grading_menu_form($symb));
 8979: 	return;
 8980:     }
 8981:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8982:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8983:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8984:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8985:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8986:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8987:     $r->print('
 8988:     <p>
 8989: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8990: 	      '<a href="'.$orig.'">','</a>').'
 8991:     </p>
 8992:     <p>
 8993: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8994: 	      '<a href="'.$corrected.'">','</a>').'
 8995:     </p>
 8996:     <p>
 8997: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8998: 	      '<a href="'.$skipped.'">','</a>').'
 8999:     </p>
 9000: ');
 9001:     $r->print(&show_grading_menu_form($symb));
 9002:     return '';
 9003: }
 9004: 
 9005: sub checkscantron_results {
 9006:     my ($r) = @_;
 9007:     my ($symb)=&get_symb($r);
 9008:     if (!$symb) {return '';}
 9009:     my $grading_menu_button=&show_grading_menu_form($symb);
 9010:     my $cid = $env{'request.course.id'};
 9011:     my %lettdig = &letter_to_digits();
 9012:     my $numletts = scalar(keys(%lettdig));
 9013:     my $cnum = $env{'course.'.$cid.'.num'};
 9014:     my $cdom = $env{'course.'.$cid.'.domain'};
 9015:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9016:     my %record;
 9017:     my %scantron_config =
 9018:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9019:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9020:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9021:     my $classlist=&Apache::loncoursedata::get_classlist();
 9022:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9023:     my $navmap=Apache::lonnavmaps::navmap->new();
 9024:     unless (ref($navmap)) {
 9025:         $r->print(&navmap_errormsg());
 9026:         return '';
 9027:     }
 9028:     my $map=$navmap->getResourceByUrl($sequence);
 9029:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9030:         %grader_randomlists_by_symb,%orderedforcode);
 9031:     if (ref($map)) {
 9032:         $randomorder=$map->randomorder();
 9033:         $randompick=$map->randompick();
 9034:     }
 9035:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9036:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9037:     if ($nav_error) {
 9038:         $r->print(&navmap_errormsg());
 9039:         return '';
 9040:     }
 9041:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9042:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9043:     my ($uname,$udom);
 9044:     my (%scandata,%lastname,%bylast);
 9045:     $r->print('
 9046: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9047: 
 9048:     my @delayqueue;
 9049:     my %completedstudents;
 9050: 
 9051:     my $count=&get_todo_count($scanlines,$scan_data);
 9052:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9053:     my ($username,$domain,$started,%ordered);
 9054:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9055:     if ($nav_error) {
 9056:         $r->print(&navmap_errormsg());
 9057:         return '';
 9058:     }
 9059: 
 9060:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9061:                                           'Processing first student');
 9062:     my $start=&Time::HiRes::time();
 9063:     my $i=-1;
 9064: 
 9065:     while ($i<$scanlines->{'count'}) {
 9066:         ($username,$domain,$uname)=('','','');
 9067:         $i++;
 9068:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9069:         if ($line=~/^[\s\cz]*$/) { next; }
 9070:         if ($started) {
 9071:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9072:                                                      'last student');
 9073:         }
 9074:         $started=1;
 9075:         my $scan_record=
 9076:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9077:                                                      $scan_data);
 9078:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9079:                                               \%idmap,$i)) {
 9080:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9081:                                 'Unable to find a student that matches',1);
 9082:             next;
 9083:         }
 9084:         if (exists $completedstudents{$uname}) {
 9085:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9086:                                 'Student '.$uname.' has multiple sheets',2);
 9087:             next;
 9088:         }
 9089:         my $pid = $scan_record->{'scantron.ID'};
 9090:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9091:         push(@{$bylast{$lastname{$pid}}},$pid);
 9092:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9093:         my $user = $uname.':'.$usec;
 9094:         ($username,$domain)=split(/:/,$uname);
 9095: 
 9096:         my $scancode;
 9097:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9098:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9099:             $scancode = $scan_record->{'scantron.CODE'};
 9100:         } else {
 9101:             $scancode = '';
 9102:         }
 9103: 
 9104:         my @mapresources = @resources;
 9105:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9106:         my %respnumlookup=();
 9107:         my %startline=();
 9108:         if ($randomorder || $randompick) {
 9109:             @mapresources =
 9110:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9111:                              \%orderedforcode);
 9112:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9113:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9114:                                              \%grader_partids_by_symb,\%orderedforcode,
 9115:                                              \%respnumlookup,\%startline);
 9116:             if ($randompick && $total) {
 9117:                 $lastpos = $total*$scantron_config{'Qlength'};
 9118:             }
 9119:         }
 9120:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9121:         chomp($scandata{$pid});
 9122:         $scandata{$pid} =~ s/\r$//;
 9123: 
 9124:         my $counter = -1;
 9125:         foreach my $resource (@mapresources) {
 9126:             my $parts;
 9127:             my $ressymb = $resource->symb();
 9128:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9129:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9130:                 (my $analysis,$parts) =
 9131:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9132:                                               $username,$domain,undef,
 9133:                                               $bubbles_per_row);
 9134:             } else {
 9135:                 $parts = $grader_partids_by_symb{$ressymb};
 9136:             }
 9137:             ($counter,my $recording) =
 9138:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9139:                                          $scandata{$pid},$parts,
 9140:                                          \%scantron_config,\%lettdig,$numletts,
 9141:                                          $randomorder,$randompick,
 9142:                                          \%respnumlookup,\%startline);
 9143:             $record{$pid} .= $recording;
 9144:         }
 9145:     }
 9146:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9147:     $r->print('<br />');
 9148:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9149:     $passed = 0;
 9150:     $failed = 0;
 9151:     $numstudents = 0;
 9152:     foreach my $last (sort(keys(%bylast))) {
 9153:         if (ref($bylast{$last}) eq 'ARRAY') {
 9154:             foreach my $pid (sort(@{$bylast{$last}})) {
 9155:                 my $showscandata = $scandata{$pid};
 9156:                 my $showrecord = $record{$pid};
 9157:                 $showscandata =~ s/\s/&nbsp;/g;
 9158:                 $showrecord =~ s/\s/&nbsp;/g;
 9159:                 if ($scandata{$pid} eq $record{$pid}) {
 9160:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9161:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9162: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9163: '</tr>'."\n".
 9164: '<tr class="'.$css_class.'">'."\n".
 9165: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 9166:                     $passed ++;
 9167:                 } else {
 9168:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9169:                     $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".
 9170: '</tr>'."\n".
 9171: '<tr class="'.$css_class.'">'."\n".
 9172: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9173: '</tr>'."\n";
 9174:                     $failed ++;
 9175:                 }
 9176:                 $numstudents ++;
 9177:             }
 9178:         }
 9179:     }
 9180:     $r->print('<p>'.
 9181:               &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).',
 9182:                   '<b>',
 9183:                   $numstudents,
 9184:                   '</b>',
 9185:                   $env{'form.scantron_maxbubble'}).
 9186:               '</p>'
 9187:     );
 9188:     $r->print('<p>'
 9189:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9190:              .'<br />'
 9191:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9192:              .'</p>');
 9193:     if ($passed) {
 9194:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9195:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9196:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9197:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9198:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9199:                  $okstudents."\n".
 9200:                  &Apache::loncommon::end_data_table().'<br />');
 9201:     }
 9202:     if ($failed) {
 9203:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9204:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9205:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9206:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9207:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9208:                  $badstudents."\n".
 9209:                  &Apache::loncommon::end_data_table()).'<br />'.
 9210:                  &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.');  
 9211:     }
 9212:     $r->print('</form><br />'.$grading_menu_button);
 9213:     return;
 9214: }
 9215: 
 9216: sub verify_scantron_grading {
 9217:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9218:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9219:         $respnumlookup,$startline) = @_;
 9220:     my ($record,%expected,%startpos);
 9221:     return ($counter,$record) if (!ref($resource));
 9222:     return ($counter,$record) if (!$resource->is_problem());
 9223:     my $symb = $resource->symb();
 9224:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9225:     foreach my $part_id (@{$partids}) {
 9226:         $counter ++;
 9227:         $expected{$part_id} = 0;
 9228:         my $respnum = $counter;
 9229:         if ($randomorder || $randompick) {
 9230:             $respnum = $respnumlookup->{$counter};
 9231:             $startpos{$part_id} = $startline->{$counter} + 1;
 9232:         } else {
 9233:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9234:         }
 9235:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9236:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9237:             foreach my $item (@sub_lines) {
 9238:                 $expected{$part_id} += $item;
 9239:             }
 9240:         } else {
 9241:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9242:         }
 9243:     }
 9244:     if ($symb) {
 9245:         my %recorded;
 9246:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9247:         if ($returnhash{'version'}) {
 9248:             my %lasthash=();
 9249:             my $version;
 9250:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9251:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9252:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9253:                 }
 9254:             }
 9255:             foreach my $key (keys(%lasthash)) {
 9256:                 if ($key =~ /\.scantron$/) {
 9257:                     my $value = &unescape($lasthash{$key});
 9258:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9259:                     if ($value eq '') {
 9260:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9261:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9262:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9263:                             }
 9264:                         }
 9265:                     } else {
 9266:                         my @tocheck;
 9267:                         my @items = split(//,$value);
 9268:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9269:                             ($scantron_config->{'Qon'} eq 'number')) {
 9270:                             if (@items < $expected{$part_id}) {
 9271:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9272:                                 my @singles = split(//,$fragment);
 9273:                                 foreach my $pos (@singles) {
 9274:                                     if ($pos eq ' ') {
 9275:                                         push(@tocheck,$pos);
 9276:                                     } else {
 9277:                                         my $next = shift(@items);
 9278:                                         push(@tocheck,$next);
 9279:                                     }
 9280:                                 }
 9281:                             } else {
 9282:                                 @tocheck = @items;
 9283:                             }
 9284:                             foreach my $letter (@tocheck) {
 9285:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9286:                                     if ($letter !~ /^[A-J]$/) {
 9287:                                         $letter = $scantron_config->{'Qoff'};
 9288:                                     }
 9289:                                     $recorded{$part_id} .= $letter;
 9290:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9291:                                     my $digit;
 9292:                                     if ($letter !~ /^[A-J]$/) {
 9293:                                         $digit = $scantron_config->{'Qoff'};
 9294:                                     } else {
 9295:                                         $digit = $lettdig->{$letter};
 9296:                                     }
 9297:                                     $recorded{$part_id} .= $digit;
 9298:                                 }
 9299:                             }
 9300:                         } else {
 9301:                             @tocheck = @items;
 9302:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9303:                                 my $curr_sub = shift(@tocheck);
 9304:                                 my $digit;
 9305:                                 if ($curr_sub =~ /^[A-J]$/) {
 9306:                                     $digit = $lettdig->{$curr_sub}-1;
 9307:                                 }
 9308:                                 if ($curr_sub eq 'J') {
 9309:                                     $digit += scalar($numletts);
 9310:                                 }
 9311:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9312:                                     if ($j == $digit) {
 9313:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9314:                                     } else {
 9315:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9316:                                     }
 9317:                                 }
 9318:                             }
 9319:                         }
 9320:                     }
 9321:                 }
 9322:             }
 9323:         }
 9324:         foreach my $part_id (@{$partids}) {
 9325:             if ($recorded{$part_id} eq '') {
 9326:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9327:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9328:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9329:                     }
 9330:                 }
 9331:             }
 9332:             $record .= $recorded{$part_id};
 9333:         }
 9334:     }
 9335:     return ($counter,$record);
 9336: }
 9337: 
 9338: sub letter_to_digits {
 9339:     my %lettdig = (
 9340:                     A => 1,
 9341:                     B => 2,
 9342:                     C => 3,
 9343:                     D => 4,
 9344:                     E => 5,
 9345:                     F => 6,
 9346:                     G => 7,
 9347:                     H => 8,
 9348:                     I => 9,
 9349:                     J => 0,
 9350:                   );
 9351:     return %lettdig;
 9352: }
 9353: 
 9354: 
 9355: #-------- end of section for handling grading scantron forms -------
 9356: #
 9357: #-------------------------------------------------------------------
 9358: 
 9359: #-------------------------- Menu interface -------------------------
 9360: #
 9361: #--- Show a Grading Menu button - Calls the next routine ---
 9362: sub show_grading_menu_form {
 9363:     my ($symb)=@_;
 9364:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9365: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9366: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9367: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9368: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9369: 	'</form>'."\n";
 9370:     return $result;
 9371: }
 9372: 
 9373: # -- Retrieve choices for grading form
 9374: sub savedState {
 9375:     my %savedState = ();
 9376:     if ($env{'form.saveState'}) {
 9377: 	foreach (split(/:/,$env{'form.saveState'})) {
 9378: 	    my ($key,$value) = split(/=/,$_,2);
 9379: 	    $savedState{$key} = $value;
 9380: 	}
 9381:     }
 9382:     return \%savedState;
 9383: }
 9384: 
 9385: #--- Href with symb and command ---
 9386: 
 9387: sub href_symb_cmd {
 9388:     my ($symb,$cmd)=@_;
 9389:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9390: }
 9391: 
 9392: sub grading_menu {
 9393:     my ($request) = @_;
 9394:     my ($symb)=&get_symb($request);
 9395:     if (!$symb) {return '';}
 9396:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9397:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9398: 
 9399:     $request->print($table);
 9400:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9401:                   'handgrade'=>$hdgrade,
 9402:                   'probTitle'=>$probTitle,
 9403:                   'command'=>'submit_options',
 9404:                   'saveState'=>"",
 9405:                   'gradingMenu'=>1,
 9406:                   'showgrading'=>"yes");
 9407:     
 9408:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9409:     
 9410:     $fields{'command'} = 'csvform';
 9411:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9412:     
 9413:     $fields{'command'} = 'processclicker';
 9414:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9415:     
 9416:     $fields{'command'} = 'scantron_selectphase';
 9417:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9418:     
 9419:     my @menu = ({	categorytitle=>'Course Grading',
 9420:             items =>[
 9421:                         {	linktext => 'Manual Grading/View Submissions',
 9422:                     		url => $url1,
 9423:                     		permission => 'F',
 9424:                     		icon => 'edit-find-replace.png',
 9425:                     		linktitle => 'Start the process of hand grading submissions.'
 9426:                         },
 9427:                 	    {	linktext => 'Upload Scores',
 9428:                     		url => $url2,
 9429:                     		permission => 'F',
 9430:                     		icon => 'uploadscores.png',
 9431:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9432:                 	    },
 9433:                 	    {	linktext => 'Process Clicker',
 9434:                     		url => $url3,
 9435:                     		permission => 'F',
 9436:                     		icon => 'addClickerInfoFile.png',
 9437:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9438:                 	    },
 9439:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9440:                     		url => $url4,
 9441:                     		permission => 'F',
 9442:                     		icon => 'stat.png',
 9443:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9444:                 	    }
 9445:                     ]
 9446:             });
 9447: 
 9448:     #$fields{'command'} = 'verify';
 9449:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9450:     #
 9451:     # Create the menu
 9452:     my $Str;
 9453:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9454:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9455:     $Str .= '<input type="hidden" name="command" value="" />'.
 9456:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9457: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9458: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9459: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9460: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9461: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9462: 
 9463:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9464:     #$menudata->{'jscript'}
 9465:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9466:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9467:         ' /> '.
 9468:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9469:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9470: 
 9471:     $Str .="</form>\n";
 9472:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9473:     $request->print(<<GRADINGMENUJS);
 9474: <script type="text/javascript" language="javascript">
 9475:     function checkChoice(formname,val,cmdx) {
 9476: 	if (val <= 2) {
 9477: 	    var cmd = radioSelection(formname.radioChoice);
 9478: 	    var cmdsave = cmd;
 9479: 	} else {
 9480: 	    cmd = cmdx;
 9481: 	    cmdsave = 'submission';
 9482: 	}
 9483: 	formname.command.value = cmd;
 9484: 	if (val < 5) formname.submit();
 9485: 	if (val == 5) {
 9486: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9487: 	        return false;
 9488: 	    } else {
 9489: 	        formname.submit();
 9490: 	    }
 9491: 	}
 9492:     }
 9493: 
 9494:     function checkReceiptNo(formname,nospace) {
 9495: 	var receiptNo = formname.receipt.value;
 9496: 	var checkOpt = false;
 9497: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9498: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9499: 	if (checkOpt) {
 9500: 	    alert("$receiptalert");
 9501: 	    formname.receipt.value = "";
 9502: 	    formname.receipt.focus();
 9503: 	    return false;
 9504: 	}
 9505: 	return true;
 9506:     }
 9507: </script>
 9508: GRADINGMENUJS
 9509:     &commonJSfunctions($request);
 9510:     return $Str;    
 9511: }
 9512: 
 9513: 
 9514: #--- Displays the submissions first page -------
 9515: sub submit_options {
 9516:     my ($request) = @_;
 9517:     my ($symb)=&get_symb($request);
 9518:     if (!$symb) {return '';}
 9519:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9520: 
 9521:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9522:     $request->print(<<GRADINGMENUJS);
 9523: <script type="text/javascript" language="javascript">
 9524:     function checkChoice(formname,val,cmdx) {
 9525: 	if (val <= 2) {
 9526: 	    var cmd = radioSelection(formname.radioChoice);
 9527: 	    var cmdsave = cmd;
 9528: 	} else {
 9529: 	    cmd = cmdx;
 9530: 	    cmdsave = 'submission';
 9531: 	}
 9532: 	formname.command.value = cmd;
 9533: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9534: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9535: 	if (val < 5) formname.submit();
 9536: 	if (val == 5) {
 9537: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9538: 	    formname.submit();
 9539: 	}
 9540: 	if (val < 7) formname.submit();
 9541:     }
 9542: 
 9543:     function checkReceiptNo(formname,nospace) {
 9544: 	var receiptNo = formname.receipt.value;
 9545: 	var checkOpt = false;
 9546: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9547: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9548: 	if (checkOpt) {
 9549: 	    alert("$receiptalert");
 9550: 	    formname.receipt.value = "";
 9551: 	    formname.receipt.focus();
 9552: 	    return false;
 9553: 	}
 9554: 	return true;
 9555:     }
 9556: </script>
 9557: GRADINGMENUJS
 9558:     &commonJSfunctions($request);
 9559:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9560:     my $result;
 9561:     my (undef,$sections) = &getclasslist('all','0');
 9562:     my $savedState = &savedState();
 9563:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9564:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9565:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9566:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9567: 
 9568:     # Preselect sections
 9569:     my $selsec="";
 9570:     if (ref($sections)) {
 9571:         foreach my $section (sort(@$sections)) {
 9572:             $selsec.='<option value="'.$section.'" '.
 9573:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9574:         }
 9575:     }
 9576: 
 9577:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9578: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9579: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9580: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9581: 	'<input type="hidden" name="command"     value="" />'."\n".
 9582: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9583: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9584: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9585: 
 9586:     $result.='
 9587: <h2>
 9588:   '.&mt('Grade Current Resource').'
 9589: </h2>
 9590: <div>
 9591:   '.$table.'
 9592: </div>
 9593: 
 9594: <div class="LC_columnSection">
 9595:   
 9596:     <fieldset>
 9597:       <legend>
 9598:        '.&mt('Sections').'
 9599:       </legend>
 9600:       <select name="section" multiple="multiple" size="5">'."\n";
 9601:     $result.= $selsec;
 9602:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9603:     $result.='
 9604:     </fieldset>
 9605:   
 9606:     <fieldset>
 9607:       <legend>
 9608:         '.&mt('Groups').'
 9609:       </legend>
 9610:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9611:     </fieldset>
 9612:   
 9613:     <fieldset>
 9614:       <legend>
 9615:         '.&mt('Access Status').'
 9616:       </legend>
 9617:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9618:     </fieldset>
 9619:   
 9620:     <fieldset>
 9621:       <legend>
 9622:         '.&mt('Submission Status').'
 9623:       </legend>
 9624:       <select name="submitonly" size="5">
 9625: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9626: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9627: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9628: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9629:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9630:       </select>
 9631:     </fieldset>
 9632:   
 9633: </div>
 9634: 
 9635: <br />
 9636:           <div>
 9637:             <div>
 9638:               <label>
 9639:                 <input type="radio" name="radioChoice" value="submission" '.
 9640:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9641:              &mt('Select individual students to grade and view submissions.').'
 9642: 	      </label> 
 9643:             </div>
 9644:             <div>
 9645: 	      <label>
 9646:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9647:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 9648:                     &mt('Grade all selected students in a grading table.').'
 9649:               </label>
 9650:             </div>
 9651:             <div>
 9652: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9653:             </div>
 9654:           </div>
 9655: 
 9656: 
 9657:         <h2>
 9658:          '.&mt('Grade Complete Folder for One Student').'
 9659:         </h2>
 9660:         <div>
 9661:             <div>
 9662:               <label>
 9663:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 9664: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 9665:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 9666:               </label>
 9667:             </div>
 9668:             <div>
 9669: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9670:             </div>
 9671:         </div>
 9672:   </form>';
 9673:     $result .= &show_grading_menu_form($symb);
 9674:     return $result;
 9675: }
 9676: 
 9677: sub reset_perm {
 9678:     undef(%perm);
 9679: }
 9680: 
 9681: sub init_perm {
 9682:     &reset_perm();
 9683:     foreach my $test_perm ('vgr','mgr','opa') {
 9684: 
 9685: 	my $scope = $env{'request.course.id'};
 9686: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9687: 
 9688: 	    $scope .= '/'.$env{'request.course.sec'};
 9689: 	    if ( $perm{$test_perm}=
 9690: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9691: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9692: 	    } else {
 9693: 		delete($perm{$test_perm});
 9694: 	    }
 9695: 	}
 9696:     }
 9697: }
 9698: 
 9699: sub init_old_essays {
 9700:     my ($symb,$apath,$adom,$aname) = @_;
 9701:     if ($symb ne '') {
 9702:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9703:         if (keys(%essays) > 0) {
 9704:             $old_essays{$symb} = \%essays;
 9705:         }
 9706:     }
 9707:     return;
 9708: }
 9709: 
 9710: sub reset_old_essays {
 9711:     undef(%old_essays);
 9712: }
 9713: 
 9714: sub gather_clicker_ids {
 9715:     my %clicker_ids;
 9716: 
 9717:     my $classlist = &Apache::loncoursedata::get_classlist();
 9718: 
 9719:     # Set up a couple variables.
 9720:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9721:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9722:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9723: 
 9724:     foreach my $student (keys(%$classlist)) {
 9725:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9726:         my $username = $classlist->{$student}->[$username_idx];
 9727:         my $domain   = $classlist->{$student}->[$domain_idx];
 9728:         my $clickers =
 9729: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9730:         foreach my $id (split(/\,/,$clickers)) {
 9731:             $id=~s/^[\#0]+//;
 9732:             $id=~s/[\-\:]//g;
 9733:             if (exists($clicker_ids{$id})) {
 9734: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9735:             } else {
 9736: 		$clicker_ids{$id}=$username.':'.$domain;
 9737:             }
 9738:         }
 9739:     }
 9740:     return %clicker_ids;
 9741: }
 9742: 
 9743: sub gather_adv_clicker_ids {
 9744:     my %clicker_ids;
 9745:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9746:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9747:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9748:     foreach my $element (sort(keys(%coursepersonnel))) {
 9749:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9750:             my ($puname,$pudom)=split(/\:/,$person);
 9751:             my $clickers =
 9752: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9753:             foreach my $id (split(/\,/,$clickers)) {
 9754: 		$id=~s/^[\#0]+//;
 9755:                 $id=~s/[\-\:]//g;
 9756: 		if (exists($clicker_ids{$id})) {
 9757: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9758: 		} else {
 9759: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9760: 		}
 9761:             }
 9762:         }
 9763:     }
 9764:     return %clicker_ids;
 9765: }
 9766: 
 9767: sub clicker_grading_parameters {
 9768:     return ('gradingmechanism' => 'scalar',
 9769:             'upfiletype' => 'scalar',
 9770:             'specificid' => 'scalar',
 9771:             'pcorrect' => 'scalar',
 9772:             'pincorrect' => 'scalar');
 9773: }
 9774: 
 9775: sub process_clicker {
 9776:     my ($r)=@_;
 9777:     my ($symb)=&get_symb($r);
 9778:     if (!$symb) {return '';}
 9779:     my $result=&checkforfile_js();
 9780:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 9781:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 9782:     $result.=$table;
 9783:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 9784:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 9785:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 9786:         '</b></td></tr>'."\n";
 9787:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 9788: # Attempt to restore parameters from last session, set defaults if not present
 9789:     my %Saveable_Parameters=&clicker_grading_parameters();
 9790:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9791:                                                  \%Saveable_Parameters);
 9792:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9793:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9794:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9795:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9796: 
 9797:     my %checked;
 9798:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9799:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9800:           $checked{$gradingmechanism}=' checked="checked"';
 9801:        }
 9802:     }
 9803: 
 9804:     my $upload=&mt("Upload File");
 9805:     my $type=&mt("Type");
 9806:     my $attendance=&mt("Award points just for participation");
 9807:     my $personnel=&mt("Correctness determined from response by course personnel");
 9808:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9809:     my $given=&mt("Correctness determined from given list of answers").' '.
 9810:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9811:     my $pcorrect=&mt("Percentage points for correct solution");
 9812:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9813:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9814:                                                    {'iclicker' => 'i>clicker',
 9815:                                                     'interwrite' => 'interwrite PRS',
 9816:                                                     'turning' => 'Turning Technologies'});
 9817:     $symb = &Apache::lonenc::check_encrypt($symb);
 9818:     $result.=<<ENDUPFORM;
 9819: <script type="text/javascript">
 9820: function sanitycheck() {
 9821: // Accept only integer percentages
 9822:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9823:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9824: // Find out grading choice
 9825:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9826:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9827:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9828:       }
 9829:    }
 9830: // By default, new choice equals user selection
 9831:    newgradingchoice=gradingchoice;
 9832: // Not good to give more points for false answers than correct ones
 9833:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9834:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9835:    }
 9836: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9837:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9838:       document.forms.gradesupload.pcorrect.value=100;
 9839:       document.forms.gradesupload.pincorrect.value=100;
 9840:    }
 9841: // If the values are different, cannot be attendance only
 9842:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9843:        (gradingchoice=='attendance')) {
 9844:        newgradingchoice='personnel';
 9845:    }
 9846: // Change grading choice to new one
 9847:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9848:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9849:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9850:       } else {
 9851:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9852:       }
 9853:    }
 9854: // Remember the old state
 9855:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9856: }
 9857: </script>
 9858: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9859: <input type="hidden" name="symb" value="$symb" />
 9860: <input type="hidden" name="command" value="processclickerfile" />
 9861: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9862: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9863: <input type="file" name="upfile" size="50" />
 9864: <br /><label>$type: $selectform</label>
 9865: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9866: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9867: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9868: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9869: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9870: <br />&nbsp;&nbsp;&nbsp;
 9871: <input type="text" name="givenanswer" size="50" />
 9872: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9873: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9874: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9875: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9876: </form>
 9877: ENDUPFORM
 9878:     $result.='</td></tr></table>'."\n".
 9879:              '</td></tr></table><br /><br />'."\n";
 9880:     $result.=&show_grading_menu_form($symb);
 9881:     return $result;
 9882: }
 9883: 
 9884: sub process_clicker_file {
 9885:     my ($r)=@_;
 9886:     my ($symb)=&get_symb($r);
 9887:     if (!$symb) {return '';}
 9888: 
 9889:     my %Saveable_Parameters=&clicker_grading_parameters();
 9890:     &Apache::loncommon::store_course_settings('grades_clicker',
 9891:                                               \%Saveable_Parameters);
 9892: 
 9893:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9894:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9895: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9896: 	return $result.&show_grading_menu_form($symb);
 9897:     }
 9898:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9899:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9900:         return $result.&show_grading_menu_form($symb);
 9901:     }
 9902:     my $foundgiven=0;
 9903:     if ($env{'form.gradingmechanism'} eq 'given') {
 9904:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9905:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9906:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9907:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9908:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9909:         $foundgiven=$#answers+1;
 9910:     }
 9911:     my %clicker_ids=&gather_clicker_ids();
 9912:     my %correct_ids;
 9913:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9914: 	%correct_ids=&gather_adv_clicker_ids();
 9915:     }
 9916:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9917: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9918: 	   $correct_id=~tr/a-z/A-Z/;
 9919: 	   $correct_id=~s/\s//gs;
 9920: 	   $correct_id=~s/^[\#0]+//;
 9921:            $correct_id=~s/[\-\:]//g;
 9922:            if ($correct_id) {
 9923: 	      $correct_ids{$correct_id}='specified';
 9924:            }
 9925:         }
 9926:     }
 9927:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9928: 	$result.=&mt('Score based on attendance only');
 9929:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9930:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9931:     } else {
 9932: 	my $number=0;
 9933: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9934: 	foreach my $id (sort(keys(%correct_ids))) {
 9935: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9936: 	    if ($correct_ids{$id} eq 'specified') {
 9937: 		$result.=&mt('specified');
 9938: 	    } else {
 9939: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9940: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9941: 	    }
 9942: 	    $number++;
 9943: 	}
 9944:         $result.="</p>\n";
 9945: 	if ($number==0) {
 9946: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9947: 	    return $result.&show_grading_menu_form($symb);
 9948: 	}
 9949:     }
 9950:     if (length($env{'form.upfile'}) < 2) {
 9951:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9952: 		     '<span class="LC_error">',
 9953: 		     '</span>',
 9954: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9955:         return $result.&show_grading_menu_form($symb);
 9956:     }
 9957: 
 9958: # Were able to get all the info needed, now analyze the file
 9959: 
 9960:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9961:     $symb = &Apache::lonenc::check_encrypt($symb);
 9962:     my $heading=&mt('Scanning clicker file');
 9963:     $result.=(<<ENDHEADER);
 9964: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9965: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9966: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
 9967: <form method="post" action="/adm/grades" name="clickeranalysis">
 9968: <input type="hidden" name="symb" value="$symb" />
 9969: <input type="hidden" name="command" value="assignclickergrades" />
 9970: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9971: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9972: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9973: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9974: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9975: ENDHEADER
 9976:     if ($env{'form.gradingmechanism'} eq 'given') {
 9977:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9978:     } 
 9979:     my %responses;
 9980:     my @questiontitles;
 9981:     my $errormsg='';
 9982:     my $number=0;
 9983:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9984: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9985:     }
 9986:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9987:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9988:     }
 9989:     if ($env{'form.upfiletype'} eq 'turning') {
 9990:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9991:     }
 9992:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9993:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9994:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9995:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9996:              '<br />';
 9997:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9998:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9999:        return $result.&show_grading_menu_form($symb);
10000:     } 
10001: # Remember Question Titles
10002: # FIXME: Possibly need delimiter other than ":"
10003:     for (my $i=0;$i<$number;$i++) {
10004:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10005:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10006:     }
10007:     my $correct_count=0;
10008:     my $student_count=0;
10009:     my $unknown_count=0;
10010: # Match answers with usernames
10011: # FIXME: Possibly need delimiter other than ":"
10012:     foreach my $id (keys(%responses)) {
10013:        if ($correct_ids{$id}) {
10014:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10015:           $correct_count++;
10016:        } elsif ($clicker_ids{$id}) {
10017:           if ($clicker_ids{$id}=~/\,/) {
10018: # More than one user with the same clicker!
10019:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10020:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10021:                            "<select name='multi".$id."'>";
10022:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10023:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10024:              }
10025:              $result.='</select>';
10026:              $unknown_count++;
10027:           } else {
10028: # Good: found one and only one user with the right clicker
10029:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10030:              $student_count++;
10031:           }
10032:        } else {
10033:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10034:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10035:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10036:                    "\n".&mt("Domain").": ".
10037:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10038:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10039:           $unknown_count++;
10040:        }
10041:     }
10042:     $result.='<hr />'.
10043:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10044:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10045:        if ($correct_count==0) {
10046:           $errormsg.="Found no correct answers for grading!";
10047:        } elsif ($correct_count>1) {
10048:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10049:        }
10050:     }
10051:     if ($number<1) {
10052:        $errormsg.="Found no questions.";
10053:     }
10054:     if ($errormsg) {
10055:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10056:     } else {
10057:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10058:     }
10059:     $result.='</form></td></tr></table>'."\n".
10060:              '</td></tr></table><br /><br />'."\n";
10061:     return $result.&show_grading_menu_form($symb);
10062: }
10063: 
10064: sub iclicker_eval {
10065:     my ($questiontitles,$responses)=@_;
10066:     my $number=0;
10067:     my $errormsg='';
10068:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10069:         my %components=&Apache::loncommon::record_sep($line);
10070:         my @entries=map {$components{$_}} (sort(keys(%components)));
10071: 	if ($entries[0] eq 'Question') {
10072: 	    for (my $i=3;$i<$#entries;$i+=6) {
10073: 		$$questiontitles[$number]=$entries[$i];
10074: 		$number++;
10075: 	    }
10076: 	}
10077: 	if ($entries[0]=~/^\#/) {
10078: 	    my $id=$entries[0];
10079: 	    my @idresponses;
10080: 	    $id=~s/^[\#0]+//;
10081: 	    for (my $i=0;$i<$number;$i++) {
10082: 		my $idx=3+$i*6;
10083:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10084: 		push(@idresponses,$entries[$idx]);
10085: 	    }
10086: 	    $$responses{$id}=join(',',@idresponses);
10087: 	}
10088:     }
10089:     return ($errormsg,$number);
10090: }
10091: 
10092: sub interwrite_eval {
10093:     my ($questiontitles,$responses)=@_;
10094:     my $number=0;
10095:     my $errormsg='';
10096:     my $skipline=1;
10097:     my $questionnumber=0;
10098:     my %idresponses=();
10099:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10100:         my %components=&Apache::loncommon::record_sep($line);
10101:         my @entries=map {$components{$_}} (sort(keys(%components)));
10102:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10103:         if ($entries[1] eq 'Response') { $skipline=1; }
10104:         next if $skipline;
10105:         if ($entries[0]!=$questionnumber) {
10106:            $questionnumber=$entries[0];
10107:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10108:            $number++;
10109:         }
10110:         my $id=$entries[4];
10111:         $id=~s/^[\#0]+//;
10112:         $id=~s/^v\d*\://i;
10113:         $id=~s/[\-\:]//g;
10114:         $idresponses{$id}[$number]=$entries[6];
10115:     }
10116:     foreach my $id (keys(%idresponses)) {
10117:        $$responses{$id}=join(',',@{$idresponses{$id}});
10118:        $$responses{$id}=~s/^\s*\,//;
10119:     }
10120:     return ($errormsg,$number);
10121: }
10122: 
10123: sub turning_eval {
10124:     my ($questiontitles,$responses)=@_;
10125:     my $number=0;
10126:     my $errormsg='';
10127:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10128:         my %components=&Apache::loncommon::record_sep($line);
10129:         my @entries=map {$components{$_}} (sort(keys(%components)));
10130:         if ($#entries>$number) { $number=$#entries; }
10131:         my $id=$entries[0];
10132:         my @idresponses;
10133:         $id=~s/^[\#0]+//;
10134:         unless ($id) { next; }
10135:         for (my $idx=1;$idx<=$#entries;$idx++) {
10136:             $entries[$idx]=~s/\,/\;/g;
10137:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10138:             push(@idresponses,$entries[$idx]);
10139:         }
10140:         $$responses{$id}=join(',',@idresponses);
10141:     }
10142:     for (my $i=1; $i<=$number; $i++) {
10143:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10144:     }
10145:     return ($errormsg,$number);
10146: }
10147: 
10148: sub assign_clicker_grades {
10149:     my ($r)=@_;
10150:     my ($symb)=&get_symb($r);
10151:     if (!$symb) {return '';}
10152: # See which part we are saving to
10153:     my $res_error;
10154:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10155:     if ($res_error) {
10156:         return &navmap_errormsg();
10157:     }
10158: # FIXME: This should probably look for the first handgradeable part
10159:     my $part=$$partlist[0];
10160: # Start screen output
10161:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10162: 
10163:     $result .= '<br />'.
10164:                &Apache::loncommon::start_data_table().
10165:                &Apache::loncommon::start_data_table_header_row().
10166:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10167:                &Apache::loncommon::end_data_table_header_row().
10168:                &Apache::loncommon::start_data_table_row().'<td>';
10169: 
10170: # Get correct result
10171: # FIXME: Possibly need delimiter other than ":"
10172:     my @correct=();
10173:     my $gradingmechanism=$env{'form.gradingmechanism'};
10174:     my $number=$env{'form.number'};
10175:     if ($gradingmechanism ne 'attendance') {
10176:        foreach my $key (keys(%env)) {
10177:           if ($key=~/^form\.correct\:/) {
10178:              my @input=split(/\,/,$env{$key});
10179:              for (my $i=0;$i<=$#input;$i++) {
10180:                  if (($correct[$i]) && ($input[$i]) &&
10181:                      ($correct[$i] ne $input[$i])) {
10182:                     $result.='<br /><span class="LC_warning">'.
10183:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10184:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10185:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10186:                     $correct[$i]=$input[$i];
10187:                  }
10188:              }
10189:           }
10190:        }
10191:        for (my $i=0;$i<$number;$i++) {
10192:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10193:              $result.='<br /><span class="LC_error">'.
10194:                       &mt('No correct result given for question "[_1]"!',
10195:                           $env{'form.question:'.$i}).'</span>';
10196:           }
10197:        }
10198:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10199:     }
10200: # Start grading
10201:     my $pcorrect=$env{'form.pcorrect'};
10202:     my $pincorrect=$env{'form.pincorrect'};
10203:     my $storecount=0;
10204:     my %users=();
10205:     foreach my $key (keys(%env)) {
10206:        my $user='';
10207:        if ($key=~/^form\.student\:(.*)$/) {
10208:           $user=$1;
10209:        }
10210:        if ($key=~/^form\.unknown\:(.*)$/) {
10211:           my $id=$1;
10212:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10213:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10214:           } elsif ($env{'form.multi'.$id}) {
10215:              $user=$env{'form.multi'.$id};
10216:           }
10217:        }
10218:        if ($user) {
10219:           if ($users{$user}) {
10220:              $result.='<br /><span class="LC_warning">'.
10221:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10222:                       '</span><br />';
10223:           }
10224:           $users{$user}=1;
10225:           my @answer=split(/\,/,$env{$key});
10226:           my $sum=0;
10227:           my $realnumber=$number;
10228:           for (my $i=0;$i<$number;$i++) {
10229:              if  ($correct[$i] eq '-') {
10230:                 $realnumber--;
10231:              } elsif ($answer[$i]) {
10232:                 if ($gradingmechanism eq 'attendance') {
10233:                    $sum+=$pcorrect;
10234:                 } elsif ($correct[$i] eq '*') {
10235:                    $sum+=$pcorrect;
10236:                 } else {
10237: # We actually grade if correct or not
10238:                    my $increment=$pincorrect;
10239: # Special case: numerical answer "0"
10240:                    if ($correct[$i] eq '0') {
10241:                       if ($answer[$i]=~/^[0\.]+$/) {
10242:                          $increment=$pcorrect;
10243:                       }
10244: # General numerical answer, both evaluate to something non-zero
10245:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10246:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10247:                          $increment=$pcorrect;
10248:                       }
10249: # Must be just alphanumeric
10250:                    } elsif ($answer[$i] eq $correct[$i]) {
10251:                       $increment=$pcorrect;
10252:                    }
10253:                    $sum+=$increment;
10254:                 }
10255:              }
10256:           }
10257:           my $ave=$sum/(100*$realnumber);
10258: # Store
10259:           my ($username,$domain)=split(/\:/,$user);
10260:           my %grades=();
10261:           $grades{"resource.$part.solved"}='correct_by_override';
10262:           $grades{"resource.$part.awarded"}=$ave;
10263:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10264:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10265:                                                  $env{'request.course.id'},
10266:                                                  $domain,$username);
10267:           if ($returncode ne 'ok') {
10268:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10269:           } else {
10270:              $storecount++;
10271:           }
10272:        }
10273:     }
10274: # We are done
10275:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10276:              '</td>'.
10277:              &Apache::loncommon::end_data_table_row().
10278:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10279:     return $result.&show_grading_menu_form($symb);
10280: }
10281: 
10282: sub navmap_errormsg {
10283:     return '<div class="LC_error">'.
10284:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10285:            &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>').
10286:            '</div>';
10287: }
10288: 
10289: sub startpage {
10290:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10291:     if ($nomenu) {
10292:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10293:     } else {
10294:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10295:                                                  {'bread_crumbs' => $crumbs}));
10296:     }
10297:     unless ($nodisplayflag) {
10298:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10299:     }
10300: }
10301: 
10302: sub handler {
10303:     my $request=$_[0];
10304:     &reset_caches();
10305:     if ($request->header_only) {
10306:         &Apache::loncommon::content_type($request,'text/html');
10307:         $request->send_http_header;
10308:         return OK;
10309:     }
10310:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10311: 
10312:     my $symb=&get_symb($request,1);
10313:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10314:     my $command=$commands[0];
10315: 
10316:     if ($#commands > 0) {
10317: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10318:     }
10319: 
10320:     $ssi_error = 0;
10321:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10322:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10323:                                                     {'bread_crumbs' => $brcrum});
10324:     if ($symb eq '' && $command eq '') {
10325: 	if ($env{'user.adv'}) {
10326:             &Apache::loncommon::content_type($request,'text/html');
10327:             $request->send_http_header;
10328:             $request->print($start_page);
10329: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10330: 		($env{'form.codethree'})) {
10331: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10332: 		    $env{'form.codethree'};
10333: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10334: 		    &Apache::lonnet::checkin($token);
10335: 		if ($tsymb) {
10336: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10337: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10338: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10339: 					  ('grade_username' => $tuname,
10340: 					   'grade_domain' => $tudom,
10341: 					   'grade_courseid' => $tcrsid,
10342: 					   'grade_symb' => $tsymb)));
10343: 		    } else {
10344: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10345: 		    }
10346: 		} else {
10347: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10348: 		}
10349: 	    } else {
10350: 		$request->print(&Apache::lonxml::tokeninputfield());
10351: 	    }
10352:         } elsif ($env{'request.course.id'}) {
10353:             &init_perm(); 
10354:             if (!%perm) {
10355:                 $request->internal_redirect('/adm/quickgrades');
10356:                 return OK;
10357:             } else {
10358:                 &Apache::loncommon::content_type($request,'text/html');
10359:                 $request->send_http_header;
10360:                 $request->print($start_page);
10361:             }
10362:         }
10363:     } else {
10364:         &init_perm();
10365:         if (!$env{'request.course.id'}) {
10366:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10367:                     ($command =~ /^scantronupload/)) {
10368:                 # Not in a course.
10369:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10370:                 return HTTP_NOT_ACCEPTABLE;
10371:             }
10372:         } elsif (!%perm) {
10373:             $request->internal_redirect('/adm/quickgrades');
10374:         }
10375:         &Apache::loncommon::content_type($request,'text/html');
10376:         $request->send_http_header;
10377:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10378:             $request->print($start_page); 
10379:         }
10380: 	if ($command eq 'submission' && $perm{'vgr'}) {
10381:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10382:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10383:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10384:                     &choose_task_version_form($symb,$env{'form.student'},
10385:                                               $env{'form.userdom'});
10386:             }
10387:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10388:             if ($versionform) {
10389:                 $request->print($versionform);
10390:             }
10391:             $request->print('<br clear="all" />');
10392: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10393:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10394:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10395:                 &choose_task_version_form($symb,$env{'form.student'},
10396:                                           $env{'form.userdom'},
10397:                                           $env{'form.inhibitmenu'});
10398:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10399:             if ($versionform) {
10400:                 $request->print($versionform);
10401:             }
10402:             $request->print('<br clear="all" />');
10403:             $request->print(&show_previous_task_version($request,$symb));
10404: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10405: 	    &pickStudentPage($request);
10406: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10407: 	    &displayPage($request);
10408: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10409: 	    &updateGradeByPage($request);
10410: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10411: 	    &processGroup($request);
10412: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10413: 	    $request->print(&grading_menu($request));
10414: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10415: 	    $request->print(&submit_options($request));
10416: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10417: 	    $request->print(&viewgrades($request));
10418: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10419: 	    $request->print(&processHandGrade($request));
10420: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10421: 	    $request->print(&editgrades($request));
10422: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10423: 	    $request->print(&verifyreceipt($request));
10424:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10425:             $request->print(&process_clicker($request));
10426:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10427:             $request->print(&process_clicker_file($request));
10428:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10429:             $request->print(&assign_clicker_grades($request));
10430: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10431: 	    $request->print(&upcsvScores_form($request));
10432: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10433: 	    $request->print(&csvupload($request));
10434: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10435: 	    $request->print(&csvuploadmap($request));
10436: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10437: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10438: 		$request->print(&csvuploadoptions($request));
10439: 	    } else {
10440: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10441: 		    $env{'form.upfile_associate'} = 'reverse';
10442: 		} else {
10443: 		    $env{'form.upfile_associate'} = 'forward';
10444: 		}
10445: 		$request->print(&csvuploadmap($request));
10446: 	    }
10447: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10448: 	    $request->print(&csvuploadassign($request));
10449: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10450: 	    $request->print(&scantron_selectphase($request));
10451:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10452:  	    $request->print(&scantron_do_warning($request));
10453: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10454: 	    $request->print(&scantron_validate_file($request));
10455: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10456: 	    $request->print(&scantron_process_students($request));
10457:  	} elsif ($command eq 'scantronupload' && 
10458:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10459: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10460:  	    $request->print(&scantron_upload_scantron_data($request)); 
10461:  	} elsif ($command eq 'scantronupload_save' &&
10462:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10463: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10464:  	    $request->print(&scantron_upload_scantron_data_save($request));
10465:  	} elsif ($command eq 'scantron_download' &&
10466: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10467:  	    $request->print(&scantron_download_scantron_data($request));
10468:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10469:             $request->print(&checkscantron_results($request));     
10470: 	} elsif ($command) {
10471: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10472: 	}
10473:     }
10474:     if ($ssi_error) {
10475: 	&ssi_print_error($request);
10476:     }
10477:     $request->print(&Apache::loncommon::end_page());
10478:     &reset_caches();
10479:     return OK;
10480: }
10481: 
10482: 1;
10483: 
10484: __END__;
10485: 
10486: 
10487: =head1 NAME
10488: 
10489: Apache::grades
10490: 
10491: =head1 SYNOPSIS
10492: 
10493: Handles the viewing of grades.
10494: 
10495: This is part of the LearningOnline Network with CAPA project
10496: described at http://www.lon-capa.org.
10497: 
10498: =head1 OVERVIEW
10499: 
10500: Do an ssi with retries:
10501: While I'd love to factor out this with the vesrion in lonprintout,
10502: 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
10503: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10504: 
10505: At least the logic that drives this has been pulled out into loncommon.
10506: 
10507: 
10508: 
10509: ssi_with_retries - Does the server side include of a resource.
10510:                      if the ssi call returns an error we'll retry it up to
10511:                      the number of times requested by the caller.
10512:                      If we still have a proble, no text is appended to the
10513:                      output and we set some global variables.
10514:                      to indicate to the caller an SSI error occurred.  
10515:                      All of this is supposed to deal with the issues described
10516:                      in LonCAPA BZ 5631 see:
10517:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10518:                      by informing the user that this happened.
10519: 
10520: Parameters:
10521:   resource   - The resource to include.  This is passed directly, without
10522:                interpretation to lonnet::ssi.
10523:   form       - The form hash parameters that guide the interpretation of the resource
10524:                
10525:   retries    - Number of retries allowed before giving up completely.
10526: Returns:
10527:   On success, returns the rendered resource identified by the resource parameter.
10528: Side Effects:
10529:   The following global variables can be set:
10530:    ssi_error                - If an unrecoverable error occurred this becomes true.
10531:                               It is up to the caller to initialize this to false
10532:                               if desired.
10533:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10534:                               of the resource that could not be rendered by the ssi
10535:                               call.
10536:    ssi_error_message   - The error string fetched from the ssi response
10537:                               in the event of an error.
10538: 
10539: 
10540: =head1 HANDLER SUBROUTINE
10541: 
10542: ssi_with_retries()
10543: 
10544: =head1 SUBROUTINES
10545: 
10546: =over
10547: 
10548: =item scantron_get_correction() : 
10549: 
10550:    Builds the interface screen to interact with the operator to fix a
10551:    specific error condition in a specific scanline
10552: 
10553:  Arguments:
10554:     $r           - Apache request object
10555:     $i           - number of the current scanline
10556:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10557:     $scan_config - hash ref as returned from &get_scantron_config()
10558:     $line        - full contents of the current scanline
10559:     $error       - error condition, valid values are
10560:                    'incorrectCODE', 'duplicateCODE',
10561:                    'doublebubble', 'missingbubble',
10562:                    'duplicateID', 'incorrectID'
10563:     $arg         - extra information needed
10564:        For errors:
10565:          - duplicateID   - paper number that this studentID was seen before on
10566:          - duplicateCODE - array ref of the paper numbers this CODE was
10567:                            seen on before
10568:          - incorrectCODE - current incorrect CODE 
10569:          - doublebubble  - array ref of the bubble lines that have double
10570:                            bubble errors
10571:          - missingbubble - array ref of the bubble lines that have missing
10572:                            bubble errors
10573: 
10574:    $randomorder - True if exam folder has randomorder set
10575:    $randompick  - True if exam folder has randompick set
10576:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10577:                      for current line to question number used for same question
10578:                      in "Master Seqence" (as seen by Course Coordinator).
10579:    $startline   - Reference to hash where key is question number (0 is first)
10580:                   and value is number of first bubble line for current student
10581:                   or code-based randompick and/or randomorder.
10582: 
10583: 
10584: =item  scantron_get_maxbubble() : 
10585: 
10586:    Arguments:
10587:        $nav_error  - Reference to scalar which is a flag to indicate a
10588:                       failure to retrieve a navmap object.
10589:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10590:        calling routine should trap the error condition and display the warning
10591:        found in &navmap_errormsg().
10592: 
10593:        $scantron_config - Reference to bubblesheet format configuration hash.
10594: 
10595:    Returns the maximum number of bubble lines that are expected to
10596:    occur. Does this by walking the selected sequence rendering the
10597:    resource and then checking &Apache::lonxml::get_problem_counter()
10598:    for what the current value of the problem counter is.
10599: 
10600:    Caches the results to $env{'form.scantron_maxbubble'},
10601:    $env{'form.scantron.bubble_lines.n'}, 
10602:    $env{'form.scantron.first_bubble_line.n'} and
10603:    $env{"form.scantron.sub_bubblelines.n"}
10604:    which are the total number of bubble lines, the number of bubble
10605:    lines for response n and number of the first bubble line for response n,
10606:    and a comma separated list of numbers of bubble lines for sub-questions
10607:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10608: 
10609: 
10610: =item  scantron_validate_missingbubbles() : 
10611: 
10612:    Validates all scanlines in the selected file to not have any
10613:     answers that don't have bubbles that have not been verified
10614:     to be bubble free.
10615: 
10616: =item  scantron_process_students() : 
10617: 
10618:    Routine that does the actual grading of the bubblesheet information.
10619: 
10620:    The parsed scanline hash is added to %env 
10621: 
10622:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10623:    foreach resource , with the form data of
10624: 
10625: 	'submitted'     =>'scantron' 
10626: 	'grade_target'  =>'grade',
10627: 	'grade_username'=> username of student
10628: 	'grade_domain'  => domain of student
10629: 	'grade_courseid'=> of course
10630: 	'grade_symb'    => symb of resource to grade
10631: 
10632:     This triggers a grading pass. The problem grading code takes care
10633:     of converting the bubbled letter information (now in %env) into a
10634:     valid submission.
10635: 
10636: =item  scantron_upload_scantron_data() :
10637: 
10638:     Creates the screen for adding a new bubblesheet data file to a course.
10639: 
10640: =item  scantron_upload_scantron_data_save() : 
10641: 
10642:    Adds a provided bubble information data file to the course if user
10643:    has the correct privileges to do so. 
10644: 
10645: =item  valid_file() :
10646: 
10647:    Validates that the requested bubble data file exists in the course.
10648: 
10649: =item  scantron_download_scantron_data() : 
10650: 
10651:    Shows a list of the three internal files (original, corrected,
10652:    skipped) for a specific bubblesheet data file that exists in the
10653:    course.
10654: 
10655: =item  scantron_validate_ID() : 
10656: 
10657:    Validates all scanlines in the selected file to not have any
10658:    invalid or underspecified student/employee IDs
10659: 
10660: =item navmap_errormsg() :
10661: 
10662:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10663:    Should be called whenever the request to instantiate a navmap object fails.  
10664: 
10665: =back
10666: 
10667: =cut

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