File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.45: download - view: text, annotated - select for diffs
Sat Feb 16 17:53:05 2019 UTC (5 years, 2 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  - Backport 1.753

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.45 2019/02/16 17:53:05 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 Apache::lontexconvert();
   48: use String::Similarity;
   49: use LONCAPA;
   50: 
   51: use POSIX qw(floor);
   52: 
   53: 
   54: 
   55: my %perm=();
   56: my %old_essays=();
   57: 
   58: #  These variables are used to recover from ssi errors
   59: 
   60: my $ssi_retries = 5;
   61: my $ssi_error;
   62: my $ssi_error_resource;
   63: my $ssi_error_message;
   64: 
   65: 
   66: sub ssi_with_retries {
   67:     my ($resource, $retries, %form) = @_;
   68:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   69:     if ($response->is_error) {
   70: 	$ssi_error          = 1;
   71: 	$ssi_error_resource = $resource;
   72: 	$ssi_error_message  = $response->code . " " . $response->message;
   73:     }
   74: 
   75:     return $content;
   76: 
   77: }
   78: #
   79: #  Prodcuces an ssi retry failure error message to the user:
   80: #
   81: 
   82: sub ssi_print_error {
   83:     my ($r) = @_;
   84:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   85:     $r->print('
   86: <br />
   87: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   88: <p>
   89: '.&mt('Unable to retrieve a resource from a server:').'<br />
   90: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   91: '.&mt('Error:').' '.$ssi_error_message.'
   92: </p>
   93: <p>'.
   94: &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 />'.
   95: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   96: '</p>');
   97:     return;
   98: }
   99: 
  100: #
  101: # --- Retrieve the parts from the metadata file.---
  102: sub getpartlist {
  103:     my ($symb,$errorref) = @_;
  104: 
  105:     my $navmap   = Apache::lonnavmaps::navmap->new();
  106:     unless (ref($navmap)) {
  107:         if (ref($errorref)) { 
  108:             $$errorref = 'navmap';
  109:             return;
  110:         }
  111:     }
  112:     my $res      = $navmap->getBySymb($symb);
  113:     my $partlist = $res->parts();
  114:     my $url      = $res->src();
  115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  116: 
  117:     my @stores;
  118:     foreach my $part (@{ $partlist }) {
  119: 	foreach my $key (@metakeys) {
  120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  121: 	}
  122:     }
  123:     return @stores;
  124: }
  125: 
  126: # --- Get the symbolic name of a problem and the url
  127: sub get_symb {
  128:     my ($request,$silent) = @_;
  129:     my $symb=$env{'form.symb'};
  130:     unless ($symb) {
  131:         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  132:         $symb = &Apache::lonnet::symbread($url);
  133:         if ($symb eq '') { 
  134: 	    if (!$silent) {
  135:                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  136: 	        return ();
  137: 	    }
  138:         }
  139:     }
  140:     &Apache::lonenc::check_decrypt(\$symb);
  141:     return ($symb);
  142: }
  143: 
  144: #--- Format fullname, username:domain if different for display
  145: #--- Use anywhere where the student names are listed
  146: sub nameUserString {
  147:     my ($type,$fullname,$uname,$udom) = @_;
  148:     if ($type eq 'header') {
  149: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  150:     } else {
  151: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  152: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  153:     }
  154: }
  155: 
  156: #--- Get the partlist and the response type for a given problem. ---
  157: #--- Indicate if a response type is coded handgraded or not. ---
  158: sub response_type {
  159:     my ($symb,$response_error) = @_;
  160: 
  161:     my $navmap = Apache::lonnavmaps::navmap->new();
  162:     unless (ref($navmap)) {
  163:         if (ref($response_error)) {
  164:             $$response_error = 1;
  165:         }
  166:         return;
  167:     }
  168:     my $res = $navmap->getBySymb($symb);
  169:     unless (ref($res)) {
  170:         $$response_error = 1;
  171:         return;
  172:     }
  173:     my $partlist = $res->parts();
  174:     my %vPart = 
  175: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  176:     my (%response_types,%handgrade);
  177:     foreach my $part (@{ $partlist }) {
  178: 	next if (%vPart && !exists($vPart{$part}));
  179: 
  180: 	my @types = $res->responseType($part);
  181: 	my @ids = $res->responseIds($part);
  182: 	for (my $i=0; $i < scalar(@ids); $i++) {
  183: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  184: 	    $handgrade{$part.'_'.$ids[$i]} = 
  185: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  186: 				     '.handgrade',$symb);
  187: 	}
  188:     }
  189:     return ($partlist,\%handgrade,\%response_types);
  190: }
  191: 
  192: sub flatten_responseType {
  193:     my ($responseType) = @_;
  194:     my @part_response_id =
  195: 	map { 
  196: 	    my $part = $_;
  197: 	    map {
  198: 		[$part,$_]
  199: 		} sort(keys(%{ $responseType->{$part} }));
  200: 	} sort(keys(%$responseType));
  201:     return @part_response_id;
  202: }
  203: 
  204: sub get_display_part {
  205:     my ($partID,$symb)=@_;
  206:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  207:     if (defined($display) and $display ne '') {
  208:         $display.= ' (<span class="LC_internal_info">'
  209:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  210:     } else {
  211: 	$display=$partID;
  212:     }
  213:     return $display;
  214: }
  215: 
  216: #--- Show resource title
  217: #--- and parts and response type
  218: sub showResourceInfo {
  219:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  220:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  221:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  222:     if (ref($res_error)) {
  223:         if ($$res_error) {
  224:             return;
  225:         }
  226:     }
  227:     $result.=&Apache::loncommon::start_data_table()
  228:             .&Apache::loncommon::start_data_table_header_row();
  229:     if ($checkboxes) {
  230:         $result.='<th>&nbsp;</th>';
  231:     }
  232:     $result.='<th>'.&mt('Problem Part').'</th>'
  233:             .'<th>'.&mt('Res. ID').'</th>'
  234:             .'<th>'.&mt('Type').'</th>'
  235:             .&Apache::loncommon::end_data_table_header_row();
  236:     my %resptype = ();
  237:     my $hdgrade='no';
  238:     my %partsseen;
  239:     foreach my $partID (sort(keys(%$responseType))) {
  240:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  241:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  242:             my $responsetype = $responseType->{$partID}->{$resID};
  243:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  244:             $result.=&Apache::loncommon::start_data_table_row();
  245:             if ($checkboxes) {
  246:                 if (exists($partsseen{$partID})) {
  247:                     $result.="<td>&nbsp;</td>";
  248:                 } else {
  249:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  250:                 }
  251:                 $partsseen{$partID}=1;
  252:             }
  253:             my $display_part=&get_display_part($partID,$symb);
  254:             $result.='<td>'.$display_part.'</td>'
  255:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  256:                     .'<td>'.&mt($responsetype).'</td>'
  257: #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
  258:                     .&Apache::loncommon::end_data_table_row();
  259:         }
  260:     }
  261:     $result.=&Apache::loncommon::end_data_table();
  262:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  263: }
  264: 
  265: sub reset_caches {
  266:     &reset_analyze_cache();
  267:     &reset_perm();
  268:     &reset_old_essays();
  269: }
  270: 
  271: {
  272:     my %analyze_cache;
  273:     my %analyze_cache_formkeys;
  274: 
  275:     sub reset_analyze_cache {
  276: 	undef(%analyze_cache);
  277:         undef(%analyze_cache_formkeys);
  278:     }
  279: 
  280:     sub get_analyze {
  281: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  282: 	my $key = "$symb\0$uname\0$udom";
  283:         if ($type eq 'randomizetry') {
  284:             if ($trial ne '') {
  285:                 $key .= "\0".$trial;
  286:             }
  287:         }
  288: 	if (exists($analyze_cache{$key})) {
  289:             my $getupdate = 0;
  290:             if (ref($add_to_hash) eq 'HASH') {
  291:                 foreach my $item (keys(%{$add_to_hash})) {
  292:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  293:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  294:                             $getupdate = 1;
  295:                             last;
  296:                         }
  297:                     } else {
  298:                         $getupdate = 1;
  299:                     }
  300:                 }
  301:             }
  302:             if (!$getupdate) {
  303:                 return $analyze_cache{$key};
  304:             }
  305:         }
  306: 
  307: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  308: 	$url=&Apache::lonnet::clutter($url);
  309:         my %form = ('grade_target'      => 'analyze',
  310:                     'grade_domain'      => $udom,
  311:                     'grade_symb'        => $symb,
  312:                     'grade_courseid'    =>  $env{'request.course.id'},
  313:                     'grade_username'    => $uname,
  314:                     'grade_noincrement' => $no_increment);
  315:         if ($bubbles_per_row ne '') {
  316:             $form{'bubbles_per_row'} = $bubbles_per_row;
  317:         }
  318:         if ($type eq 'randomizetry') {
  319:             $form{'grade_questiontype'} = $type;
  320:             if ($rndseed ne '') {
  321:                 $form{'grade_rndseed'} = $rndseed;
  322:             }
  323:         }
  324:         if (ref($add_to_hash)) {
  325:             %form = (%form,%{$add_to_hash});
  326:         }
  327: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  328: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  329: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  330:         if (ref($add_to_hash) eq 'HASH') {
  331:             $analyze_cache_formkeys{$key} = $add_to_hash;
  332:         } else {
  333:             $analyze_cache_formkeys{$key} = {};
  334:         }
  335: 	return $analyze_cache{$key} = \%analyze;
  336:     }
  337: 
  338:     sub get_order {
  339: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  340: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  341: 	return $analyze->{"$partid.$respid.shown"};
  342:     }
  343: 
  344:     sub get_radiobutton_correct_foil {
  345: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  346: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  347:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  348:         if (ref($foils) eq 'ARRAY') {
  349: 	    foreach my $foil (@{$foils}) {
  350: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  351: 		    return $foil;
  352: 	        }
  353: 	    }
  354: 	}
  355:     }
  356: 
  357:     sub scantron_partids_tograde {
  358:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  359:         my (%analysis,@parts);
  360:         if (ref($resource)) {
  361:             my $symb = $resource->symb();
  362:             my $add_to_form;
  363:             if ($check_for_randomlist) {
  364:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  365:             }
  366:             if ($scancode) {
  367:                 if (ref($add_to_form) eq 'HASH') {
  368:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  369:                 } else {
  370:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  371:                 }
  372:             }
  373:             my $analyze =
  374:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  375:                              undef,undef,undef,$bubbles_per_row);
  376:             if (ref($analyze) eq 'HASH') {
  377:                 %analysis = %{$analyze};
  378:             }
  379:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  380:                 foreach my $part (@{$analysis{'parts'}}) {
  381:                     my ($id,$respid) = split(/\./,$part);
  382:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  383:                         push(@parts,$part);
  384:                     }
  385:                 }
  386:             }
  387:         }
  388:         return (\%analysis,\@parts);
  389:     }
  390: 
  391: }
  392: 
  393: #--- Clean response type for display
  394: #--- Currently filters option/rank/radiobutton/match/essay/Task
  395: #        response types only.
  396: sub cleanRecord {
  397:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  398: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  399:     my $grayFont = '<span class="LC_internal_info">';
  400:     if ($response =~ /^(option|rank)$/) {
  401: 	my %answer=&Apache::lonnet::str2hash($answer);
  402:         my @answer = %answer;
  403:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  404: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  405: 	my ($toprow,$bottomrow);
  406: 	foreach my $foil (@$order) {
  407: 	    if ($grading{$foil} == 1) {
  408: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  409: 	    } else {
  410: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  411: 	    }
  412: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  413: 	}
  414: 	return '<blockquote><table border="1">'.
  415: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  416: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  417: 	    $bottomrow.'</tr></table></blockquote>';
  418:     } elsif ($response eq 'match') {
  419: 	my %answer=&Apache::lonnet::str2hash($answer);
  420:         my @answer = %answer;
  421:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  422: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  423: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  424: 	my ($toprow,$middlerow,$bottomrow);
  425: 	foreach my $foil (@$order) {
  426: 	    my $item=shift(@items);
  427: 	    if ($grading{$foil} == 1) {
  428: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  429: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  430: 	    } else {
  431: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  432: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  433: 	    }
  434: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  435: 	}
  436: 	return '<blockquote><table border="1">'.
  437: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  438: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  439: 	    $middlerow.'</tr>'.
  440: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  441: 	    $bottomrow.'</tr></table></blockquote>';
  442:     } elsif ($response eq 'radiobutton') {
  443: 	my %answer=&Apache::lonnet::str2hash($answer);
  444: 	my ($toprow,$bottomrow);
  445: 	my $correct = 
  446: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  447: 	foreach my $foil (@$order) {
  448: 	    if (exists($answer{$foil})) {
  449: 		if ($foil eq $correct) {
  450: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  451: 		} else {
  452: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  453: 		}
  454: 	    } else {
  455: 		$toprow.='<td>'.&mt('false').'</td>';
  456: 	    }
  457: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  458: 	}
  459: 	return '<blockquote><table border="1">'.
  460: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  461: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  462: 	    $bottomrow.'</tr></table></blockquote>';
  463:     } elsif ($response eq 'essay') {
  464: 	if (! exists ($env{'form.'.$symb})) {
  465: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  466: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  467: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  468: 
  469: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  470: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  471: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  472: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  473: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  474: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  475: 	}
  476:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  477: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  478:     } elsif ( $response eq 'organic') {
  479:         my $result=&mt('Smile representation: [_1]',
  480:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  481: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  482: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  483: 	return $result;
  484:     } elsif ( $response eq 'Task') {
  485: 	if ( $answer eq 'SUBMITTED') {
  486: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  487: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  488: 	    return $result;
  489: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  490: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  491: 			       keys(%{$record}));
  492: 	    return join('<br />',($version,@matches));
  493: 			       
  494: 			       
  495: 	} else {
  496: 	    my $result =
  497: 		'<p>'
  498: 		.&mt('Overall result: [_1]',
  499: 		     $record->{$version."resource.$respid.$partid.status"})
  500: 		.'</p>';
  501: 	    
  502: 	    $result .= '<ul>';
  503: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  504: 			     keys(%{$record}));
  505: 	    foreach my $grade (sort(@grade)) {
  506: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  507: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  508: 				     $dim, $record->{$grade}).
  509: 			  '</li>';
  510: 	    }
  511: 	    $result.='</ul>';
  512: 	    return $result;
  513: 	}
  514:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  515:         # Respect multiple input fields, see Bug #5409 
  516: 	$answer = 
  517: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  518: 							      $answer);
  519:         return $answer;
  520:     }
  521:     return &HTML::Entities::encode($answer, '"<>&');
  522: }
  523: 
  524: #-- A couple of common js functions
  525: sub commonJSfunctions {
  526:     my $request = shift;
  527:     $request->print(<<COMMONJSFUNCTIONS);
  528: <script type="text/javascript" language="javascript">
  529:     function radioSelection(radioButton) {
  530: 	var selection=null;
  531: 	if (radioButton.length > 1) {
  532: 	    for (var i=0; i<radioButton.length; i++) {
  533: 		if (radioButton[i].checked) {
  534: 		    return radioButton[i].value;
  535: 		}
  536: 	    }
  537: 	} else {
  538: 	    if (radioButton.checked) return radioButton.value;
  539: 	}
  540: 	return selection;
  541:     }
  542: 
  543:     function pullDownSelection(selectOne) {
  544: 	var selection="";
  545: 	if (selectOne.length > 1) {
  546: 	    for (var i=0; i<selectOne.length; i++) {
  547: 		if (selectOne[i].selected) {
  548: 		    return selectOne[i].value;
  549: 		}
  550: 	    }
  551: 	} else {
  552:             // only one value it must be the selected one
  553: 	    return selectOne.value;
  554: 	}
  555:     }
  556: </script>
  557: COMMONJSFUNCTIONS
  558: }
  559: 
  560: #--- Dumps the class list with usernames,list of sections,
  561: #--- section, ids and fullnames for each user.
  562: sub getclasslist {
  563:     my ($getsec,$filterlist,$getgroup) = @_;
  564:     my @getsec;
  565:     my @getgroup;
  566:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  567:     if (!ref($getsec)) {
  568: 	if ($getsec ne '' && $getsec ne 'all') {
  569: 	    @getsec=($getsec);
  570: 	}
  571:     } else {
  572: 	@getsec=@{$getsec};
  573:     }
  574:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  575:     if (!ref($getgroup)) {
  576: 	if ($getgroup ne '' && $getgroup ne 'all') {
  577: 	    @getgroup=($getgroup);
  578: 	}
  579:     } else {
  580: 	@getgroup=@{$getgroup};
  581:     }
  582:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  583: 
  584:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  585:     # Bail out if we were unable to get the classlist
  586:     return if (! defined($classlist));
  587:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  588:     #
  589:     my %sections;
  590:     my %fullnames;
  591:     foreach my $student (keys(%$classlist)) {
  592:         my $end      = 
  593:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  594:         my $start    = 
  595:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  596:         my $id       = 
  597:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  598:         my $section  = 
  599:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  600:         my $fullname = 
  601:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  602:         my $status   = 
  603:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  604:         my $group   = 
  605:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  606: 	# filter students according to status selected
  607: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  608: 	    if (!($stu_status =~ $status)) {
  609: 		delete($classlist->{$student});
  610: 		next;
  611: 	    }
  612: 	}
  613: 	# filter students according to groups selected
  614: 	my @stu_groups = split(/,/,$group);
  615: 	if (@getgroup) {
  616: 	    my $exclude = 1;
  617: 	    foreach my $grp (@getgroup) {
  618: 	        foreach my $stu_group (@stu_groups) {
  619: 	            if ($stu_group eq $grp) {
  620: 	                $exclude = 0;
  621:     	            } 
  622: 	        }
  623:     	        if (($grp eq 'none') && !$group) {
  624:         	        $exclude = 0;
  625:         	}
  626: 	    }
  627: 	    if ($exclude) {
  628: 	        delete($classlist->{$student});
  629: 	    }
  630: 	}
  631: 	$section = ($section ne '' ? $section : 'none');
  632: 	if (&canview($section)) {
  633: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  634: 		$sections{$section}++;
  635: 		if ($classlist->{$student}) {
  636: 		    $fullnames{$student}=$fullname;
  637: 		}
  638: 	    } else {
  639: 		delete($classlist->{$student});
  640: 	    }
  641: 	} else {
  642: 	    delete($classlist->{$student});
  643: 	}
  644:     }
  645:     my %seen = ();
  646:     my @sections = sort(keys(%sections));
  647:     return ($classlist,\@sections,\%fullnames);
  648: }
  649: 
  650: sub canmodify {
  651:     my ($sec)=@_;
  652:     if ($perm{'mgr'}) {
  653: 	if (!defined($perm{'mgr_section'})) {
  654: 	    # can modify whole class
  655: 	    return 1;
  656: 	} else {
  657: 	    if ($sec eq $perm{'mgr_section'}) {
  658: 		#can modify the requested section
  659: 		return 1;
  660: 	    } else {
  661: 		# can't modify the request section
  662: 		return 0;
  663: 	    }
  664: 	}
  665:     }
  666:     #can't modify
  667:     return 0;
  668: }
  669: 
  670: sub canview {
  671:     my ($sec)=@_;
  672:     if ($perm{'vgr'}) {
  673: 	if (!defined($perm{'vgr_section'})) {
  674: 	    # can modify whole class
  675: 	    return 1;
  676: 	} else {
  677: 	    if ($sec eq $perm{'vgr_section'}) {
  678: 		#can modify the requested section
  679: 		return 1;
  680: 	    } else {
  681: 		# can't modify the request section
  682: 		return 0;
  683: 	    }
  684: 	}
  685:     }
  686:     #can't modify
  687:     return 0;
  688: }
  689: 
  690: #--- Retrieve the grade status of a student for all the parts
  691: sub student_gradeStatus {
  692:     my ($symb,$udom,$uname,$partlist) = @_;
  693:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  694:     my %partstatus = ();
  695:     foreach (@$partlist) {
  696: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  697: 	$status              = 'nothing' if ($status eq '');
  698: 	$partstatus{$_}      = $status;
  699: 	my $subkey           = "resource.$_.submitted_by";
  700: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  701:     }
  702:     return %partstatus;
  703: }
  704: 
  705: # hidden form and javascript that calls the form
  706: # Use by verifyscript and viewgrades
  707: # Shows a student's view of problem and submission
  708: sub jscriptNform {
  709:     my ($symb) = @_;
  710:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  711:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  712: 	'    function viewOneStudent(user,domain) {'."\n".
  713: 	'	document.onestudent.student.value = user;'."\n".
  714: 	'	document.onestudent.userdom.value = domain;'."\n".
  715: 	'	document.onestudent.submit();'."\n".
  716: 	'    }'."\n".
  717: 	'</script>'."\n";
  718:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  719: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  720: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  721: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  722: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  723: 	'<input type="hidden" name="command" value="submission" />'."\n".
  724: 	'<input type="hidden" name="student" value="" />'."\n".
  725: 	'<input type="hidden" name="userdom" value="" />'."\n".
  726: 	'</form>'."\n";
  727:     return $jscript;
  728: }
  729: 
  730: 
  731: 
  732: # Given the score (as a number [0-1] and the weight) what is the final
  733: # point value? This function will round to the nearest tenth, third,
  734: # or quarter if one of those is within the tolerance of .00001.
  735: sub compute_points {
  736:     my ($score, $weight) = @_;
  737:     
  738:     my $tolerance = .00001;
  739:     my $points = $score * $weight;
  740: 
  741:     # Check for nearness to 1/x.
  742:     my $check_for_nearness = sub {
  743:         my ($factor) = @_;
  744:         my $num = ($points * $factor) + $tolerance;
  745:         my $floored_num = floor($num);
  746:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  747:             return $floored_num / $factor;
  748:         }
  749:         return $points;
  750:     };
  751: 
  752:     $points = $check_for_nearness->(10);
  753:     $points = $check_for_nearness->(3);
  754:     $points = $check_for_nearness->(4);
  755:     
  756:     return $points;
  757: }
  758: 
  759: #------------------ End of general use routines --------------------
  760: 
  761: #
  762: # Find most similar essay
  763: #
  764: 
  765: sub most_similar {
  766:     my ($uname,$udom,$symb,$uessay)=@_;
  767: 
  768:     unless ($symb) { return ''; }
  769: 
  770:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  771: 
  772: # ignore spaces and punctuation
  773: 
  774:     $uessay=~s/\W+/ /gs;
  775: 
  776: # ignore empty submissions (occuring when only files are sent)
  777: 
  778:     unless ($uessay=~/\w+/s) { return ''; }
  779: 
  780: # these will be returned. Do not care if not at least 50 percent similar
  781:     my $limit=0.6;
  782:     my $sname='';
  783:     my $sdom='';
  784:     my $scrsid='';
  785:     my $sessay='';
  786: # go through all essays ...
  787:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  788: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  789: # ... except the same student
  790:         next if (($tname eq $uname) && ($tdom eq $udom));
  791: 	my $tessay=$old_essays{$symb}{$tkey};
  792: 	$tessay=~s/\W+/ /gs;
  793: # String similarity gives up if not even limit
  794: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  795: # Found one
  796: 	if ($tsimilar>$limit) {
  797: 	    $limit=$tsimilar;
  798: 	    $sname=$tname;
  799: 	    $sdom=$tdom;
  800: 	    $scrsid=$tcrsid;
  801: 	    $sessay=$old_essays{$symb}{$tkey};
  802: 	}
  803:     }
  804:     if ($limit>0.6) {
  805:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  806:     } else {
  807:        return ('','','','',0);
  808:     }
  809: }
  810: 
  811: #-------------------------------------------------------------------
  812: 
  813: #------------------------------------ Receipt Verification Routines
  814: #
  815: #--- Check whether a receipt number is valid.---
  816: sub verifyreceipt {
  817:     my $request  = shift;
  818: 
  819:     my $courseid = $env{'request.course.id'};
  820:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  821: 	$env{'form.receipt'};
  822:     $receipt     =~ s/[^\-\d]//g;
  823:     my ($symb)   = &get_symb($request);
  824: 
  825:     my $title.=
  826: 	'<h3><span class="LC_info">'.
  827: 	&mt('Verifying Receipt No. [_1]',$receipt).
  828: 	'</span></h3>'."\n".
  829: 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
  830: 	'</h4>'."\n";
  831: 
  832:     my ($string,$contents,$matches) = ('','',0);
  833:     my (undef,undef,$fullname) = &getclasslist('all','0');
  834:     
  835:     my $receiptparts=0;
  836:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  837: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  838:     my $parts=['0'];
  839:     if ($receiptparts) {
  840:         my $res_error; 
  841:         ($parts)=&response_type($symb,\$res_error);
  842:         if ($res_error) {
  843:             return &navmap_errormsg();
  844:         } 
  845:     }
  846:     
  847:     my $header = 
  848: 	&Apache::loncommon::start_data_table().
  849: 	&Apache::loncommon::start_data_table_header_row().
  850: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  851: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  852: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  853:     if ($receiptparts) {
  854: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  855:     }
  856:     $header.=
  857: 	&Apache::loncommon::end_data_table_header_row();
  858: 
  859:     foreach (sort 
  860: 	     {
  861: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  862: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  863: 		 }
  864: 		 return $a cmp $b;
  865: 	     } (keys(%$fullname))) {
  866: 	my ($uname,$udom)=split(/\:/);
  867: 	foreach my $part (@$parts) {
  868: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  869: 		$contents.=
  870: 		    &Apache::loncommon::start_data_table_row().
  871: 		    '<td>&nbsp;'."\n".
  872: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  873: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  874: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  875: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  876: 		if ($receiptparts) {
  877: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  878: 		}
  879: 		$contents.= 
  880: 		    &Apache::loncommon::end_data_table_row()."\n";
  881: 		
  882: 		$matches++;
  883: 	    }
  884: 	}
  885:     }
  886:     if ($matches == 0) {
  887:         $string = $title
  888:                  .'<p class="LC_warning">'
  889:                  .&mt('No match found for the above receipt number.')
  890:                  .'</p>';
  891:     } else {
  892: 	$string = &jscriptNform($symb).$title.
  893: 	    '<p>'.
  894: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  895: 	    '</p>'.
  896: 	    $header.
  897: 	    $contents.
  898: 	    &Apache::loncommon::end_data_table()."\n";
  899:     }
  900:     return $string.&show_grading_menu_form($symb);
  901: }
  902: 
  903: #--- This is called by a number of programs.
  904: #--- Called from the Grading Menu - View/Grade an individual student
  905: #--- Also called directly when one clicks on the subm button 
  906: #    on the problem page.
  907: sub listStudents {
  908:     my ($request) = shift;
  909: 
  910:     my ($symb) = &get_symb($request);
  911:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  912:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  913:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  914:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  915:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  916:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  917:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  918: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  919: 
  920:     my $result='<h3><span class="LC_info">&nbsp;'
  921: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  922: 	.'</span></h3>';
  923: 
  924:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  925: 
  926:     my %js_lt = &Apache::lonlocal::texthash (
  927: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  928: 		'single'   => 'Please select the student before clicking on the Next button.',
  929: 	     );
  930:     &js_escape(\%js_lt);
  931:     $request->print(<<LISTJAVASCRIPT);
  932: <script type="text/javascript" language="javascript">
  933:     function checkSelect(checkBox) {
  934: 	var ctr=0;
  935: 	var sense="";
  936: 	if (checkBox.length > 1) {
  937: 	    for (var i=0; i<checkBox.length; i++) {
  938: 		if (checkBox[i].checked) {
  939: 		    ctr++;
  940: 		}
  941: 	    }
  942: 	    sense = '$js_lt{'multiple'}';
  943: 	} else {
  944: 	    if (checkBox.checked) {
  945: 		ctr = 1;
  946: 	    }
  947: 	    sense = '$js_lt{'single'}';
  948: 	}
  949: 	if (ctr == 0) {
  950: 	    alert(sense);
  951: 	    return false;
  952: 	}
  953: 	document.gradesub.submit();
  954:     }
  955: 
  956:     function reLoadList(formname) {
  957: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  958: 	formname.command.value = 'submission';
  959: 	formname.submit();
  960:     }
  961: </script>
  962: LISTJAVASCRIPT
  963: 
  964:     &commonJSfunctions($request);
  965:     $request->print($result);
  966: 
  967:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  968:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  969:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  970: 	"\n".$table;
  971: 	
  972:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  973:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  974:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  975:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  976:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  977:                   .&Apache::lonhtmlcommon::row_closure();
  978:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  979:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  980:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  981:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  982:                   .&Apache::lonhtmlcommon::row_closure();
  983: 
  984:     my $submission_options;
  985:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  986: 	$submission_options.=
  987: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  988:     }
  989:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  990:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  991:     $env{'form.Status'} = $saveStatus;
  992:     $submission_options.=
  993:         '<span class="LC_nobreak">'.
  994:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  995:         &mt('last submission only').' </label></span>'."\n".
  996:         '<span class="LC_nobreak">'.
  997:         '<label><input type="radio" name="lastSub" value="last" /> '.
  998:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  999:         '<span class="LC_nobreak">'.
 1000:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
 1001:         &mt('by dates and submissions').'</label></span>'."\n".
 1002:         '<span class="LC_nobreak">'.
 1003:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1004:         &mt('all details').'</label></span>';
 1005:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
 1006:                   .$submission_options
 1007:                   .&Apache::lonhtmlcommon::row_closure();
 1008: 
 1009:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1010:                   .'<select name="increment">'
 1011:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1012:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1013:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1014:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1015:                   .'</select>'
 1016:                   .&Apache::lonhtmlcommon::row_closure();
 1017: 
 1018:     $gradeTable .= 
 1019:         &build_section_inputs().
 1020: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1021: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1022: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1023: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1024: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1025: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1026: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1027: 
 1028:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1029: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1030:     } else {
 1031:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1032:                       .&Apache::lonhtmlcommon::StatusOptions(
 1033:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1034:                       .&Apache::lonhtmlcommon::row_closure();
 1035:     }
 1036: 
 1037:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1038:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1039:                   .&Apache::lonhtmlcommon::row_closure(1)
 1040:                   .&Apache::lonhtmlcommon::end_pick_box();
 1041: 
 1042:     $gradeTable .= '<p>'
 1043:                   .&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"
 1044:                   .'<input type="hidden" name="command" value="processGroup" />'
 1045:                   .'</p>';
 1046: 
 1047: # checkall buttons
 1048:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1049:     $gradeTable.='<input type="button" '."\n".
 1050:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1051:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1052:     $gradeTable.=&check_buttons();
 1053:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1054:     $gradeTable.= &Apache::loncommon::start_data_table().
 1055: 	&Apache::loncommon::start_data_table_header_row();
 1056:     my $loop = 0;
 1057:     while ($loop < 2) {
 1058: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1059: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1060: 	if ($env{'form.showgrading'} eq 'yes' 
 1061: 	    && $submitonly ne 'queued'
 1062: 	    && $submitonly ne 'all') {
 1063: 	    foreach my $part (sort(@$partlist)) {
 1064: 		my $display_part=
 1065: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1066: 		$gradeTable.=
 1067: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1068: 	    }
 1069: 	} elsif ($submitonly eq 'queued') {
 1070: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1071: 	}
 1072: 	$loop++;
 1073: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1074:     }
 1075:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1076: 
 1077:     my $ctr = 0;
 1078:     foreach my $student (sort 
 1079: 			 {
 1080: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1081: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1082: 			     }
 1083: 			     return $a cmp $b;
 1084: 			 }
 1085: 			 (keys(%$fullname))) {
 1086: 	my ($uname,$udom) = split(/:/,$student);
 1087: 
 1088: 	my %status = ();
 1089: 
 1090: 	if ($submitonly eq 'queued') {
 1091: 	    my %queue_status = 
 1092: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1093: 							$udom,$uname);
 1094: 	    next if (!defined($queue_status{'gradingqueue'}));
 1095: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1096: 	}
 1097: 
 1098: 	if ($env{'form.showgrading'} eq 'yes' 
 1099: 	    && $submitonly ne 'queued'
 1100: 	    && $submitonly ne 'all') {
 1101: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1102: 	    my $submitted = 0;
 1103: 	    my $graded = 0;
 1104: 	    my $incorrect = 0;
 1105: 	    foreach (keys(%status)) {
 1106: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1107: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1108: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1109: 		
 1110: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1111: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1112: 		    $submitted = 0;
 1113: 		    my ($part)=split(/\./,$partid);
 1114: 		    $gradeTable.='<input type="hidden" name="'.
 1115: 			$student.':'.$part.':submitted_by" value="'.
 1116: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1117: 		}
 1118: 	    }
 1119: 	    
 1120: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1121: 				     $submitonly eq 'incorrect' ||
 1122: 				     $submitonly eq 'graded'));
 1123: 	    next if (!$graded && ($submitonly eq 'graded'));
 1124: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1125: 	}
 1126: 
 1127: 	$ctr++;
 1128: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1129:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1130: 	if ( $perm{'vgr'} eq 'F' ) {
 1131: 	    if ($ctr%2 ==1) {
 1132: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1133: 	    }
 1134: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1135:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1136:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1137: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1138: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1139: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1140: 
 1141: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1142: 		foreach (sort(keys(%status))) {
 1143: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1144: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1145: 		}
 1146: 	    }
 1147: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1148: 	    if ($ctr%2 ==0) {
 1149: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1150: 	    }
 1151: 	}
 1152:     }
 1153:     if ($ctr%2 ==1) {
 1154: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1155: 	    if ($env{'form.showgrading'} eq 'yes' 
 1156: 		&& $submitonly ne 'queued'
 1157: 		&& $submitonly ne 'all') {
 1158: 		foreach (@$partlist) {
 1159: 		    $gradeTable.='<td>&nbsp;</td>';
 1160: 		}
 1161: 	    } elsif ($submitonly eq 'queued') {
 1162: 		$gradeTable.='<td>&nbsp;</td>';
 1163: 	    }
 1164: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1165:     }
 1166: 
 1167:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1168:         '<input type="button" '.
 1169:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1170:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1171:     if ($ctr == 0) {
 1172: 	my $num_students=(scalar(keys(%$fullname)));
 1173: 	if ($num_students eq 0) {
 1174: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1175: 	} else {
 1176: 	    my $submissions='submissions';
 1177: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1178: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1179: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1180: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1181: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1182: 		    $num_students).
 1183: 		'</span><br />';
 1184: 	}
 1185:     } elsif ($ctr == 1) {
 1186: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1187:     }
 1188:     $gradeTable.=&show_grading_menu_form($symb);
 1189:     $request->print($gradeTable);
 1190:     return '';
 1191: }
 1192: 
 1193: #---- Called from the listStudents routine
 1194: 
 1195: sub check_script {
 1196:     my ($form, $type)=@_;
 1197:     my $chkallscript='<script type="text/javascript">
 1198:     function checkall() {
 1199:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1200:             ele = document.forms.'.$form.'.elements[i];
 1201:             if (ele.name == "'.$type.'") {
 1202:             document.forms.'.$form.'.elements[i].checked=true;
 1203:                                        }
 1204:         }
 1205:     }
 1206: 
 1207:     function checksec() {
 1208:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1209:             ele = document.forms.'.$form.'.elements[i];
 1210:            string = document.forms.'.$form.'.chksec.value;
 1211:            if
 1212:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1213:               document.forms.'.$form.'.elements[i].checked=true;
 1214:             }
 1215:         }
 1216:     }
 1217: 
 1218: 
 1219:     function uncheckall() {
 1220:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1221:             ele = document.forms.'.$form.'.elements[i];
 1222:             if (ele.name == "'.$type.'") {
 1223:             document.forms.'.$form.'.elements[i].checked=false;
 1224:                                        }
 1225:         }
 1226:     }
 1227: 
 1228: </script>'."\n";
 1229:     return $chkallscript;
 1230: }
 1231: 
 1232: sub check_buttons {
 1233:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1234:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1235:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1236:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1237:     return $buttons;
 1238: }
 1239: 
 1240: #     Displays the submissions for one student or a group of students
 1241: sub processGroup {
 1242:     my ($request)  = shift;
 1243:     my $ctr        = 0;
 1244:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1245:     my $total      = scalar(@stuchecked)-1;
 1246: 
 1247:     foreach my $student (@stuchecked) {
 1248: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1249: 	$env{'form.student'}        = $uname;
 1250: 	$env{'form.userdom'}        = $udom;
 1251: 	$env{'form.fullname'}       = $fullname;
 1252: 	&submission($request,$ctr,$total);
 1253: 	$ctr++;
 1254:     }
 1255:     return '';
 1256: }
 1257: 
 1258: #------------------------------------------------------------------------------------
 1259: #
 1260: #-------------------------- Next few routines handles grading by student, essentially
 1261: #                           handles essay response type problem/part
 1262: #
 1263: #--- Javascript to handle the submission page functionality ---
 1264: sub sub_page_js {
 1265:     my $request = shift;
 1266:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1267:     &js_escape(\$alertmsg);
 1268:     $request->print(<<SUBJAVASCRIPT);
 1269: <script type="text/javascript" language="javascript">
 1270:     function updateRadio(formname,id,weight) {
 1271: 	var gradeBox = formname["GD_BOX"+id];
 1272: 	var radioButton = formname["RADVAL"+id];
 1273: 	var oldpts = formname["oldpts"+id].value;
 1274: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1275: 	gradeBox.value = pts;
 1276: 	var resetbox = false;
 1277: 	if (isNaN(pts) || pts < 0) {
 1278: 	    alert("$alertmsg"+pts);
 1279: 	    for (var i=0; i<radioButton.length; i++) {
 1280: 		if (radioButton[i].checked) {
 1281: 		    gradeBox.value = i;
 1282: 		    resetbox = true;
 1283: 		}
 1284: 	    }
 1285: 	    if (!resetbox) {
 1286: 		formtextbox.value = "";
 1287: 	    }
 1288: 	    return;
 1289: 	}
 1290: 
 1291: 	if (pts > weight) {
 1292: 	    var resp = confirm("You entered a value ("+pts+
 1293: 			       ") greater than the weight for the part. Accept?");
 1294: 	    if (resp == false) {
 1295: 		gradeBox.value = oldpts;
 1296: 		return;
 1297: 	    }
 1298: 	}
 1299: 
 1300: 	for (var i=0; i<radioButton.length; i++) {
 1301: 	    radioButton[i].checked=false;
 1302: 	    if (pts == i && pts != "") {
 1303: 		radioButton[i].checked=true;
 1304: 	    }
 1305: 	}
 1306: 	updateSelect(formname,id);
 1307: 	formname["stores"+id].value = "0";
 1308:     }
 1309: 
 1310:     function writeBox(formname,id,pts) {
 1311: 	var gradeBox = formname["GD_BOX"+id];
 1312: 	if (checkSolved(formname,id) == 'update') {
 1313: 	    gradeBox.value = pts;
 1314: 	} else {
 1315: 	    var oldpts = formname["oldpts"+id].value;
 1316: 	    gradeBox.value = oldpts;
 1317: 	    var radioButton = formname["RADVAL"+id];
 1318: 	    for (var i=0; i<radioButton.length; i++) {
 1319: 		radioButton[i].checked=false;
 1320: 		if (i == oldpts) {
 1321: 		    radioButton[i].checked=true;
 1322: 		}
 1323: 	    }
 1324: 	}
 1325: 	formname["stores"+id].value = "0";
 1326: 	updateSelect(formname,id);
 1327: 	return;
 1328:     }
 1329: 
 1330:     function clearRadBox(formname,id) {
 1331: 	if (checkSolved(formname,id) == 'noupdate') {
 1332: 	    updateSelect(formname,id);
 1333: 	    return;
 1334: 	}
 1335: 	gradeSelect = formname["GD_SEL"+id];
 1336: 	for (var i=0; i<gradeSelect.length; i++) {
 1337: 	    if (gradeSelect[i].selected) {
 1338: 		var selectx=i;
 1339: 	    }
 1340: 	}
 1341: 	var stores = formname["stores"+id];
 1342: 	if (selectx == stores.value) { return };
 1343: 	var gradeBox = formname["GD_BOX"+id];
 1344: 	gradeBox.value = "";
 1345: 	var radioButton = formname["RADVAL"+id];
 1346: 	for (var i=0; i<radioButton.length; i++) {
 1347: 	    radioButton[i].checked=false;
 1348: 	}
 1349: 	stores.value = selectx;
 1350:     }
 1351: 
 1352:     function checkSolved(formname,id) {
 1353: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1354: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1355: 	    if (!reply) {return "noupdate";}
 1356: 	    formname.overRideScore.value = 'yes';
 1357: 	}
 1358: 	return "update";
 1359:     }
 1360: 
 1361:     function updateSelect(formname,id) {
 1362: 	formname["GD_SEL"+id][0].selected = true;
 1363: 	return;
 1364:     }
 1365: 
 1366: //=========== Check that a point is assigned for all the parts  ============
 1367:     function checksubmit(formname,val,total,parttot) {
 1368: 	formname.gradeOpt.value = val;
 1369: 	if (val == "Save & Next") {
 1370: 	    for (i=0;i<=total;i++) {
 1371: 		for (j=0;j<parttot;j++) {
 1372: 		    var partid = formname["partid"+i+"_"+j].value;
 1373: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1374: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1375: 			if (points == "") {
 1376: 			    var name = formname["name"+i].value;
 1377: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1378: 			    var resp = confirm("You did not assign a score for "+studentID+
 1379: 					       ", part "+partid+". Continue?");
 1380: 			    if (resp == false) {
 1381: 				formname["GD_BOX"+i+"_"+partid].focus();
 1382: 				return false;
 1383: 			    }
 1384: 			}
 1385: 		    }
 1386: 		}
 1387: 	    }
 1388: 	}
 1389: 	if (val == "Grade Student") {
 1390: 	    formname.showgrading.value = "yes";
 1391: 	    if (formname.Status.value == "") {
 1392: 		formname.Status.value = "Active";
 1393: 	    }
 1394: 	    formname.studentNo.value = total;
 1395: 	}
 1396: 	formname.submit();
 1397:     }
 1398: 
 1399: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1400:     function checkSubmitPage(formname,total) {
 1401: 	noscore = new Array(100);
 1402: 	var ptr = 0;
 1403: 	for (i=1;i<total;i++) {
 1404: 	    var partid = formname["q_"+i].value;
 1405: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1406: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1407: 		var status = formname["solved"+i+"_"+partid].value;
 1408: 		if (points == "" && status != "correct_by_student") {
 1409: 		    noscore[ptr] = i;
 1410: 		    ptr++;
 1411: 		}
 1412: 	    }
 1413: 	}
 1414: 	if (ptr != 0) {
 1415: 	    var sense = ptr == 1 ? ": " : "s: ";
 1416: 	    var prolist = "";
 1417: 	    if (ptr == 1) {
 1418: 		prolist = noscore[0];
 1419: 	    } else {
 1420: 		var i = 0;
 1421: 		while (i < ptr-1) {
 1422: 		    prolist += noscore[i]+", ";
 1423: 		    i++;
 1424: 		}
 1425: 		prolist += "and "+noscore[i];
 1426: 	    }
 1427: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1428: 	    if (resp == false) {
 1429: 		return false;
 1430: 	    }
 1431: 	}
 1432: 
 1433: 	formname.submit();
 1434:     }
 1435: </script>
 1436: SUBJAVASCRIPT
 1437: }
 1438: 
 1439: #--- javascript for essay type problem --
 1440: sub sub_page_kw_js {
 1441:     my $request = shift;
 1442:     my $iconpath = $request->dir_config('lonIconsURL');
 1443:     &commonJSfunctions($request);
 1444: 
 1445:     my $inner_js_msg_central=<<INNERJS;
 1446:     <script text="text/javascript">
 1447:     function checkInput() {
 1448:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1449:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1450:       var usrctr = document.msgcenter.usrctr.value;
 1451:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1452:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1453: 
 1454:       var msgchk = "";
 1455:       if (document.msgcenter.subchk.checked) {
 1456:          msgchk = "msgsub,";
 1457:       }
 1458:       var includemsg = 0;
 1459:       for (var i=1; i<=nmsg; i++) {
 1460:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1461:           var frmmsg = document.msgcenter["msg"+i];
 1462:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1463:           var showflg = opener.document.SCORE["shownOnce"+i];
 1464:           showflg.value = "1";
 1465:           var chkbox = document.msgcenter["msgn"+i];
 1466:           if (chkbox.checked) {
 1467:              msgchk += "savemsg"+i+",";
 1468:              includemsg = 1;
 1469:           }
 1470:       }
 1471:       if (document.msgcenter.newmsgchk.checked) {
 1472:          msgchk += "newmsg"+usrctr;
 1473:          includemsg = 1;
 1474:       }
 1475:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1476:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1477:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1478:       includemsg.value = msgchk;
 1479: 
 1480:       self.close()
 1481: 
 1482:     }
 1483:     </script>
 1484: INNERJS
 1485: 
 1486:     my $inner_js_highlight_central=<<INNERJS;
 1487:  <script type="text/javascript">
 1488:     function updateChoice(flag) {
 1489:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1490:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1491:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1492:       opener.document.SCORE.refresh.value = "on";
 1493:       if (opener.document.SCORE.keywords.value!=""){
 1494:          opener.document.SCORE.submit();
 1495:       }
 1496:       self.close()
 1497:     }
 1498: </script>
 1499: INNERJS
 1500: 
 1501:     my $start_page_msg_central = 
 1502:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1503: 				       {'js_ready'  => 1,
 1504: 					'only_body' => 1,
 1505: 					'bgcolor'   =>'#FFFFFF',});
 1506:     my $end_page_msg_central = 
 1507: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1508: 
 1509: 
 1510:     my $start_page_highlight_central = 
 1511:         &Apache::loncommon::start_page('Highlight Central',
 1512: 				       $inner_js_highlight_central,
 1513: 				       {'js_ready'  => 1,
 1514: 					'only_body' => 1,
 1515: 					'bgcolor'   =>'#FFFFFF',});
 1516:     my $end_page_highlight_central = 
 1517: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1518: 
 1519:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1520:     $docopen=~s/^document\.//;
 1521:     my %js_lt = &Apache::lonlocal::texthash(
 1522:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1523:                 plse => 'Please select a word or group of words from document and then click this link.',
 1524:                 adds => 'Add selection to keyword list? Edit if desired.',
 1525:                 col1 => 'red',
 1526:                 col2 => 'green',
 1527:                 col3 => 'blue',
 1528:                 siz1 => 'normal',
 1529:                 siz2 => '+1',
 1530:                 siz3 => '+2',
 1531:                 sty1 => 'normal',
 1532:                 sty2 => 'italic',
 1533:                 sty3 => 'bold',
 1534:              );
 1535:     my %html_js_lt = &Apache::lonlocal::texthash(
 1536:                 comp => 'Compose Message for: ',
 1537:                 incl => 'Include',
 1538:                 type => 'Type',
 1539:                 subj => 'Subject',
 1540:                 mesa => 'Message',
 1541:                 new  => 'New',
 1542:                 save => 'Save',
 1543:                 canc => 'Cancel',
 1544:                 kehi => 'Keyword Highlight Options',
 1545:                 txtc => 'Text Color',
 1546:                 font => 'Font Size',
 1547:                 fnst => 'Font Style',
 1548:              );
 1549:     &js_escape(\%js_lt);
 1550:     &html_escape(\%html_js_lt);
 1551:     &js_escape(\%html_js_lt);
 1552:     $request->print(<<SUBJAVASCRIPT);
 1553: <script type="text/javascript" language="javascript">
 1554: 
 1555: //===================== Show list of keywords ====================
 1556:   function keywords(formname) {
 1557:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1558:     if (nret==null) return;
 1559:     formname.keywords.value = nret;
 1560: 
 1561:     if (formname.keywords.value != "") {
 1562: 	formname.refresh.value = "on";
 1563: 	formname.submit();
 1564:     }
 1565:     return;
 1566:   }
 1567: 
 1568: //===================== Script to view submitted by ==================
 1569:   function viewSubmitter(submitter) {
 1570:     document.SCORE.refresh.value = "on";
 1571:     document.SCORE.NCT.value = "1";
 1572:     document.SCORE.unamedom0.value = submitter;
 1573:     document.SCORE.submit();
 1574:     return;
 1575:   }
 1576: 
 1577: //===================== Script to add keyword(s) ==================
 1578:   function getSel() {
 1579:     if (document.getSelection) txt = document.getSelection();
 1580:     else if (document.selection) txt = document.selection.createRange().text;
 1581:     else return;
 1582:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1583:     if (cleantxt=="") {
 1584: 	alert("$js_lt{'plse'}");
 1585: 	return;
 1586:     }
 1587:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1588:     if (nret==null) return;
 1589:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1590:     if (document.SCORE.keywords.value != "") {
 1591: 	document.SCORE.refresh.value = "on";
 1592: 	document.SCORE.submit();
 1593:     }
 1594:     return;
 1595:   }
 1596: 
 1597: //====================== Script for composing message ==============
 1598:    // preload images
 1599:    img1 = new Image();
 1600:    img1.src = "$iconpath/mailbkgrd.gif";
 1601:    img2 = new Image();
 1602:    img2.src = "$iconpath/mailto.gif";
 1603: 
 1604:   function msgCenter(msgform,usrctr,fullname) {
 1605:     var Nmsg  = msgform.savemsgN.value;
 1606:     savedMsgHeader(Nmsg,usrctr,fullname);
 1607:     var subject = msgform.msgsub.value;
 1608:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1609:     re = /msgsub/;
 1610:     var shwsel = "";
 1611:     if (re.test(msgchk)) { shwsel = "checked" }
 1612:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1613:     displaySubject(checkEntities(subject),shwsel);
 1614:     for (var i=1; i<=Nmsg; i++) {
 1615: 	var testmsg = "savemsg"+i+",";
 1616: 	re = new RegExp(testmsg,"g");
 1617: 	shwsel = "";
 1618: 	if (re.test(msgchk)) { shwsel = "checked" }
 1619: 	var message = document.SCORE["savemsg"+i].value;
 1620: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1621: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1622: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1623:     }
 1624:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1625:     shwsel = "";
 1626:     re = /newmsg/;
 1627:     if (re.test(msgchk)) { shwsel = "checked" }
 1628:     newMsg(newmsg,shwsel);
 1629:     msgTail(); 
 1630:     return;
 1631:   }
 1632: 
 1633:   function checkEntities(strx) {
 1634:     if (strx.length == 0) return strx;
 1635:     var orgStr = ["&", "<", ">", '"']; 
 1636:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1637:     var counter = 0;
 1638:     while (counter < 4) {
 1639: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1640: 	counter++;
 1641:     }
 1642:     return strx;
 1643:   }
 1644: 
 1645:   function strReplace(strx, orgStr, newStr) {
 1646:     return strx.split(orgStr).join(newStr);
 1647:   }
 1648: 
 1649:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1650:     var height = 70*Nmsg+250;
 1651:     if (height > 600) {
 1652: 	height = 600;
 1653:     }
 1654:     var xpos = (screen.width-600)/2;
 1655:     xpos = (xpos < 0) ? '0' : xpos;
 1656:     var ypos = (screen.height-height)/2-30;
 1657:     ypos = (ypos < 0) ? '0' : ypos;
 1658: 
 1659:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1660:     pWin.focus();
 1661:     pDoc = pWin.document;
 1662:     pDoc.$docopen;
 1663:     pDoc.write('$start_page_msg_central');
 1664: 
 1665:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1666:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1667:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1668: 
 1669:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1670:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1671:     pDoc.write("<td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1672: }
 1673:     function displaySubject(msg,shwsel) {
 1674:     pDoc = pWin.document;
 1675:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1676:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1677:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1678:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1679: }
 1680: 
 1681:   function displaySavedMsg(ctr,msg,shwsel) {
 1682:     pDoc = pWin.document;
 1683:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1684:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1685:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1686:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1687: }
 1688: 
 1689:   function newMsg(newmsg,shwsel) {
 1690:     pDoc = pWin.document;
 1691:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1692:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1693:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1694:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1695: }
 1696: 
 1697:   function msgTail() {
 1698:     pDoc = pWin.document;
 1699:     pDoc.write("<\\/table>");
 1700:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1701:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1702:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1703:     pDoc.write("<\\/form>");
 1704:     pDoc.write('$end_page_msg_central');
 1705:     pDoc.close();
 1706: }
 1707: 
 1708: //====================== Script for keyword highlight options ==============
 1709:   function kwhighlight() {
 1710:     var kwclr    = document.SCORE.kwclr.value;
 1711:     var kwsize   = document.SCORE.kwsize.value;
 1712:     var kwstyle  = document.SCORE.kwstyle.value;
 1713:     var redsel = "";
 1714:     var grnsel = "";
 1715:     var blusel = "";
 1716:     var txtcol1 = "$js_lt{'col1'}";
 1717:     var txtcol2 = "$js_lt{'col2'}";
 1718:     var txtcol3 = "$js_lt{'col3'}";
 1719:     var txtsiz1 = "$js_lt{'siz1'}";
 1720:     var txtsiz2 = "$js_lt{'siz2'}";
 1721:     var txtsiz3 = "$js_lt{'siz3'}";
 1722:     var txtsty1 = "$js_lt{'sty1'}";
 1723:     var txtsty2 = "$js_lt{'sty2'}";
 1724:     var txtsty3 = "$js_lt{'sty3'}";
 1725:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1726:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1727:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1728:     var sznsel = "";
 1729:     var sz1sel = "";
 1730:     var sz2sel = "";
 1731:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1732:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1733:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1734:     var synsel = "";
 1735:     var syisel = "";
 1736:     var sybsel = "";
 1737:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1738:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1739:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1740:     highlightCentral();
 1741:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1742:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1743:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1744:     highlightend();
 1745:     return;
 1746:   }
 1747: 
 1748:   function highlightCentral() {
 1749: //    if (window.hwdWin) window.hwdWin.close();
 1750:     var xpos = (screen.width-400)/2;
 1751:     xpos = (xpos < 0) ? '0' : xpos;
 1752:     var ypos = (screen.height-330)/2-30;
 1753:     ypos = (ypos < 0) ? '0' : ypos;
 1754: 
 1755:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1756:     hwdWin.focus();
 1757:     var hDoc = hwdWin.document;
 1758:     hDoc.$docopen;
 1759:     hDoc.write('$start_page_highlight_central');
 1760:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1761:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1762: 
 1763:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1764:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1765:   }
 1766: 
 1767:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1768:     var hDoc = hwdWin.document;
 1769:     hDoc.write("<tr>");
 1770:     hDoc.write("<td align=\\"left\\">");
 1771:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1772:     hDoc.write("<td align=\\"left\\">");
 1773:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1774:     hDoc.write("<td align=\\"left\\">");
 1775:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1776:     hDoc.write("<\\/tr>");
 1777:   }
 1778: 
 1779:   function highlightend() { 
 1780:     var hDoc = hwdWin.document;
 1781:     hDoc.write("<\\/table><br \\/>");
 1782:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1783:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1784:     hDoc.write("<\\/form>");
 1785:     hDoc.write('$end_page_highlight_central');
 1786:     hDoc.close();
 1787:   }
 1788: 
 1789: </script>
 1790: SUBJAVASCRIPT
 1791: }
 1792: 
 1793: sub get_increment {
 1794:     my $increment = $env{'form.increment'};
 1795:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1796:         $increment != .1) {
 1797:         $increment = 1;
 1798:     }
 1799:     return $increment;
 1800: }
 1801: 
 1802: sub gradeBox_start {
 1803:     return (
 1804:         &Apache::loncommon::start_data_table()
 1805:        .&Apache::loncommon::start_data_table_header_row()
 1806:        .'<th>'.&mt('Part').'</th>'
 1807:        .'<th>'.&mt('Points').'</th>'
 1808:        .'<th>&nbsp;</th>'
 1809:        .'<th>'.&mt('Assign Grade').'</th>'
 1810:        .'<th>'.&mt('Weight').'</th>'
 1811:        .'<th>'.&mt('Grade Status').'</th>'
 1812:        .&Apache::loncommon::end_data_table_header_row()
 1813:     );
 1814: }
 1815: 
 1816: sub gradeBox_end {
 1817:     return (
 1818:         &Apache::loncommon::end_data_table()
 1819:     );
 1820: }
 1821: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1822: sub gradeBox {
 1823:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1824:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1825: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1826:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1827:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1828:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1829:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1830:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1831: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1832:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1833:     my $display_part= &get_display_part($partid,$symb);
 1834:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1835: 				       [$partid]);
 1836:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1837:     if ($last_resets{$partid}) {
 1838:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1839:     }
 1840:     my $result=&Apache::loncommon::start_data_table_row();
 1841:     my $ctr = 0;
 1842:     my $thisweight = 0;
 1843:     my $increment = &get_increment();
 1844: 
 1845:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1846:     while ($thisweight<=$wgt) {
 1847: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1848:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1849: 	    $thisweight.')" value="'.$thisweight.'" '.
 1850: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1851: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1852:         $thisweight += $increment;
 1853: 	$ctr++;
 1854:     }
 1855:     $radio.='</tr></table>';
 1856: 
 1857:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1858: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1859: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1860: 	$wgt.')" /></td>'."\n";
 1861:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1862: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1863: 	' </td>'."\n";
 1864:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1865: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1866:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1867: 	$line.='<option></option>'.
 1868: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1869:     } else {
 1870: 	$line.='<option selected="selected"></option>'.
 1871: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1872:     }
 1873:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1874: 
 1875: 
 1876:     $result .= 
 1877: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1878:     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
 1879:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1880: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1881: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1882: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1883:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1884:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1885:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1886:         $aggtries.'" />'."\n";
 1887:     my $res_error;
 1888:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1889:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1890:     if ($res_error) {
 1891:         return &navmap_errormsg();
 1892:     }
 1893:     return $result;
 1894: }
 1895: 
 1896: sub handback_box {
 1897:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1898:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1899:     my (@respids);
 1900:     my @part_response_id = &flatten_responseType($responseType);
 1901:     foreach my $part_response_id (@part_response_id) {
 1902:     	my ($part,$resp) = @{ $part_response_id };
 1903:         if ($part eq $partid) {
 1904:             push(@respids,$resp);
 1905:         }
 1906:     }
 1907:     my $result;
 1908:     foreach my $respid (@respids) {
 1909: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1910: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1911: 	next if (!@$files);
 1912: 	my $file_counter = 0;
 1913: 	foreach my $file (@$files) {
 1914: 	    if ($file =~ /\/portfolio\//) {
 1915:                 $file_counter++;
 1916:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1917:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1918:     	        $file_disp = "$name.$ext";
 1919:     	        $file = $file_path.$file_disp;
 1920:     	        $result.=&mt('Return commented version of [_1] to student.',
 1921:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1922:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1923:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1924: 	    }
 1925: 	}
 1926:         if ($file_counter) {
 1927:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1928:                        '<span class="LC_info">'.
 1929:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1930:         }
 1931:     }
 1932:     return $result;    
 1933: }
 1934: 
 1935: sub show_problem {
 1936:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1937:     my $rendered;
 1938:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1939:     &Apache::lonxml::remember_problem_counter();
 1940:     if ($mode eq 'both' or $mode eq 'text') {
 1941: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1942: 						       $env{'request.course.id'},
 1943: 						       undef,\%form);
 1944:     }
 1945:     if ($removeform) {
 1946: 	$rendered=~s|<form(.*?)>||g;
 1947: 	$rendered=~s|</form>||g;
 1948: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1949:     }
 1950:     my $companswer;
 1951:     if ($mode eq 'both' or $mode eq 'answer') {
 1952: 	&Apache::lonxml::restore_problem_counter();
 1953: 	$companswer=
 1954: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1955: 						    $env{'request.course.id'},
 1956: 						    %form);
 1957:     }
 1958:     if ($removeform) {
 1959: 	$companswer=~s|<form(.*?)>||g;
 1960: 	$companswer=~s|</form>||g;
 1961: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1962:     }
 1963:     my $renderheading = &mt('View of the problem');
 1964:     my $answerheading = &mt('Correct answer');
 1965:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1966:         my $stu_fullname = $env{'form.fullname'};
 1967:         if ($stu_fullname eq '') {
 1968:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1969:         }
 1970:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1971:         if ($forwhom ne '') {
 1972:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1973:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1974:         }
 1975:     }
 1976:     $rendered=
 1977:         '<div class="LC_Box">'
 1978:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1979:        .$rendered
 1980:        .'</div>';
 1981:     $companswer=
 1982:         '<div class="LC_Box">'
 1983:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1984:        .$companswer
 1985:        .'</div>';
 1986:     my $result;
 1987:     if ($mode eq 'both') {
 1988:         $result=$rendered.$companswer;
 1989:     } elsif ($mode eq 'text') {
 1990:         $result=$rendered;
 1991:     } elsif ($mode eq 'answer') {
 1992:         $result=$companswer;
 1993:     }
 1994:     return $result;
 1995: }
 1996: 
 1997: sub files_exist {
 1998:     my ($r, $symb) = @_;
 1999:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2000: 
 2001:     foreach my $student (@students) {
 2002:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2003:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2004: 					      $udom,$uname);
 2005:         my ($string,$timestamp)= &get_last_submission(\%record);
 2006:         foreach my $submission (@$string) {
 2007:             my ($partid,$respid) =
 2008: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2009:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2010: 					   \%record);
 2011:             return 1 if (@$files);
 2012:         }
 2013:     }
 2014:     return 0;
 2015: }
 2016: 
 2017: sub download_all_link {
 2018:     my ($r,$symb) = @_;
 2019:     my $all_students = 
 2020: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2021: 
 2022:     my $parts =
 2023: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2024: 
 2025:     my $identifier = &Apache::loncommon::get_cgi_id();
 2026:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2027:                              'cgi.'.$identifier.'.symb' => $symb,
 2028:                              'cgi.'.$identifier.'.parts' => $parts,});
 2029:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2030: 	      &mt('Download All Submitted Documents').'</a>');
 2031:     return
 2032: }
 2033: 
 2034: sub build_section_inputs {
 2035:     my $section_inputs;
 2036:     if ($env{'form.section'} eq '') {
 2037:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2038:     } else {
 2039:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2040:         foreach my $section (@sections) {
 2041:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2042:         }
 2043:     }
 2044:     return $section_inputs;
 2045: }
 2046: 
 2047: # --------------------------- show submissions of a student, option to grade 
 2048: sub submission {
 2049:     my ($request,$counter,$total) = @_;
 2050:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2051:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2052:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2053:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2054:     my ($symb) = &get_symb($request); 
 2055:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2056:     my ($essayurl,%coursedesc_by_cid);
 2057: 
 2058:     if (!&canview($usec)) {
 2059:         $request->print(
 2060:             '<span class="LC_warning">'.
 2061:             &mt('Unable to view requested student.').
 2062:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2063:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2064:             '</span>');
 2065: 	$request->print(&show_grading_menu_form($symb));
 2066: 	return;
 2067:     }
 2068: 
 2069:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2070:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2071:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2072:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2073:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2074: 	'" src="'.$request->dir_config('lonIconsURL').
 2075: 	'/check.gif" height="16" border="0" />';
 2076: 
 2077:     # header info
 2078:     if ($counter == 0) {
 2079: 	&sub_page_js($request);
 2080: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2081: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2082: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2083: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2084: 	    &download_all_link($request, $symb);
 2085: 	}
 2086: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2087: 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
 2088: 
 2089: 	# option to display problem, only once else it cause problems 
 2090:         # with the form later since the problem has a form.
 2091: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2092: 	    my $mode;
 2093: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2094: 		$mode='both';
 2095: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2096: 		$mode='text';
 2097: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2098: 		$mode='answer';
 2099: 	    }
 2100: 	    &Apache::lonxml::clear_problem_counter();
 2101: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2102: 	}
 2103: 
 2104: 	# kwclr is the only variable that is guaranteed not to be blank 
 2105:         # if this subroutine has been called once.
 2106: 	my %keyhash = ();
 2107: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2108: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2109: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2110: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2111: 
 2112: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2113: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2114: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2115: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2116: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2117: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2118: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2119: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2120: 	}
 2121: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2122: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2123: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2124: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2125: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2126: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2127: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2128: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2129: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2130: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2131: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2132: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2133: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2134: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2135: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2136: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2137: 			&build_section_inputs().
 2138: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2139: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2140: 			'<input type="hidden" name="NCT"'.
 2141: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2142: 	if ($env{'form.handgrade'} eq 'yes') {
 2143: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2144: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2145: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2146: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2147: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2148: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2149: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2150: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2151: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2152: 	    }
 2153: 	}
 2154: 	
 2155: 	my ($cts,$prnmsg) = (1,'');
 2156: 	while ($cts <= $env{'form.savemsgN'}) {
 2157: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2158: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2159: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2160: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2161: 		'" />'."\n".
 2162: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2163: 	    $cts++;
 2164: 	}
 2165: 	$request->print($prnmsg);
 2166: 
 2167: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2168: 
 2169:             my %lt = &Apache::lonlocal::texthash(
 2170:                           keyh => 'Keyword Highlighting for Essays',
 2171:                           keyw => 'Keyword Options',
 2172:                           list => 'List',
 2173:                           past => 'Paste Selection to List',
 2174:                           high => 'Highlight Attribute',
 2175:                      );
 2176: #
 2177: # Print out the keyword options line
 2178: #
 2179:             $request->print(
 2180:                 '<div class="LC_columnSection">'
 2181:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2182:                .&Apache::lonhtmlcommon::funclist_from_array(
 2183:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2184:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2185:  class="page">'.$lt{'past'}.'</a>',
 2186:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2187:                     {legend => $lt{'keyw'}})
 2188:                .'</fieldset></div>'
 2189:             );
 2190: 
 2191: #
 2192: # Load the other essays for similarity check
 2193: #
 2194:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2195:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2196:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2197:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2198:                 if ($cdom ne '' && $cnum ne '') {
 2199:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2200:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2201:                         my $apath = $1.'_'.$id;
 2202:                         $apath=~s/\W/\_/gs;
 2203:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2204:                     }
 2205:                 }
 2206:             } else {
 2207: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2208: 	        $apath=&escape($apath);
 2209: 	        $apath=~s/\W/\_/gs;
 2210:                 &init_old_essays($symb,$apath,$adom,$aname);
 2211:             }
 2212:         }
 2213:     }
 2214: 
 2215: # This is where output for one specific student would start
 2216:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2217:     $request->print(
 2218:         "\n\n"
 2219:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2220:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2221:        ."\n"
 2222:     );
 2223: 
 2224:     # Show additional functions if allowed
 2225:     if ($perm{'vgr'}) {
 2226:         $request->print(
 2227:             &Apache::loncommon::track_student_link(
 2228:                 'View recent activity',
 2229:                 $uname,$udom,'check')
 2230:            .' '
 2231:         );
 2232:     }
 2233:     if ($perm{'opa'}) {
 2234:         $request->print(
 2235:             &Apache::loncommon::pprmlink(
 2236:                 &mt('Set/Change parameters'),
 2237:                 $uname,$udom,$symb,'check'));
 2238:     }
 2239: 
 2240:     # Show Problem
 2241:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2242: 	my $mode;
 2243: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2244: 	    $mode='both';
 2245: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2246: 	    $mode='text';
 2247: 	} elsif ($env{'form.vAns'} eq 'all') {
 2248: 	    $mode='answer';
 2249: 	}
 2250: 	&Apache::lonxml::clear_problem_counter();
 2251: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2252:     }
 2253: 
 2254:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2255:     my $res_error;
 2256:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2257:     if ($res_error) {
 2258:         $request->print(&navmap_errormsg());
 2259:         return;
 2260:     }
 2261: 
 2262:     # Display student info
 2263:     $request->print(($counter == 0 ? '' : '<br />'));
 2264: 
 2265:     my $result='<div class="LC_Box">'
 2266:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2267:     $result.='<input type="hidden" name="name'.$counter.
 2268:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2269:     if ($env{'form.handgrade'} eq 'no') {
 2270:         $result.='<p class="LC_info">'
 2271:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2272:                 ."</p>\n";
 2273:     }
 2274: 
 2275:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2276:     my $fullname;
 2277:     my $col_fullnames = [];
 2278:     if ($env{'form.handgrade'} eq 'yes') {
 2279: 	(my $sub_result,$fullname,$col_fullnames)=
 2280: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2281: 				 $counter);
 2282: 	$result.=$sub_result;
 2283:     }
 2284:     $request->print($result."\n");
 2285: 
 2286:     # print student answer/submission
 2287:     # Options are (1) Handgraded submission only
 2288:     #             (2) Last submission, includes submission that is not handgraded 
 2289:     #                  (for multi-response type part)
 2290:     #             (3) Last submission plus the parts info
 2291:     #             (4) The whole record for this student
 2292: 
 2293: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2294: 	
 2295: 	my $lastsubonly;
 2296: 
 2297:         if ($$timestamp eq '') {
 2298:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2299:         } else {
 2300:             $lastsubonly =
 2301:                 '<div class="LC_grade_submissions_body">'
 2302:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2303: 
 2304: 	    my %seenparts;
 2305: 	    my @part_response_id = &flatten_responseType($responseType);
 2306: 	    foreach my $part (@part_response_id) {
 2307: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2308: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2309: 
 2310: 		my ($partid,$respid) = @{ $part };
 2311: 		my $display_part=&get_display_part($partid,$symb);
 2312: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2313: 		    if (exists($seenparts{$partid})) { next; }
 2314: 		    $seenparts{$partid}=1;
 2315:                     $request->print(
 2316:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2317:                         ' <b>'.&mt('Collaborative submission by: [_1]',
 2318:                                    '<a href="javascript:viewSubmitter(\''.
 2319:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
 2320:                                    '\');" target="_self">'.
 2321:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2322:                         '<br />');
 2323: 		    next;
 2324: 		}
 2325: 		my $responsetype = $responseType->{$partid}->{$respid};
 2326: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2327:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2328:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2329:                         ' <span class="LC_internal_info">'.
 2330:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2331:                         '</span>&nbsp; &nbsp;'.
 2332: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2333: 		    next;
 2334: 		}
 2335: 		foreach my $submission (@$string) {
 2336: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2337: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2338: 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2339: 		    # Similarity check
 2340: 		    my $similar='';
 2341:                     my ($type,$trial,$rndseed);
 2342:                     if ($hide eq 'rand') {
 2343:                         $type = 'randomizetry';
 2344:                         $trial = $record{"resource.$partid.tries"};
 2345:                         $rndseed = $record{"resource.$partid.rndseed"};
 2346:                     }
 2347: 		    if ($env{'form.checkPlag'}) {
 2348: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2349: 			    &most_similar($uname,$udom,$symb,$subval);
 2350: 			if ($osim) {
 2351: 			    $osim=int($osim*100.0);
 2352:                             if ($hide eq 'anon') {
 2353:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2354:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2355:                             } else {
 2356: 			        $similar='<hr />';
 2357:                                 if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2358:                                     $similar .= '<h3><span class="LC_warning">'.
 2359:                                                 &mt('Essay is [_1]% similar to an essay by [_2]',
 2360:                                                     $osim,
 2361:                                                     &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2362:                                                 '</span></h3>';
 2363:                                 } elsif ($ocrsid ne '') {
 2364:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2365:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2366:                                     } else {
 2367:                                         my $args;
 2368:                                         if ($ocrsid ne $env{'request.course.id'}) {
 2369:                                             $args = {'one_time' => 1};
 2370:                                         }
 2371:                                         %old_course_desc =
 2372:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
 2373:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2374:                                     }
 2375:                                     $similar .=
 2376: 				        &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2377: 				            $osim,
 2378: 				            &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2379: 				            $old_course_desc{'description'},
 2380: 				            $old_course_desc{'num'},
 2381: 				            $old_course_desc{'domain'}).
 2382: 				            '</span></h3>';
 2383:                                 } else {
 2384:                                     $similar .=
 2385:                                         '<h3><span class="LC_warning">'.
 2386:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2387:                                             $osim,
 2388:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2389:                                         '</span></h3>';
 2390:                                 }
 2391:                                 $similar .= '<blockquote><i>'.
 2392:                                             &keywords_highlight($oessay).
 2393:                                             '</i></blockquote><hr />';
 2394: 		            }
 2395:                         }
 2396:                     }
 2397: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2398:                                          undef,$type,$trial,$rndseed);
 2399:                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
 2400:                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2401: 			my $display_part=&get_display_part($partid,$symb);
 2402:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2403:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2404:                             ' <span class="LC_internal_info">'.
 2405:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2406:                             '</span>&nbsp; &nbsp;';
 2407: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2408: 			if (@$files) {
 2409:                             if ($hide eq 'anon') {
 2410:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2411:                             } else {
 2412:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2413:                                             .'<br /><span class="LC_warning">';
 2414:                                 if(@$files == 1) {
 2415:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2416:                                 } else {
 2417:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2418:                                 }
 2419:                                 $lastsubonly .= '</span>';
 2420: 
 2421:                                 foreach my $file (@$files) {
 2422:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2423:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2424:                                 }
 2425:                             }
 2426: 			    $lastsubonly.='<br />';
 2427: 			}
 2428:                         if ($hide eq 'anon') {
 2429:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2430:                         } else {
 2431: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2432:                             if ($draft) {
 2433:                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2434:                             }
 2435:                             $subval =
 2436: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2437: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2438:                             if ($responsetype eq 'essay') {
 2439:                                 $subval =~ s{\n}{<br />}g;
 2440:                             }
 2441:                             $lastsubonly.=$subval."\n";
 2442:                         }
 2443: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2444: 			$lastsubonly.='</div>';
 2445: 		    }
 2446: 		}
 2447: 	    }
 2448: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2449: 	}
 2450: 	$request->print($lastsubonly);
 2451:    if ($env{'form.lastSub'} eq 'datesub') {
 2452: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2453: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2454:     }
 2455:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2456:         my $identifier = (&canmodify($usec)? $counter : '');
 2457: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2458: 								 $env{'request.course.id'},
 2459: 								 $last,'.submission',
 2460: 								 'Apache::grades::keywords_highlight',
 2461:                                                                  $usec,$identifier));
 2462:     }
 2463: 
 2464:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2465: 	.$udom.'" />'."\n");
 2466:     # return if view submission with no grading option
 2467:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2468: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2469: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2470: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2471: 	$toGrade.='</div>'."\n";
 2472: 	if (($env{'form.command'} eq 'submission') || 
 2473: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2474: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2475: 	}
 2476: 	$request->print($toGrade);
 2477: 	return;
 2478:     } else {
 2479: 	$request->print('</div>'."\n");
 2480:     }
 2481: 
 2482:     # essay grading message center
 2483:     if ($env{'form.handgrade'} eq 'yes') {
 2484: 	my $result='<div class="LC_grade_message_center">';
 2485:     
 2486: 	$result.='<div class="LC_grade_message_center_header">'.
 2487: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2488: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2489: 	my $msgfor = $givenn.' '.$lastname;
 2490: 	if (scalar(@$col_fullnames) > 0) {
 2491: 	    my $lastone = pop(@$col_fullnames);
 2492: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2493: 	}
 2494: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2495: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2496: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2497: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2498: 	    ',\''.$msgfor.'\');" target="_self">'.
 2499: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2500: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2501: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2502: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2503: 	    '<br />&nbsp;('.
 2504: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2505: 	$result.='</div></div>';
 2506: 	$request->print($result);
 2507:     }
 2508: 
 2509:     my %seen = ();
 2510:     my @partlist;
 2511:     my @gradePartRespid;
 2512:     my @part_response_id = &flatten_responseType($responseType);
 2513:     $request->print(
 2514:         '<div class="LC_Box">'
 2515:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2516:     );
 2517:     $request->print(&gradeBox_start());
 2518:     foreach my $part_response_id (@part_response_id) {
 2519:     	my ($partid,$respid) = @{ $part_response_id };
 2520: 	my $part_resp = join('_',@{ $part_response_id });
 2521: 	next if ($seen{$partid} > 0);
 2522: 	$seen{$partid}++;
 2523: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2524: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2525: 	push(@partlist,$partid);
 2526: 	push(@gradePartRespid,$partid.'.'.$respid);
 2527: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2528:     }
 2529:     $request->print(&gradeBox_end()); # </div>
 2530:     $request->print('</div>');
 2531: 
 2532:     $request->print('<div class="LC_grade_info_links">');
 2533:     $request->print('</div>');
 2534: 
 2535:     $result='<input type="hidden" name="partlist'.$counter.
 2536: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2537:     $result.='<input type="hidden" name="gradePartRespid'.
 2538: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2539:     my $ctr = 0;
 2540:     while ($ctr < scalar(@partlist)) {
 2541: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2542: 	    $partlist[$ctr].'" />'."\n";
 2543: 	$ctr++;
 2544:     }
 2545:     $request->print($result.''."\n");
 2546: 
 2547: # Done with printing info for one student
 2548: 
 2549:     $request->print('</div>');#LC_grade_show_user
 2550: 
 2551: 
 2552:     # print end of form
 2553:     if ($counter == $total) {
 2554:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2555: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2556: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2557: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2558: 	my $ntstu ='<select name="NTSTU">'.
 2559: 	    '<option>1</option><option>2</option>'.
 2560: 	    '<option>3</option><option>5</option>'.
 2561: 	    '<option>7</option><option>10</option></select>'."\n";
 2562: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2563: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2564:         $endform.=&mt('[_1]student(s)',$ntstu);
 2565: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2566: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2567: 	    '<input type="button" value="'.&mt('Next').'" '.
 2568: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2569:         $endform.='<span class="LC_warning">'.
 2570:                   &mt('(Next and Previous (student) do not save the scores.)').
 2571:                   '</span>'."\n" ;
 2572:         $endform.="<input type='hidden' value='".&get_increment().
 2573:             "' name='increment' />";
 2574: 	$endform.='</td></tr></table></form>';
 2575: 	$endform.=&show_grading_menu_form($symb);
 2576: 	$request->print($endform);
 2577:     }
 2578:     return '';
 2579: }
 2580: 
 2581: sub check_collaborators {
 2582:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2583:     my ($result,@col_fullnames);
 2584:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2585:     foreach my $part (keys(%$handgrade)) {
 2586: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2587: 					'.maxcollaborators',
 2588: 					$symb,$udom,$uname);
 2589: 	next if ($ncol <= 0);
 2590: 	$part =~ s/\_/\./g;
 2591: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2592: 	my (@good_collaborators, @bad_collaborators);
 2593: 	foreach my $possible_collaborator
 2594: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2595: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2596: 	    next if ($possible_collaborator eq '');
 2597: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2598: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2599: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2600: 	    # Doing this grep allows 'fuzzy' specification
 2601: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2602: 			       keys(%$classlist));
 2603: 	    if (! scalar(@matches)) {
 2604: 		push(@bad_collaborators, $possible_collaborator);
 2605: 	    } else {
 2606: 		push(@good_collaborators, @matches);
 2607: 	    }
 2608: 	}
 2609: 	if (scalar(@good_collaborators) != 0) {
 2610: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2611: 	    foreach my $name (@good_collaborators) {
 2612: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2613: 		push(@col_fullnames, $givenn.' '.$lastname);
 2614: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2615: 	    }
 2616: 	    $result.='</ol><br />'."\n";
 2617: 	    my ($part)=split(/\./,$part);
 2618: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2619: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2620: 		"\n";
 2621: 	}
 2622: 	if (scalar(@bad_collaborators) > 0) {
 2623: 	    $result.='<div class="LC_warning">';
 2624: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2625: 	    $result .= '</div>';
 2626: 	}         
 2627: 	if (scalar(@bad_collaborators > $ncol)) {
 2628: 	    $result .= '<div class="LC_warning">';
 2629: 	    $result .= &mt('This student has submitted too many '.
 2630: 		'collaborators.  Maximum is [_1].',$ncol);
 2631: 	    $result .= '</div>';
 2632: 	}
 2633:     }
 2634:     return ($result,$fullname,\@col_fullnames);
 2635: }
 2636: 
 2637: #--- Retrieve the last submission for all the parts
 2638: sub get_last_submission {
 2639:     my ($returnhash)=@_;
 2640:     my (@string,$timestamp,%lasthidden);
 2641:     if ($$returnhash{'version'}) {
 2642: 	my %lasthash=();
 2643: 	my ($version);
 2644: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2645: 	    foreach my $key (sort(split(/\:/,
 2646: 					$$returnhash{$version.':keys'}))) {
 2647: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2648: 		$timestamp = 
 2649: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2650: 	    }
 2651: 	}
 2652:         my (%typeparts,%randombytry);
 2653:         my $showsurv = 
 2654:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2655:         foreach my $key (sort(keys(%lasthash))) {
 2656:             if ($key =~ /\.type$/) {
 2657:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2658:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2659:                     ($lasthash{$key} eq 'randomizetry')) {
 2660:                     my ($ign,@parts) = split(/\./,$key);
 2661:                     pop(@parts);
 2662:                     my $id = join('.',@parts);
 2663:                     if ($lasthash{$key} eq 'randomizetry') {
 2664:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2665:                     } else {
 2666:                         unless ($showsurv) {
 2667:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2668:                         }
 2669:                     }
 2670:                     delete($lasthash{$key});
 2671:                 }
 2672:             }
 2673:         }
 2674:         my @hidden = keys(%typeparts);
 2675:         my @randomize = keys(%randombytry);
 2676: 	foreach my $key (keys(%lasthash)) {
 2677: 	    next if ($key !~ /\.submission$/);
 2678:             my $hide;
 2679:             if (@hidden) {
 2680:                 foreach my $id (@hidden) {
 2681:                     if ($key =~ /^\Q$id\E/) {
 2682:                         $hide = 'anon';
 2683:                         last;
 2684:                     }
 2685:                 }
 2686:             }
 2687:             unless ($hide) {
 2688:                 if (@randomize) {
 2689:                     foreach my $id (@randomize) {
 2690:                         if ($key =~ /^\Q$id\E/) {
 2691:                             $hide = 'rand';
 2692:                             last;
 2693:                         }
 2694:                     }
 2695:                 }
 2696:             }
 2697: 	    my ($partid,$foo) = split(/submission$/,$key);
 2698: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
 2699:             push(@string, join(':', $key, $hide, $draft, (
 2700:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2701:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2702: 	}
 2703:     }
 2704:     if (!@string) {
 2705: 	$string[0] =
 2706: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2707:     }
 2708:     return (\@string,\$timestamp);
 2709: }
 2710: 
 2711: #--- High light keywords, with style choosen by user.
 2712: sub keywords_highlight {
 2713:     my $string    = shift;
 2714:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2715:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2716:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2717:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2718:     foreach my $keyword (@keylist) {
 2719: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2720:     }
 2721:     return $string;
 2722: }
 2723: 
 2724: # For Tasks provide a mechanism to display previous version for one specific student
 2725: 
 2726: sub show_previous_task_version {
 2727:     my ($request,$symb) = @_;
 2728:     if ($symb eq '') {
 2729:         $request->print(
 2730:             '<span class="LC_error">'.
 2731:             &mt('Unable to handle ambiguous references.').
 2732:             '</span>');
 2733:         return '';
 2734:     }
 2735:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2736:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2737:     if (!&canview($usec)) {
 2738:         $request->print('<span class="LC_warning">'.
 2739:                         &mt('Unable to view previous version for requested student.').
 2740:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2741:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2742:                         '</span>');
 2743:         return;
 2744:     }
 2745:     my $mode = 'both';
 2746:     my $isTask = ($symb =~/\.task$/);
 2747:     if ($isTask) {
 2748:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2749:             if ($env{'form.fullname'} eq '') {
 2750:                 $env{'form.fullname'} =
 2751:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2752:             }
 2753:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2754:             $request->print("\n\n".
 2755:                             '<div class="LC_grade_show_user">'.
 2756:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2757:                             '</h2>'."\n");
 2758:             &Apache::lonxml::clear_problem_counter();
 2759:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2760:                             {'previousversion' => $env{'form.previousversion'} }));
 2761:             $request->print("\n</div>");
 2762:         }
 2763:     }
 2764:     return;
 2765: }
 2766: 
 2767: sub choose_task_version_form {
 2768:     my ($symb,$uname,$udom,$nomenu) = @_;
 2769:     my $isTask = ($symb =~/\.task$/);
 2770:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2771:     if ($isTask) {
 2772:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2773:                                               $udom,$uname);
 2774:         if (($record{'resource.0.version'} eq '') ||
 2775:             ($record{'resource.0.version'} < 2)) {
 2776:             return ($record{'resource.0.version'},
 2777:                     $record{'resource.0.version'},$result,$js);
 2778:         } else {
 2779:             $current = $record{'resource.0.version'};
 2780:         }
 2781:         if ($env{'form.previousversion'}) {
 2782:             $displayed = $env{'form.previousversion'};
 2783:             $rowtitle = &mt('Choose another version:')
 2784:         } else {
 2785:             $displayed = $current;
 2786:             $rowtitle = &mt('Show earlier version:');
 2787:         }
 2788:         $result = '<div class="LC_left_float">';
 2789:         my $list;
 2790:         my $numversions = 0;
 2791:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2792:             if ($i == $current) {
 2793:                 if (!$env{'form.previousversion'} || $nomenu) {
 2794:                     next;
 2795:                 } else {
 2796:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2797:                     $numversions ++;
 2798:                 }
 2799:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2800:                 unless ($i == $env{'form.previousversion'}) {
 2801:                     $numversions ++;
 2802:                 }
 2803:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2804:             }
 2805:         }
 2806:         if ($numversions) {
 2807:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2808:             $result .=
 2809:                 '<form name="getprev" method="post" action=""'.
 2810:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2811:                 &Apache::loncommon::start_data_table().
 2812:                 &Apache::loncommon::start_data_table_row().
 2813:                 '<th align="left">'.$rowtitle.'</th>'.
 2814:                 '<td><select name="version">'.
 2815:                 '<option>'.&mt('Select').'</option>'.
 2816:                 $list.
 2817:                 '</select></td>'.
 2818:                 &Apache::loncommon::end_data_table_row();
 2819:             unless ($nomenu) {
 2820:                 $result .= &Apache::loncommon::start_data_table_row().
 2821:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2822:                 '<td><span class="LC_nobreak">'.
 2823:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2824:                 &mt('Yes').'</label>'.
 2825:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2826:                 '</span></td>'.
 2827:                 &Apache::loncommon::end_data_table_row();
 2828:             }
 2829:             $result .=
 2830:                 &Apache::loncommon::start_data_table_row().
 2831:                 '<th align="left">&nbsp;</th>'.
 2832:                 '<td>'.
 2833:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2834:                 '</td>'.
 2835:                 &Apache::loncommon::end_data_table_row().
 2836:                 &Apache::loncommon::end_data_table().
 2837:                 '</form>';
 2838:             $js = &previous_display_javascript($nomenu,$current);
 2839:         } elsif ($displayed && $nomenu) {
 2840:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2841:         } else {
 2842:             $result .= &mt('No previous versions to show for this student');
 2843:         }
 2844:         $result .= '</div>';
 2845:     }
 2846:     return ($current,$displayed,$result,$js);
 2847: }
 2848: 
 2849: sub previous_display_javascript {
 2850:     my ($nomenu,$current) = @_;
 2851:     my $js = <<"JSONE";
 2852: <script type="text/javascript">
 2853: // <![CDATA[
 2854: function previousVersion(uname,udom,symb) {
 2855:     var current = '$current';
 2856:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2857:     var prevstr = new RegExp("^\\\\d+\$");
 2858:     if (!prevstr.test(version)) {
 2859:         return false;
 2860:     }
 2861:     var url = '';
 2862:     if (version == current) {
 2863:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2864:     } else {
 2865:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2866:     }
 2867: JSONE
 2868:     if ($nomenu) {
 2869:         $js .= <<"JSTWO";
 2870:     document.location.href = url;
 2871: JSTWO
 2872:     } else {
 2873:         $js .= <<"JSTHREE";
 2874:     var newwin = 0;
 2875:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2876:         if (document.getprev.prevwin[i].checked == true) {
 2877:             newwin = document.getprev.prevwin[i].value;
 2878:         }
 2879:     }
 2880:     if (newwin == 1) {
 2881:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2882:         url = url+'&inhibitmenu=yes';
 2883:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2884:             previousWin = window.open(url,'',options,1);
 2885:         } else {
 2886:             previousWin.location.href = url;
 2887:         }
 2888:         previousWin.focus();
 2889:         return false;
 2890:     } else {
 2891:         document.location.href = url;
 2892:         return false;
 2893:     }
 2894: JSTHREE
 2895:     }
 2896:     $js .= <<"ENDJS";
 2897:     return false;
 2898: }
 2899: // ]]>
 2900: </script>
 2901: ENDJS
 2902: 
 2903: }
 2904: 
 2905: #--- Called from submission routine
 2906: sub processHandGrade {
 2907:     my ($request) = shift;
 2908:     my ($symb)   = &get_symb($request);
 2909:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2910:     my $button = $env{'form.gradeOpt'};
 2911:     my $ngrade = $env{'form.NCT'};
 2912:     my $ntstu  = $env{'form.NTSTU'};
 2913:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2914:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2915: 
 2916:     if ($button eq 'Save & Next') {
 2917: 	my $ctr = 0;
 2918: 	while ($ctr < $ngrade) {
 2919: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2920: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2921:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2922: 	    if ($errorflag eq 'no_score') {
 2923: 		$ctr++;
 2924: 		next;
 2925: 	    }
 2926: 	    if ($errorflag eq 'not_allowed') {
 2927:                 $request->print(
 2928:                     '<span class="LC_error">'
 2929:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2930:                    .'</span>');
 2931: 		$ctr++;
 2932: 		next;
 2933: 	    }
 2934:             if ($numhidden) {
 2935:                 $request->print(
 2936:                     '<span class="LC_info">'
 2937:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2938:                    .'</span><br />');
 2939:             }
 2940: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2941: 	    my ($subject,$message,$msgstatus) = ('','','');
 2942: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2943:             my ($feedurl,$showsymb) =
 2944: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2945: 	    my $messagetail;
 2946: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2947: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2948: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2949: 		$subject.=' ['.$restitle.']';
 2950: 		my (@msgnum) = split(/,/,$includemsg);
 2951: 		foreach (@msgnum) {
 2952: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2953: 		}
 2954: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2955: 		if ($env{'form.withgrades'.$ctr}) {
 2956: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2957: 		    $messagetail = " for <a href=\"".
 2958: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2959: 		}
 2960: 		$msgstatus = 
 2961:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2962: 						     $message.$messagetail,
 2963:                                                      undef,$feedurl,undef,
 2964:                                                      undef,undef,$showsymb,
 2965:                                                      $restitle);
 2966: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2967: 				$msgstatus.'<br />');
 2968: 	    }
 2969: 	    if ($env{'form.collaborator'.$ctr}) {
 2970: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2971: 		foreach my $collabstr (@collabstrs) {
 2972: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2973: 		    foreach my $collaborator (@collaborators) {
 2974: 			my ($errorflag,$pts,$wgt) = 
 2975: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2976: 					   $env{'form.unamedom'.$ctr},$part);
 2977: 			if ($errorflag eq 'not_allowed') {
 2978: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2979: 			    next;
 2980: 			} elsif ($message ne '') {
 2981: 			    my ($baseurl,$showsymb) = 
 2982: 				&get_feedurl_and_symb($symb,$collaborator,
 2983: 						      $udom);
 2984: 			    if ($env{'form.withgrades'.$ctr}) {
 2985: 				$messagetail = " for <a href=\"".
 2986:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2987: 			    }
 2988: 			    $msgstatus = 
 2989: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2990: 			}
 2991: 		    }
 2992: 		}
 2993: 	    }
 2994: 	    $ctr++;
 2995: 	}
 2996:     }
 2997: 
 2998:     if ($env{'form.handgrade'} eq 'yes') {
 2999: 	# Keywords sorted in alphabatical order
 3000: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3001: 	my %keyhash = ();
 3002: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3003: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 3004: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3005: 	$env{'form.keywords'} = join(' ',@keywords);
 3006: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3007: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3008: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3009: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3010: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3011: 
 3012: 	# message center - Order of message gets changed. Blank line is eliminated.
 3013: 	# New messages are saved in env for the next student.
 3014: 	# All messages are saved in nohist_handgrade.db
 3015: 	my ($ctr,$idx) = (1,1);
 3016: 	while ($ctr <= $env{'form.savemsgN'}) {
 3017: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3018: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3019: 		$idx++;
 3020: 	    }
 3021: 	    $ctr++;
 3022: 	}
 3023: 	$ctr = 0;
 3024: 	while ($ctr < $ngrade) {
 3025: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3026: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3027: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3028: 		$idx++;
 3029: 	    }
 3030: 	    $ctr++;
 3031: 	}
 3032: 	$env{'form.savemsgN'} = --$idx;
 3033: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3034: 	my $putresult = &Apache::lonnet::put
 3035: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3036:     }
 3037:     # Called by Save & Refresh from Highlight Attribute Window
 3038:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3039:     if ($env{'form.refresh'} eq 'on') {
 3040: 	my ($ctr,$total) = (0,0);
 3041: 	while ($ctr < $ngrade) {
 3042: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3043: 	    $ctr++;
 3044: 	}
 3045: 	$env{'form.NTSTU'}=$ngrade;
 3046: 	$ctr = 0;
 3047: 	while ($ctr < $total) {
 3048: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3049: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3050: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3051: 	    &submission($request,$ctr,$total-1);
 3052: 	    $ctr++;
 3053: 	}
 3054: 	return '';
 3055:     }
 3056: 
 3057: # Go directly to grade student - from submission or link from chart page
 3058:     if ($button eq 'Grade Student') {
 3059: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 3060: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 3061: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3062: 	$env{'form.fullname'} = $$fullname{$processUser};
 3063: 	&submission($request,0,0);
 3064: 	return '';
 3065:     }
 3066: 
 3067:     # Get the next/previous one or group of students
 3068:     my $firststu = $env{'form.unamedom0'};
 3069:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3070:     my $ctr = 2;
 3071:     while ($laststu eq '') {
 3072: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3073: 	$ctr++;
 3074: 	$laststu = $firststu if ($ctr > $ngrade);
 3075:     }
 3076: 
 3077:     my (@parsedlist,@nextlist);
 3078:     my ($nextflg) = 0;
 3079:     foreach my $item (sort 
 3080: 	     {
 3081: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3082: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3083: 		 }
 3084: 		 return $a cmp $b;
 3085: 	     } (keys(%$fullname))) {
 3086: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3087: 	    push(@parsedlist,$item);
 3088: 	}
 3089: 	$nextflg = 1 if ($item eq $laststu);
 3090: 	if ($button eq 'Previous') {
 3091: 	    last if ($item eq $firststu);
 3092: 	    push(@parsedlist,$item);
 3093: 	}
 3094:     }
 3095:     $ctr = 0;
 3096:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3097:     my $res_error;
 3098:     my ($partlist) = &response_type($symb,\$res_error);
 3099:     if ($res_error) {
 3100:         $request->print(&navmap_errormsg());
 3101:         return;
 3102:     }
 3103:     foreach my $student (@parsedlist) {
 3104: 	my $submitonly=$env{'form.submitonly'};
 3105: 	my ($uname,$udom) = split(/:/,$student);
 3106: 	
 3107: 	if ($submitonly eq 'queued') {
 3108: 	    my %queue_status = 
 3109: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3110: 							$udom,$uname);
 3111: 	    next if (!defined($queue_status{'gradingqueue'}));
 3112: 	}
 3113: 
 3114: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3115: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3116: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3117: 	    my $submitted = 0;
 3118: 	    my $ungraded = 0;
 3119: 	    my $incorrect = 0;
 3120: 	    foreach my $item (keys(%status)) {
 3121: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3122: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3123: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3124: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3125: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3126: 		    $submitted = 0;
 3127: 		}
 3128: 	    }
 3129: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3130: 				     $submitonly eq 'incorrect' ||
 3131: 				     $submitonly eq 'graded'));
 3132: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3133: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3134: 	}
 3135: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3136: 	last if ($ctr == $ntstu);
 3137: 	$ctr++;
 3138:     }
 3139: 
 3140:     $ctr = 0;
 3141:     my $total = scalar(@nextlist)-1;
 3142: 
 3143:     foreach (sort(@nextlist)) {
 3144: 	my ($uname,$udom,$submitter) = split(/:/);
 3145: 	$env{'form.student'}  = $uname;
 3146: 	$env{'form.userdom'}  = $udom;
 3147: 	$env{'form.fullname'} = $$fullname{$_};
 3148: 	&submission($request,$ctr,$total);
 3149: 	$ctr++;
 3150:     }
 3151:     if ($total < 0) {
 3152: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3153: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3154: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3155: 	$the_end.=&show_grading_menu_form($symb);
 3156: 	$request->print($the_end);
 3157:     }
 3158:     return '';
 3159: }
 3160: 
 3161: #---- Save the score and award for each student, if changed
 3162: sub saveHandGrade {
 3163:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3164:     my @version_parts;
 3165:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3166: 					   $env{'request.course.id'});
 3167:     if (!&canmodify($usec)) { return('not_allowed'); }
 3168:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3169:     my @parts_graded;
 3170:     my %newrecord  = ();
 3171:     my ($pts,$wgt,$totchg) = ('','',0);
 3172:     my %aggregate = ();
 3173:     my $aggregateflag = 0;
 3174:     if ($env{'form.HIDE'.$newflg}) {
 3175:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3176:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3177:         $totchg += $numchgs;
 3178:     }
 3179:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3180:     foreach my $new_part (@parts) {
 3181: 	#collaborator ($submi may vary for different parts
 3182: 	if ($submitter && $new_part ne $part) { next; }
 3183: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3184: 	if ($dropMenu eq 'excused') {
 3185: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3186: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3187: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3188: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3189: 		}
 3190: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3191: 	    }
 3192: 	} elsif ($dropMenu eq 'reset status'
 3193: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3194: 	    foreach my $key (keys(%record)) {
 3195: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3196: 	    }
 3197: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3198: 		"$env{'user.name'}:$env{'user.domain'}";
 3199:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3200: 
 3201:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3202: 					       [$new_part]);
 3203:             my $aggtries =$totaltries;
 3204:             if ($last_resets{$new_part}) {
 3205:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3206: 					   $new_part);
 3207:             }
 3208: 
 3209:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3210:             if ($aggtries > 0) {
 3211:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3212:                 $aggregateflag = 1;
 3213:             }
 3214: 	} elsif ($dropMenu eq '') {
 3215: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3216: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3217: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3218: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3219: 		next;
 3220: 	    }
 3221: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3222: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3223: 	    my $partial= $pts/$wgt;
 3224: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3225: 		#do not update score for part if not changed.
 3226:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3227: 		next;
 3228: 	    } else {
 3229: 	        push(@parts_graded,$new_part);
 3230: 	    }
 3231: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3232: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3233: 	    }
 3234: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3235: 	    if ($partial == 0) {
 3236: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3237: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3238: 		}
 3239: 	    } else {
 3240: 		if ($record{$reckey} ne 'correct_by_override') {
 3241: 		    $newrecord{$reckey} = 'correct_by_override';
 3242: 		}
 3243: 	    }	    
 3244: 	    if ($submitter && 
 3245: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3246: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3247: 	    }
 3248: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3249: 		"$env{'user.name'}:$env{'user.domain'}";
 3250: 	}
 3251: 	# unless problem has been graded, set flag to version the submitted files
 3252: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3253: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3254: 	        $dropMenu eq 'reset status')
 3255: 	   {
 3256: 	    push(@version_parts,$new_part);
 3257: 	}
 3258:     }
 3259:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3260:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3261: 
 3262:     if (%newrecord) {
 3263:         if (@version_parts) {
 3264:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3265:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3266: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3267: 	    foreach my $new_part (@version_parts) {
 3268: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3269: 				$new_part,\%newrecord);
 3270: 	    }
 3271:         }
 3272: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3273: 				$env{'request.course.id'},$domain,$stuname);
 3274: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3275: 				     $cdom,$cnum,$domain,$stuname);
 3276:     }
 3277:     if ($aggregateflag) {
 3278:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3279: 			      $cdom,$cnum);
 3280:     }
 3281:     return ('',$pts,$wgt,$totchg);
 3282: }
 3283: 
 3284: sub makehidden {
 3285:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3286:     return unless (ref($record) eq 'HASH');
 3287:     my %modified;
 3288:     my $numchanged = 0;
 3289:     if (exists($record->{$version.':keys'})) {
 3290:         my $partsregexp = $parts;
 3291:         $partsregexp =~ s/,/|/g;
 3292:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3293:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3294:                  my $item = $1;
 3295:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3296:                      $modified{$key} = $record->{$version.':'.$key};
 3297:                  }
 3298:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3299:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3300:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3301:                 $modified{$key} = $record->{$version.':'.$key};
 3302:             }
 3303:         }
 3304:         if (keys(%modified)) {
 3305:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3306:                                           $domain,$stuname,$tolog) eq 'ok') {
 3307:                 $numchanged ++;
 3308:             }
 3309:         }
 3310:     }
 3311:     return $numchanged;
 3312: }
 3313: 
 3314: sub check_and_remove_from_queue {
 3315:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3316:     my @ungraded_parts;
 3317:     foreach my $part (@{$parts}) {
 3318: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3319: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3320: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3321: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3322: 		) {
 3323: 	    push(@ungraded_parts, $part);
 3324: 	}
 3325:     }
 3326:     if ( !@ungraded_parts ) {
 3327: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3328: 					       $cnum,$domain,$stuname);
 3329:     }
 3330: }
 3331: 
 3332: sub handback_files {
 3333:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3334:     my $portfolio_root = '/userfiles/portfolio';
 3335:     my $res_error;
 3336:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3337:     if ($res_error) {
 3338:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3339:         return;
 3340:     }
 3341:     my @handedback;
 3342:     my $file_msg;
 3343:     my @part_response_id = &flatten_responseType($responseType);
 3344:     foreach my $part_response_id (@part_response_id) {
 3345:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3346: 	my $part_resp = join('_',@{ $part_response_id });
 3347:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3348:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3349:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3350: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3351:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3352:                     my ($directory,$answer_file) = 
 3353:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3354:                     my ($answer_name,$answer_ver,$answer_ext) =
 3355: 		        &file_name_version_ext($answer_file);
 3356: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3357:                     my $getpropath = 1;
 3358:                     my ($dir_list,$listerror) =
 3359:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3360:                                                  $domain,$stuname,$getpropath);
 3361: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3362:                     # fix filename
 3363:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3364:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3365:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3366:             	                                $save_file_name);
 3367:                     if ($result !~ m|^/uploaded/|) {
 3368:                         $request->print('<br /><span class="LC_error">'.
 3369:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3370:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3371:                                         '</span>');
 3372:                     } else {
 3373:                         # mark the file as read only
 3374:                         push(@handedback,$save_file_name);
 3375: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3376: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3377: 			}
 3378:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3379: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3380: 
 3381:                     }
 3382:                     $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>'));
 3383:                 }
 3384:             }
 3385:         }
 3386:     }
 3387:     if (@handedback > 0) {
 3388:         $request->print('<br />');
 3389:         my @what = ($symb,$env{'request.course.id'},'handback');
 3390:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3391:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3392:         my ($subject,$message);
 3393:         if (scalar(@handedback) == 1) {
 3394:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3395:         } else {
 3396:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3397:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3398:         }
 3399:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3400:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3401:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3402:         my ($feedurl,$showsymb) =
 3403:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3404:         my $restitle = &Apache::lonnet::gettitle($symb);
 3405:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3406:         my $msgstatus =
 3407:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3408:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3409:                  $restitle);
 3410:         if ($msgstatus) {
 3411:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3412:         }
 3413:     }
 3414:     return;
 3415: }
 3416: 
 3417: sub get_feedurl_and_symb {
 3418:     my ($symb,$uname,$udom) = @_;
 3419:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3420:     $url = &Apache::lonnet::clutter($url);
 3421:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3422: 					$symb,$udom,$uname);
 3423:     if ($encrypturl =~ /^yes$/i) {
 3424: 	&Apache::lonenc::encrypted(\$url,1);
 3425: 	&Apache::lonenc::encrypted(\$symb,1);
 3426:     }
 3427:     return ($url,$symb);
 3428: }
 3429: 
 3430: sub get_submitted_files {
 3431:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3432:     my @files;
 3433:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3434:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3435:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3436:     	    push(@files,$file_url.$file);
 3437:         }
 3438:     }
 3439:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3440:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3441:     }
 3442:     return (\@files);
 3443: }
 3444: 
 3445: # ----------- Provides number of tries since last reset.
 3446: sub get_num_tries {
 3447:     my ($record,$last_reset,$part) = @_;
 3448:     my $timestamp = '';
 3449:     my $num_tries = 0;
 3450:     if ($$record{'version'}) {
 3451:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3452:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3453:                 $timestamp = $$record{$version.':timestamp'};
 3454:                 if ($timestamp > $last_reset) {
 3455:                     $num_tries ++;
 3456:                 } else {
 3457:                     last;
 3458:                 }
 3459:             }
 3460:         }
 3461:     }
 3462:     return $num_tries;
 3463: }
 3464: 
 3465: # ----------- Determine decrements required in aggregate totals 
 3466: sub decrement_aggs {
 3467:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3468:     my %decrement = (
 3469:                         attempts => 0,
 3470:                         users => 0,
 3471:                         correct => 0
 3472:                     );
 3473:     $decrement{'attempts'} = $aggtries;
 3474:     if ($solvedstatus =~ /^correct/) {
 3475:         $decrement{'correct'} = 1;
 3476:     }
 3477:     if ($aggtries == $totaltries) {
 3478:         $decrement{'users'} = 1;
 3479:     }
 3480:     foreach my $type (keys(%decrement)) {
 3481:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3482:     }
 3483:     return;
 3484: }
 3485: 
 3486: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3487: sub get_last_resets {
 3488:     my ($symb,$courseid,$partids) =@_;
 3489:     my %last_resets;
 3490:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3491:     my $cname = $env{'course.'.$courseid.'.num'};
 3492:     my @keys;
 3493:     foreach my $part (@{$partids}) {
 3494: 	push(@keys,"$symb\0$part\0resettime");
 3495:     }
 3496:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3497: 				     $cdom,$cname);
 3498:     foreach my $part (@{$partids}) {
 3499: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3500:     }
 3501:     return %last_resets;
 3502: }
 3503: 
 3504: # ----------- Handles creating versions for portfolio files as answers
 3505: sub version_portfiles {
 3506:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3507:     my $version_parts = join('|',@$v_flag);
 3508:     my @returned_keys;
 3509:     my $parts = join('|', @$parts_graded);
 3510:     my $portfolio_root = '/userfiles/portfolio';
 3511:     foreach my $key (keys(%$record)) {
 3512:         my $new_portfiles;
 3513:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3514:             my @versioned_portfiles;
 3515:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3516:             foreach my $file (@portfiles) {
 3517:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3518:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3519: 		my ($answer_name,$answer_ver,$answer_ext) =
 3520: 		    &file_name_version_ext($answer_file);
 3521:                 my $getpropath = 1;
 3522:                 my ($dir_list,$listerror) =
 3523:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3524:                                              $stu_name,$getpropath);
 3525:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3526:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3527:                 if ($new_answer ne 'problem getting file') {
 3528:                     push(@versioned_portfiles, $directory.$new_answer);
 3529:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3530:                         [$directory.$new_answer],
 3531:                         [$symb,$env{'request.course.id'},'graded']);
 3532:                 }
 3533:             }
 3534:             $$record{$key} = join(',',@versioned_portfiles);
 3535:             push(@returned_keys,$key);
 3536:         }
 3537:     } 
 3538:     return (@returned_keys);   
 3539: }
 3540: 
 3541: sub get_next_version {
 3542:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3543:     my $version;
 3544:     if (ref($dir_list) eq 'ARRAY') {
 3545:         foreach my $row (@{$dir_list}) {
 3546:             my ($file) = split(/\&/,$row,2);
 3547:             my ($file_name,$file_version,$file_ext) =
 3548: 	        &file_name_version_ext($file);
 3549:             if (($file_name eq $answer_name) && 
 3550: 	        ($file_ext eq $answer_ext)) {
 3551:                 # gets here if filename and extension match, 
 3552:                 # regardless of version
 3553:                 if ($file_version ne '') {
 3554:                     # a versioned file is found  so save it for later
 3555:                     if ($file_version > $version) {
 3556: 		        $version = $file_version;
 3557:                     }
 3558: 	        }
 3559:             }
 3560:         }
 3561:     }
 3562:     $version ++;
 3563:     return($version);
 3564: }
 3565: 
 3566: sub version_selected_portfile {
 3567:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3568:     my ($answer_name,$answer_ver,$answer_ext) =
 3569:         &file_name_version_ext($file_name);
 3570:     my $new_answer;
 3571:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3572:     if($env{'form.copy'} eq '-1') {
 3573:         $new_answer = 'problem getting file';
 3574:     } else {
 3575:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3576:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3577:                             $stu_name,$domain,'copy',
 3578: 		        '/portfolio'.$directory.$new_answer);
 3579:     }    
 3580:     return ($new_answer);
 3581: }
 3582: 
 3583: sub file_name_version_ext {
 3584:     my ($file)=@_;
 3585:     my @file_parts = split(/\./, $file);
 3586:     my ($name,$version,$ext);
 3587:     if (@file_parts > 1) {
 3588: 	$ext=pop(@file_parts);
 3589: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3590: 	    $version=pop(@file_parts);
 3591: 	}
 3592: 	$name=join('.',@file_parts);
 3593:     } else {
 3594: 	$name=join('.',@file_parts);
 3595:     }
 3596:     return($name,$version,$ext);
 3597: }
 3598: 
 3599: #--------------------------------------------------------------------------------------
 3600: #
 3601: #-------------------------- Next few routines handles grading by section or whole class
 3602: #
 3603: #--- Javascript to handle grading by section or whole class
 3604: sub viewgrades_js {
 3605:     my ($request) = shift;
 3606: 
 3607:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3608:     &js_escape(\$alertmsg);
 3609:     $request->print(<<VIEWJAVASCRIPT);
 3610: <script type="text/javascript" language="javascript">
 3611:    function writePoint(partid,weight,point) {
 3612: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3613: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3614: 	if (point == "textval") {
 3615: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3616: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3617: 		alert("$alertmsg"+parseFloat(point));
 3618: 		var resetbox = false;
 3619: 		for (var i=0; i<radioButton.length; i++) {
 3620: 		    if (radioButton[i].checked) {
 3621: 			textbox.value = i;
 3622: 			resetbox = true;
 3623: 		    }
 3624: 		}
 3625: 		if (!resetbox) {
 3626: 		    textbox.value = "";
 3627: 		}
 3628: 		return;
 3629: 	    }
 3630: 	    if (parseFloat(point) > parseFloat(weight)) {
 3631: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3632: 				   ") greater than the weight for the part. Accept?");
 3633: 		if (resp == false) {
 3634: 		    textbox.value = "";
 3635: 		    return;
 3636: 		}
 3637: 	    }
 3638: 	    for (var i=0; i<radioButton.length; i++) {
 3639: 		radioButton[i].checked=false;
 3640: 		if (parseFloat(point) == i) {
 3641: 		    radioButton[i].checked=true;
 3642: 		}
 3643: 	    }
 3644: 
 3645: 	} else {
 3646: 	    textbox.value = parseFloat(point);
 3647: 	}
 3648: 	for (i=0;i<document.classgrade.total.value;i++) {
 3649: 	    var user = document.classgrade["ctr"+i].value;
 3650: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3651: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3652: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3653: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3654: 	    if (saveval != "correct") {
 3655: 		scorename.value = point;
 3656: 		if (selname[0].selected != true) {
 3657: 		    selname[0].selected = true;
 3658: 		}
 3659: 	    }
 3660: 	}
 3661: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3662:     }
 3663: 
 3664:     function writeRadText(partid,weight) {
 3665: 	var selval   = document.classgrade["SELVAL_"+partid];
 3666: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3667:         var override = document.classgrade["FORCE_"+partid].checked;
 3668: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3669: 	if (selval[1].selected || selval[2].selected) {
 3670: 	    for (var i=0; i<radioButton.length; i++) {
 3671: 		radioButton[i].checked=false;
 3672: 
 3673: 	    }
 3674: 	    textbox.value = "";
 3675: 
 3676: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3677: 		var user = document.classgrade["ctr"+i].value;
 3678: 		user = user.replace(new RegExp(':', 'g'),"_");
 3679: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3680: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3681: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3682: 		if ((saveval != "correct") || override) {
 3683: 		    scorename.value = "";
 3684: 		    if (selval[1].selected) {
 3685: 			selname[1].selected = true;
 3686: 		    } else {
 3687: 			selname[2].selected = true;
 3688: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3689: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3690: 		    }
 3691: 		}
 3692: 	    }
 3693: 	} else {
 3694: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3695: 		var user = document.classgrade["ctr"+i].value;
 3696: 		user = user.replace(new RegExp(':', 'g'),"_");
 3697: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3698: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3699: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3700: 		if ((saveval != "correct") || override) {
 3701: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3702: 		    selname[0].selected = true;
 3703: 		}
 3704: 	    }
 3705: 	}	    
 3706:     }
 3707: 
 3708:     function changeSelect(partid,user) {
 3709: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3710: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3711: 	var point  = textbox.value;
 3712: 	var weight = document.classgrade["weight_"+partid].value;
 3713: 
 3714: 	if (isNaN(point) || parseFloat(point) < 0) {
 3715: 	    alert("$alertmsg"+parseFloat(point));
 3716: 	    textbox.value = "";
 3717: 	    return;
 3718: 	}
 3719: 	if (parseFloat(point) > parseFloat(weight)) {
 3720: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3721: 			       ") greater than the weight of the part. Accept?");
 3722: 	    if (resp == false) {
 3723: 		textbox.value = "";
 3724: 		return;
 3725: 	    }
 3726: 	}
 3727: 	selval[0].selected = true;
 3728:     }
 3729: 
 3730:     function changeOneScore(partid,user) {
 3731: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3732: 	if (selval[1].selected || selval[2].selected) {
 3733: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3734: 	    if (selval[2].selected) {
 3735: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3736: 	    }
 3737:         }
 3738:     }
 3739: 
 3740:     function resetEntry(numpart) {
 3741: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3742: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3743: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3744: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3745: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3746: 	    for (var i=0; i<radioButton.length; i++) {
 3747: 		radioButton[i].checked=false;
 3748: 
 3749: 	    }
 3750: 	    textbox.value = "";
 3751: 	    selval[0].selected = true;
 3752: 
 3753: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3754: 		var user = document.classgrade["ctr"+i].value;
 3755: 		user = user.replace(new RegExp(':', 'g'),"_");
 3756: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3757: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3758: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3759: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3760: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3761: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3762: 		if (saveselval == "excused") {
 3763: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3764: 		} else {
 3765: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3766: 		}
 3767: 	    }
 3768: 	}
 3769:     }
 3770: 
 3771: </script>
 3772: VIEWJAVASCRIPT
 3773: }
 3774: 
 3775: #--- show scores for a section or whole class w/ option to change/update a score
 3776: sub viewgrades {
 3777:     my ($request) = shift;
 3778:     &viewgrades_js($request);
 3779: 
 3780:     my ($symb) = &get_symb($request);
 3781:     #need to make sure we have the correct data for later EXT calls, 
 3782:     #thus invalidate the cache
 3783:     &Apache::lonnet::devalidatecourseresdata(
 3784:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3785:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3786:     &Apache::lonnet::clear_EXT_cache_status();
 3787: 
 3788:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3789:     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3790: 
 3791:     #view individual student submission form - called using Javascript viewOneStudent
 3792:     $result.=&jscriptNform($symb);
 3793: 
 3794:     #beginning of class grading form
 3795:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3796:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3797: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3798: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3799: 	&build_section_inputs().
 3800: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3801: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3802: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3803: 
 3804:     #retrieve selected groups
 3805:     my (@groups,$group_display);
 3806:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3807:     if (grep(/^all$/,@groups)) {
 3808:         @groups = ('all');
 3809:     } elsif (grep(/^none$/,@groups)) {
 3810:         @groups = ('none');
 3811:     } elsif (@groups > 0) {
 3812:         $group_display = join(', ',@groups);
 3813:     }
 3814: 
 3815:     my ($common_header,$specific_header,@sections,$section_display);
 3816:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3817:     if (grep(/^all$/,@sections)) {
 3818:         @sections = ('all');
 3819:         if ($group_display) {
 3820:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3821:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3822:         } elsif (grep(/^none$/,@groups)) {
 3823:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3824:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3825:         } else {
 3826:             $common_header = &mt('Assign Common Grade to Class');
 3827:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3828:         }
 3829:     } elsif (grep(/^none$/,@sections)) {
 3830:         @sections = ('none');
 3831:         if ($group_display) {
 3832:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3833:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3834:         } elsif (grep(/^none$/,@groups)) {
 3835:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3836:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3837:         } else {
 3838:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3839:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3840:         }
 3841:     } else {
 3842:         $section_display = join (", ",@sections);
 3843:         if ($group_display) {
 3844:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3845:                                  $section_display,$group_display);
 3846:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3847:                                    $section_display,$group_display);
 3848:         } elsif (grep(/^none$/,@groups)) {
 3849:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3850:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3851:         } else {
 3852:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3853:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3854:         }
 3855:     }
 3856:     my %submit_types = &substatus_options();
 3857:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3858: 
 3859:     if ($env{'form.submitonly'} eq 'all') {
 3860:         $result.= '<h3>'.$common_header.'</h3>';
 3861:     } else {
 3862:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 3863:     }
 3864:     $result .= &Apache::loncommon::start_data_table();
 3865:     #radio buttons/text box for assigning points for a section or class.
 3866:     #handles different parts of a problem
 3867:     my $res_error;
 3868:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3869:     if ($res_error) {
 3870:         return &navmap_errormsg();
 3871:     }
 3872:     my %weight = ();
 3873:     my $ctsparts = 0;
 3874:     my %seen = ();
 3875:     my @part_response_id = &flatten_responseType($responseType);
 3876:     foreach my $part_response_id (@part_response_id) {
 3877:     	my ($partid,$respid) = @{ $part_response_id };
 3878: 	my $part_resp = join('_',@{ $part_response_id });
 3879: 	next if $seen{$partid};
 3880: 	$seen{$partid}++;
 3881: 	my $handgrade=$$handgrade{$part_resp};
 3882: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3883: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3884: 
 3885: 	my $display_part=&get_display_part($partid,$symb);
 3886: 	my $radio.='<table border="0"><tr>';  
 3887: 	my $ctr = 0;
 3888: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3889: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3890: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3891: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3892: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3893: 	    $ctr++;
 3894: 	}
 3895: 	$radio.='</tr></table>';
 3896: 	my $line = '<input type="text" name="TEXTVAL_'.
 3897: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3898: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3899: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3900: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3901:                 '<select name="SELVAL_'.$partid.'" '.
 3902: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 3903: 		$weight{$partid}.')"> '.
 3904: 	    '<option selected="selected"> </option>'.
 3905: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3906: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3907: 	    '</select></td>'.
 3908:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3909: 	$line.='<input type="hidden" name="partid_'.
 3910: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3911: 	$line.='<input type="hidden" name="weight_'.
 3912: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3913: 
 3914: 	$result.=
 3915: 	    &Apache::loncommon::start_data_table_row()."\n".
 3916: 	    '<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>'.
 3917: 	    &Apache::loncommon::end_data_table_row()."\n";
 3918: 	$ctsparts++;
 3919:     }
 3920:     $result.=&Apache::loncommon::end_data_table()."\n".
 3921: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3922:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3923: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3924: 
 3925:     #table listing all the students in a section/class
 3926:     #header of table
 3927:     if ($env{'form.submitonly'} eq 'all') { 
 3928:         $result.= '<h3>'.$specific_header.'</h3>';
 3929:     } else {
 3930:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 3931:     }
 3932:     $result.= &Apache::loncommon::start_data_table().
 3933: 	      &Apache::loncommon::start_data_table_header_row().
 3934: 	      '<th>'.&mt('No.').'</th>'.
 3935: 	      '<th>'.&nameUserString('header')."</th>\n";
 3936:     my $partserror;
 3937:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3938:     if ($partserror) {
 3939:         return &navmap_errormsg();
 3940:     }
 3941:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3942:     my @partids = ();
 3943:     foreach my $part (@parts) {
 3944: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3945:         my $narrowtext = &mt('Tries');
 3946: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3947: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3948: 	my ($partid) = &split_part_type($part);
 3949:         push(@partids,$partid);
 3950: 	my $display_part=&get_display_part($partid,$symb);
 3951: 	if ($display =~ /^Partial Credit Factor/) {
 3952: 	    $result.='<th>'.
 3953:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3954:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3955: 	    next;
 3956: 	    
 3957: 	} else {
 3958: 	    if ($display =~ /Problem Status/) {
 3959: 		my $grade_status_mt = &mt('Grade Status');
 3960: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3961: 	    }
 3962: 	    my $part_mt = &mt('Part:');
 3963: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3964: 	}
 3965: 
 3966: 	$result.='<th>'.$display.'</th>'."\n";
 3967:     }
 3968:     $result.=&Apache::loncommon::end_data_table_header_row();
 3969: 
 3970:     my %last_resets = 
 3971: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3972: 
 3973:     #get info for each student
 3974:     #list all the students - with points and grade status
 3975:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3976:     my $ctr = 0;
 3977:     foreach (sort 
 3978: 	     {
 3979: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3980: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3981: 		 }
 3982: 		 return $a cmp $b;
 3983: 	     } (keys(%$fullname))) {
 3984: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3985: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 3986:     }
 3987:     $result.=&Apache::loncommon::end_data_table();
 3988:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3989:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3990: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3991:     if ($ctr == 0) {
 3992:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3993:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 3994:                 '<span class="LC_warning">';
 3995:         if ($env{'form.submitonly'} eq 'all') {
 3996:             if (grep(/^all$/,@sections)) {
 3997:                 if (grep(/^all$/,@groups)) {
 3998:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 3999:                                    $stu_status);
 4000:                 } elsif (grep(/^none$/,@groups)) {
 4001:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4002:                                    $stu_status);
 4003:                 } else {
 4004:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4005:                                    $group_display,$stu_status);
 4006:                 }
 4007:             } elsif (grep(/^none$/,@sections)) {
 4008:                 if (grep(/^all$/,@groups)) {
 4009:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4010:                                    $stu_status);
 4011:                 } elsif (grep(/^none$/,@groups)) {
 4012:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4013:                                    $stu_status);
 4014:                 } else {
 4015:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4016:                                    $group_display,$stu_status);
 4017:                 }
 4018:             } else {
 4019:                 if (grep(/^all$/,@groups)) {
 4020:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4021:                                    $section_display,$stu_status);
 4022:                 } elsif (grep(/^none$/,@groups)) {
 4023:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4024:                                    $section_display,$stu_status);
 4025:                 } else {
 4026:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4027:                                    $section_display,$group_display,$stu_status);
 4028:                 }
 4029:             }
 4030:         } else {
 4031:             if (grep(/^all$/,@sections)) {
 4032:                 if (grep(/^all$/,@groups)) {
 4033:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4034:                                    $stu_status,$submission_status);
 4035:                 } elsif (grep(/^none$/,@groups)) {
 4036:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4037:                                    $stu_status,$submission_status);
 4038:                 } else {
 4039:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4040:                                    $group_display,$stu_status,$submission_status);
 4041:                 }
 4042:             } elsif (grep(/^none$/,@sections)) {
 4043:                 if (grep(/^all$/,@groups)) {
 4044:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4045:                                    $stu_status,$submission_status);
 4046:                 } elsif (grep(/^none$/,@groups)) {
 4047:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4048:                                    $stu_status,$submission_status);
 4049:                 } else {
 4050:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4051:                                    $group_display,$stu_status,$submission_status);
 4052:                 }
 4053:             } else {
 4054:                 if (grep(/^all$/,@groups)) {
 4055:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4056:                                    $section_display,$stu_status,$submission_status);
 4057:                 } elsif (grep(/^none$/,@groups)) {
 4058:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4059:                                    $section_display,$stu_status,$submission_status);
 4060:                 } else {
 4061:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] and submission status "[_4]" to modify or grade.',
 4062:                                    $section_display,$group_display,$stu_status,$submission_status);
 4063:                 }
 4064:             }
 4065: 	}
 4066: 	$result .= '</span><br />';
 4067:     }
 4068:     $result.=&show_grading_menu_form($symb);
 4069:     return $result;
 4070: }
 4071: 
 4072: #--- call by previous routine to display each student who satisfies submission filter.
 4073: sub viewstudentgrade {
 4074:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4075:     my ($uname,$udom) = split(/:/,$student);
 4076:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4077:     my $submitonly = $env{'form.submitonly'};
 4078:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4079:         my %partstatus = ();
 4080:         if (ref($parts) eq 'ARRAY') {
 4081:             foreach my $apart (@{$parts}) {
 4082:                 my ($part,$type) = &split_part_type($apart);
 4083:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4084:                 $status = 'nothing' if ($status eq '');
 4085:                 $partstatus{$part}      = $status;
 4086:                 my $subkey = "resource.$part.submitted_by";
 4087:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4088:             }
 4089:             my $submitted = 0;
 4090:             my $graded = 0;
 4091:             my $incorrect = 0;
 4092:             foreach my $key (keys(%partstatus)) {
 4093:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4094:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4095:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4096: 
 4097:                 my $partid = (split(/\./,$key))[1];
 4098:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4099:                     $submitted = 0;
 4100:                 }
 4101:             }
 4102:             return if (!$submitted && ($submitonly eq 'yes' ||
 4103:                                        $submitonly eq 'incorrect' ||
 4104:                                        $submitonly eq 'graded'));
 4105:             return if (!$graded && ($submitonly eq 'graded'));
 4106:             return if (!$incorrect && $submitonly eq 'incorrect');
 4107:         }
 4108:     }
 4109:     if ($submitonly eq 'queued') {
 4110:         my ($cdom,$cnum) = split(/_/,$courseid);
 4111:         my %queue_status =
 4112:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4113:                                                     $udom,$uname);
 4114:         return if (!defined($queue_status{'gradingqueue'}));
 4115:     }
 4116:     $$ctr++;
 4117:     my %aggregates = ();
 4118:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4119: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4120: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4121: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4122: 	'\');" target="_self">'.$fullname.'</a> '.
 4123: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4124:     $student=~s/:/_/; # colon doen't work in javascript for names
 4125:     foreach my $apart (@$parts) {
 4126: 	my ($part,$type) = &split_part_type($apart);
 4127: 	my $score=$record{"resource.$part.$type"};
 4128:         $result.='<td align="center">';
 4129:         my ($aggtries,$totaltries);
 4130:         unless (exists($aggregates{$part})) {
 4131: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4132: 
 4133: 	    $aggtries = $totaltries;
 4134:             if ($$last_resets{$part}) {  
 4135:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4136: 					   $part);
 4137:             }
 4138:             $result.='<input type="hidden" name="'.
 4139:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4140:             $result.='<input type="hidden" name="'.
 4141:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4142:             $aggregates{$part} = 1;
 4143:         }
 4144: 	if ($type eq 'awarded') {
 4145: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4146: 	    $result.='<input type="hidden" name="'.
 4147: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4148: 	    $result.='<input type="text" name="'.
 4149: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4150:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4151: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4152: 	} elsif ($type eq 'solved') {
 4153: 	    my ($status,$foo)=split(/_/,$score,2);
 4154: 	    $status = 'nothing' if ($status eq '');
 4155: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4156: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4157: 	    $result.='&nbsp;<select name="'.
 4158: 		'GD_'.$student.'_'.$part.'_solved" '.
 4159:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4160: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4161: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4162: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4163: 	    $result.="</select>&nbsp;</td>\n";
 4164: 	} else {
 4165: 	    $result.='<input type="hidden" name="'.
 4166: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4167: 		    "\n";
 4168: 	    $result.='<input type="text" name="'.
 4169: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4170: 		'value="'.$score.'" size="4" /></td>'."\n";
 4171: 	}
 4172:     }
 4173:     $result.=&Apache::loncommon::end_data_table_row();
 4174:     return $result;
 4175: }
 4176: 
 4177: #--- change scores for all the students in a section/class
 4178: #    record does not get update if unchanged
 4179: sub editgrades {
 4180:     my ($request) = @_;
 4181: 
 4182:     my ($symb)=&get_symb($request);
 4183:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4184:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4185:     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 4186:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4187: 
 4188:     my $result= &Apache::loncommon::start_data_table().
 4189: 	&Apache::loncommon::start_data_table_header_row().
 4190: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4191: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4192:     my %scoreptr = (
 4193: 		    'correct'  =>'correct_by_override',
 4194: 		    'incorrect'=>'incorrect_by_override',
 4195: 		    'excused'  =>'excused',
 4196: 		    'ungraded' =>'ungraded_attempted',
 4197:                     'credited' =>'credit_attempted',
 4198: 		    'nothing'  => '',
 4199: 		    );
 4200:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4201: 
 4202:     my (@partid);
 4203:     my %weight = ();
 4204:     my %columns = ();
 4205:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4206: 
 4207:     my $partserror;
 4208:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4209:     if ($partserror) {
 4210:         return &navmap_errormsg();
 4211:     }
 4212:     my $header;
 4213:     while ($ctr < $env{'form.totalparts'}) {
 4214: 	my $partid = $env{'form.partid_'.$ctr};
 4215: 	push(@partid,$partid);
 4216: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4217: 	$ctr++;
 4218:     }
 4219:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4220:     my $totcolspan = 0;
 4221:     foreach my $partid (@partid) {
 4222: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4223: 	    '<th align="center">'.&mt('New Score').'</th>';
 4224: 	$columns{$partid}=2;
 4225: 	foreach my $stores (@parts) {
 4226: 	    my ($part,$type) = &split_part_type($stores);
 4227: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4228: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4229: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4230: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4231:             my $narrowtext = &mt('Tries');
 4232: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4233: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4234: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4235: 	    $columns{$partid}+=2;
 4236: 	}
 4237:         $totcolspan += $columns{$partid};
 4238:     }
 4239:     foreach my $partid (@partid) {
 4240: 	my $display_part=&get_display_part($partid,$symb);
 4241: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4242: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4243: 	    '</th>';
 4244: 
 4245:     }
 4246:     $result .= &Apache::loncommon::end_data_table_header_row().
 4247: 	&Apache::loncommon::start_data_table_header_row().
 4248: 	$header.
 4249: 	&Apache::loncommon::end_data_table_header_row();
 4250:     my @noupdate;
 4251:     my ($updateCtr,$noupdateCtr) = (1,1);
 4252:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4253: 	my $user = $env{'form.ctr'.$i};
 4254: 	my ($uname,$udom)=split(/:/,$user);
 4255: 	my %newrecord;
 4256: 	my $updateflag = 0;
 4257:         my $usec=$classlist->{"$uname:$udom"}[5];
 4258:         my $canmodify = &canmodify($usec);
 4259:         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4260:                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4261:         if (!$canmodify) {
 4262:             push(@noupdate,
 4263:                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4264:                  &mt('Not allowed to modify student')."</span></td>");
 4265:             next;
 4266:         }
 4267:         my %aggregate = ();
 4268:         my $aggregateflag = 0;
 4269: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4270: 	foreach (@partid) {
 4271: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4272: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4273: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4274: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4275: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4276: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4277: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4278: 	    my $score;
 4279: 	    if ($partial eq '') {
 4280: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4281: 	    } elsif ($partial > 0) {
 4282: 		$score = 'correct_by_override';
 4283: 	    } elsif ($partial == 0) {
 4284: 		$score = 'incorrect_by_override';
 4285: 	    }
 4286: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4287: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4288: 
 4289: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4290: 		"$env{'user.name'}:$env{'user.domain'}";
 4291: 	    if ($dropMenu eq 'reset status' &&
 4292: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4293: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4294: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4295: 		$newrecord{'resource.'.$_.'.award'} = '';
 4296: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4297: 		$updateflag = 1;
 4298:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4299:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4300:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4301:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4302:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4303:                     $aggregateflag = 1;
 4304:                 }
 4305: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4306: 		$updateflag = 1;
 4307: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4308: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4309: 		$rec_update++;
 4310: 	    }
 4311: 
 4312: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4313: 		'<td align="center">'.$awarded.
 4314: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4315: 
 4316: 
 4317: 	    my $partid=$_;
 4318: 	    foreach my $stores (@parts) {
 4319: 		my ($part,$type) = &split_part_type($stores);
 4320: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4321: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4322: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4323: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4324: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4325: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4326: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4327: 		    $updateflag=1;
 4328: 		}
 4329: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4330: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4331: 	    }
 4332: 	}
 4333: 	$line.="\n";
 4334: 
 4335: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4336: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4337: 
 4338: 	if ($updateflag) {
 4339: 	    $count++;
 4340: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4341: 				    $udom,$uname);
 4342: 
 4343: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4344: 					      $cnum,$udom,$uname)) {
 4345: 		# need to figure out if should be in queue.
 4346: 		my %record =  
 4347: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4348: 					     $udom,$uname);
 4349: 		my $all_graded = 1;
 4350: 		my $none_graded = 1;
 4351: 		foreach my $part (@parts) {
 4352: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4353: 			$all_graded = 0;
 4354: 		    } else {
 4355: 			$none_graded = 0;
 4356: 		    }
 4357: 		}
 4358: 
 4359: 		if ($all_graded || $none_graded) {
 4360: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4361: 							   $symb,$cdom,$cnum,
 4362: 							   $udom,$uname);
 4363: 		}
 4364: 	    }
 4365: 
 4366: 	    $result.=&Apache::loncommon::start_data_table_row().
 4367: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4368: 		&Apache::loncommon::end_data_table_row();
 4369: 	    $updateCtr++;
 4370: 	} else {
 4371: 	    push(@noupdate,
 4372: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4373: 	    $noupdateCtr++;
 4374: 	}
 4375:         if ($aggregateflag) {
 4376:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4377: 				  $cdom,$cnum);
 4378:         }
 4379:     }
 4380:     if (@noupdate) {
 4381:         my $numcols=$totcolspan+2;
 4382: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4383: 	    '<td align="center" colspan="'.$numcols.'">'.
 4384: 	    &mt('No Changes Occurred For the Students Below').
 4385: 	    '</td>'.
 4386: 	    &Apache::loncommon::end_data_table_row();
 4387: 	foreach my $line (@noupdate) {
 4388: 	    $result.=
 4389: 		&Apache::loncommon::start_data_table_row().
 4390: 		$line.
 4391: 		&Apache::loncommon::end_data_table_row();
 4392: 	}
 4393:     }
 4394:     $result .= &Apache::loncommon::end_data_table().
 4395: 	&show_grading_menu_form($symb);
 4396:     my $msg = '<p><b>'.
 4397: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4398: 	    $rec_update,$count).'</b><br />'.
 4399: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4400: 	'</b></p>';
 4401:     return $title.$msg.$result;
 4402: }
 4403: 
 4404: sub split_part_type {
 4405:     my ($partstr) = @_;
 4406:     my ($temp,@allparts)=split(/_/,$partstr);
 4407:     my $type=pop(@allparts);
 4408:     my $part=join('_',@allparts);
 4409:     return ($part,$type);
 4410: }
 4411: 
 4412: #------------- end of section for handling grading by section/class ---------
 4413: #
 4414: #----------------------------------------------------------------------------
 4415: 
 4416: 
 4417: #----------------------------------------------------------------------------
 4418: #
 4419: #-------------------------- Next few routines handles grading by csv upload
 4420: #
 4421: #--- Javascript to handle csv upload
 4422: sub csvupload_javascript_reverse_associate {
 4423:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4424:     my $error2=&mt('You need to specify at least one grading field');
 4425:   &js_escape(\$error1);
 4426:   &js_escape(\$error2);
 4427:   return(<<ENDPICK);
 4428:   function verify(vf) {
 4429:     var foundsomething=0;
 4430:     var founduname=0;
 4431:     var foundID=0;
 4432:     for (i=0;i<=vf.nfields.value;i++) {
 4433:       tw=eval('vf.f'+i+'.selectedIndex');
 4434:       if (i==0 && tw!=0) { foundID=1; }
 4435:       if (i==1 && tw!=0) { founduname=1; }
 4436:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4437:     }
 4438:     if (founduname==0 && foundID==0) {
 4439: 	alert('$error1');
 4440: 	return;
 4441:     }
 4442:     if (foundsomething==0) {
 4443: 	alert('$error2');
 4444: 	return;
 4445:     }
 4446:     vf.submit();
 4447:   }
 4448:   function flip(vf,tf) {
 4449:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4450:     var i;
 4451:     for (i=0;i<=vf.nfields.value;i++) {
 4452:       //can not pick the same destination field for both name and domain
 4453:       if (((i ==0)||(i ==1)) && 
 4454:           ((tf==0)||(tf==1)) && 
 4455:           (i!=tf) &&
 4456:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4457:         eval('vf.f'+i+'.selectedIndex=0;')
 4458:       }
 4459:     }
 4460:   }
 4461: ENDPICK
 4462: }
 4463: 
 4464: sub csvupload_javascript_forward_associate {
 4465:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4466:     my $error2=&mt('You need to specify at least one grading field');
 4467:   &js_escape(\$error1);
 4468:   &js_escape(\$error2);
 4469:   return(<<ENDPICK);
 4470:   function verify(vf) {
 4471:     var foundsomething=0;
 4472:     var founduname=0;
 4473:     var foundID=0;
 4474:     for (i=0;i<=vf.nfields.value;i++) {
 4475:       tw=eval('vf.f'+i+'.selectedIndex');
 4476:       if (tw==1) { foundID=1; }
 4477:       if (tw==2) { founduname=1; }
 4478:       if (tw>3) { foundsomething=1; }
 4479:     }
 4480:     if (founduname==0 && foundID==0) {
 4481: 	alert('$error1');
 4482: 	return;
 4483:     }
 4484:     if (foundsomething==0) {
 4485: 	alert('$error2');
 4486: 	return;
 4487:     }
 4488:     vf.submit();
 4489:   }
 4490:   function flip(vf,tf) {
 4491:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4492:     var i;
 4493:     //can not pick the same destination field twice
 4494:     for (i=0;i<=vf.nfields.value;i++) {
 4495:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4496:         eval('vf.f'+i+'.selectedIndex=0;')
 4497:       }
 4498:     }
 4499:   }
 4500: ENDPICK
 4501: }
 4502: 
 4503: sub csvuploadmap_header {
 4504:     my ($request,$symb,$datatoken,$distotal)= @_;
 4505:     my $javascript;
 4506:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4507: 	$javascript=&csvupload_javascript_reverse_associate();
 4508:     } else {
 4509: 	$javascript=&csvupload_javascript_forward_associate();
 4510:     }
 4511: 
 4512:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4513:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4514:     my $ignore=&mt('Ignore First Line');
 4515:     $symb = &Apache::lonenc::check_encrypt($symb);
 4516:     $request->print(<<ENDPICK);
 4517: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4518: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4519: $result
 4520: <hr />
 4521: <h3>Identify fields</h3>
 4522: Total number of records found in file: $distotal <hr />
 4523: Enter as many fields as you can. The system will inform you and bring you back
 4524: to this page if the data selected is insufficient to run your class.<hr />
 4525: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4526: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4527: <input type="hidden" name="associate"  value="" />
 4528: <input type="hidden" name="phase"      value="three" />
 4529: <input type="hidden" name="datatoken"  value="$datatoken" />
 4530: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4531: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4532: <input type="hidden" name="upfile_associate" 
 4533:                                        value="$env{'form.upfile_associate'}" />
 4534: <input type="hidden" name="symb"       value="$symb" />
 4535: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4536: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4537: <input type="hidden" name="command"    value="csvuploadoptions" />
 4538: <hr />
 4539: <script type="text/javascript" language="Javascript">
 4540: $javascript
 4541: </script>
 4542: ENDPICK
 4543:     return '';
 4544: 
 4545: }
 4546: 
 4547: sub csvupload_fields {
 4548:     my ($symb,$errorref) = @_;
 4549:     my (@parts) = &getpartlist($symb,$errorref);
 4550:     if (ref($errorref)) {
 4551:         if ($$errorref) {
 4552:             return;
 4553:         }
 4554:     }
 4555: 
 4556:     my @fields=(['ID','Student/Employee ID'],
 4557: 		['username','Student Username'],
 4558: 		['domain','Student Domain']);
 4559:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4560:     foreach my $part (sort(@parts)) {
 4561: 	my @datum;
 4562: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4563: 	my $name=$part;
 4564: 	if  (!$display) { $display = $name; }
 4565: 	@datum=($name,$display);
 4566: 	if ($name=~/^stores_(.*)_awarded/) {
 4567: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4568: 	}
 4569: 	push(@fields,\@datum);
 4570:     }
 4571:     return (@fields);
 4572: }
 4573: 
 4574: sub csvuploadmap_footer {
 4575:     my ($request,$i,$keyfields) =@_;
 4576:     my $buttontext = &mt('Assign Grades');
 4577:     $request->print(<<ENDPICK);
 4578: </table>
 4579: <input type="hidden" name="nfields" value="$i" />
 4580: <input type="hidden" name="keyfields" value="$keyfields" />
 4581: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4582: </form>
 4583: ENDPICK
 4584: }
 4585: 
 4586: sub checkforfile_js {
 4587:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4588:     &js_escape(\$alertmsg);
 4589:     my $result =<<CSVFORMJS;
 4590: <script type="text/javascript" language="javascript">
 4591:     function checkUpload(formname) {
 4592: 	if (formname.upfile.value == "") {
 4593: 	    alert("$alertmsg");
 4594: 	    return false;
 4595: 	}
 4596: 	formname.submit();
 4597:     }
 4598:     </script>
 4599: CSVFORMJS
 4600:     return $result;
 4601: }
 4602: 
 4603: sub upcsvScores_form {
 4604:     my ($request) = shift;
 4605:     my ($symb)=&get_symb($request);
 4606:     if (!$symb) {return '';}
 4607:     my $result=&checkforfile_js();
 4608:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4609:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4610:     $result.=$table;
 4611:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4612:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4613:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4614: 	'</b></td></tr>'."\n";
 4615:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4616:     my $upload=&mt("Upload Scores");
 4617:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4618:     my $ignore=&mt('Ignore First Line');
 4619:     $symb = &Apache::lonenc::check_encrypt($symb);
 4620:     $result.=<<ENDUPFORM;
 4621: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4622: <input type="hidden" name="symb" value="$symb" />
 4623: <input type="hidden" name="command" value="csvuploadmap" />
 4624: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4625: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4626: $upfile_select
 4627: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4628: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4629: </form>
 4630: ENDUPFORM
 4631:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4632:                            &mt("How do I create a CSV file from a spreadsheet"))
 4633:     .'</td></tr></table>'."\n";
 4634:     $result.='</td></tr></table><br /><br />'."\n";
 4635:     $result.=&show_grading_menu_form($symb);
 4636:     return $result;
 4637: }
 4638: 
 4639: 
 4640: sub csvuploadmap {
 4641:     my ($request)= @_;
 4642:     my ($symb)=&get_symb($request);
 4643:     if (!$symb) {return '';}
 4644: 
 4645:     my $datatoken;
 4646:     if (!$env{'form.datatoken'}) {
 4647: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4648:     } else {
 4649:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4650:         if ($datatoken ne '') { 
 4651: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4652:         }
 4653:     }
 4654:     my @records=&Apache::loncommon::upfile_record_sep();
 4655:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4656:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4657:     my ($i,$keyfields);
 4658:     if (@records) {
 4659:         my $fieldserror;
 4660: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4661:         if ($fieldserror) {
 4662:             $request->print(&navmap_errormsg());
 4663:             return;
 4664:         }
 4665: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4666: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4667: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4668: 							  \@fields);
 4669: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4670: 	    chop($keyfields);
 4671: 	} else {
 4672: 	    unshift(@fields,['none','']);
 4673: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4674: 							    \@fields);
 4675:             foreach my $rec (@records) {
 4676:                 my %temp = &Apache::loncommon::record_sep($rec);
 4677:                 if (%temp) {
 4678:                     $keyfields=join(',',sort(keys(%temp)));
 4679:                     last;
 4680:                 }
 4681:             }
 4682: 	}
 4683:     }
 4684:     &csvuploadmap_footer($request,$i,$keyfields);
 4685:     $request->print(&show_grading_menu_form($symb));
 4686: 
 4687:     return '';
 4688: }
 4689: 
 4690: sub csvuploadoptions {
 4691:     my ($request)= @_;
 4692:     my ($symb)=&get_symb($request);
 4693:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4694:     my $ignore=&mt('Ignore First Line');
 4695:     $request->print(<<ENDPICK);
 4696: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4697: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4698: <input type="hidden" name="command"    value="csvuploadassign" />
 4699: <!--
 4700: <p>
 4701: <label>
 4702:    <input type="checkbox" name="show_full_results" />
 4703:    Show a table of all changes
 4704: </label>
 4705: </p>
 4706: -->
 4707: <p>
 4708: <label>
 4709:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4710:    Overwrite any existing score
 4711: </label>
 4712: </p>
 4713: ENDPICK
 4714:     my %fields=&get_fields();
 4715:     if (!defined($fields{'domain'})) {
 4716: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4717: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4718:     }
 4719:     foreach my $key (sort(keys(%env))) {
 4720: 	if ($key !~ /^form\.(.*)$/) { next; }
 4721: 	my $cleankey=$1;
 4722: 	if ($cleankey eq 'command') { next; }
 4723: 	$request->print('<input type="hidden" name="'.$cleankey.
 4724: 			'"  value="'.$env{$key}.'" />'."\n");
 4725:     }
 4726:     # FIXME do a check for any duplicated user ids...
 4727:     # FIXME do a check for any invalid user ids?...
 4728:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4729: <hr /></form>'."\n");
 4730:     $request->print(&show_grading_menu_form($symb));
 4731:     return '';
 4732: }
 4733: 
 4734: sub get_fields {
 4735:     my %fields;
 4736:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4737:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4738: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4739: 	    if ($env{'form.f'.$i} ne 'none') {
 4740: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4741: 	    }
 4742: 	} else {
 4743: 	    if ($env{'form.f'.$i} ne 'none') {
 4744: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4745: 	    }
 4746: 	}
 4747:     }
 4748:     return %fields;
 4749: }
 4750: 
 4751: sub csvuploadassign {
 4752:     my ($request)= @_;
 4753:     my ($symb)=&get_symb($request);
 4754:     if (!$symb) {return '';}
 4755:     my $error_msg = '';
 4756:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4757:     if ($datatoken ne '') {
 4758:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4759:     }
 4760:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4761:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4762:     my %fields=&get_fields();
 4763:     $request->print('<h3>Assigning Grades</h3>');
 4764:     my $courseid=$env{'request.course.id'};
 4765:     my ($classlist) = &getclasslist('all',0);
 4766:     my @notallowed;
 4767:     my @skipped;
 4768:     my @warnings;
 4769:     my $countdone=0;
 4770:     foreach my $grade (@gradedata) {
 4771: 	my %entries=&Apache::loncommon::record_sep($grade);
 4772: 	my $domain;
 4773: 	if ($entries{$fields{'domain'}}) {
 4774: 	    $domain=$entries{$fields{'domain'}};
 4775: 	} else {
 4776: 	    $domain=$env{'form.default_domain'};
 4777: 	}
 4778: 	$domain=~s/\s//g;
 4779: 	my $username=$entries{$fields{'username'}};
 4780: 	$username=~s/\s//g;
 4781: 	if (!$username) {
 4782: 	    my $id=$entries{$fields{'ID'}};
 4783: 	    $id=~s/\s//g;
 4784: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4785: 	    $username=$ids{$id};
 4786: 	}
 4787: 	if (!exists($$classlist{"$username:$domain"})) {
 4788: 	    my $id=$entries{$fields{'ID'}};
 4789: 	    $id=~s/\s//g;
 4790: 	    if ($id) {
 4791: 		push(@skipped,"$id:$domain");
 4792: 	    } else {
 4793: 		push(@skipped,"$username:$domain");
 4794: 	    }
 4795: 	    next;
 4796: 	}
 4797: 	my $usec=$classlist->{"$username:$domain"}[5];
 4798: 	if (!&canmodify($usec)) {
 4799: 	    push(@notallowed,"$username:$domain");
 4800: 	    next;
 4801: 	}
 4802: 	my %points;
 4803: 	my %grades;
 4804: 	foreach my $dest (keys(%fields)) {
 4805: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4806: 		$dest eq 'domain') { next; }
 4807: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4808: 	    if ($dest=~/stores_(.*)_points/) {
 4809: 		my $part=$1;
 4810: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4811: 					      $symb,$domain,$username);
 4812:                 if ($wgt) {
 4813:                     $entries{$fields{$dest}}=~s/\s//g;
 4814:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4815:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4816:                                           : 'correct_by_override';
 4817:                     if ($pcr>1) {
 4818:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4819:                     }
 4820:                     $grades{"resource.$part.awarded"}=$pcr;
 4821:                     $grades{"resource.$part.solved"}=$award;
 4822:                     $points{$part}=1;
 4823:                 } else {
 4824:                     $error_msg = "<br />" .
 4825:                         &mt("Some point values were assigned"
 4826:                             ." for problems with a weight "
 4827:                             ."of zero. These values were "
 4828:                             ."ignored.");
 4829:                 }
 4830: 	    } else {
 4831: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4832: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4833: 		my $store_key=$dest;
 4834: 		$store_key=~s/^stores/resource/;
 4835: 		$store_key=~s/_/\./g;
 4836: 		$grades{$store_key}=$entries{$fields{$dest}};
 4837: 	    }
 4838: 	}
 4839: 	if (! %grades) { 
 4840:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4841:         } else {
 4842: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4843: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4844: 					   $env{'request.course.id'},
 4845: 					   $domain,$username);
 4846: 	   if ($result eq 'ok') {
 4847: 	      $request->print('.');
 4848: # Remove from grading queue
 4849:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4850:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4851:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4852:                                              $domain,$username);
 4853: 	   } else {
 4854: 	      $request->print("<p><span class=\"LC_error\">".
 4855:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4856:                                   "$username:$domain",$result)."</span></p>");
 4857: 	   }
 4858: 	   $request->rflush();
 4859: 	   $countdone++;
 4860:         }
 4861:     }
 4862:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4863:     if (@warnings) {
 4864:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4865:         $request->print(join(', ',@warnings));
 4866:     }
 4867:     if (@skipped) {
 4868: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4869:         $request->print(join(', ',@skipped));
 4870:     }
 4871:     if (@notallowed) {
 4872: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4873: 	$request->print(join(', ',@notallowed));
 4874:     }
 4875:     $request->print("<br />\n");
 4876:     $request->print(&show_grading_menu_form($symb));
 4877:     return $error_msg;
 4878: }
 4879: #------------- end of section for handling csv file upload ---------
 4880: #
 4881: #-------------------------------------------------------------------
 4882: #
 4883: #-------------- Next few routines handle grading by page/sequence
 4884: #
 4885: #--- Select a page/sequence and a student to grade
 4886: sub pickStudentPage {
 4887:     my ($request) = shift;
 4888: 
 4889:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4890:     &js_escape(\$alertmsg);
 4891:     $request->print(<<LISTJAVASCRIPT);
 4892: <script type="text/javascript" language="javascript">
 4893: 
 4894: function checkPickOne(formname) {
 4895:     if (radioSelection(formname.student) == null) {
 4896: 	alert("$alertmsg");
 4897: 	return;
 4898:     }
 4899:     ptr = pullDownSelection(formname.selectpage);
 4900:     formname.page.value = formname["page"+ptr].value;
 4901:     formname.title.value = formname["title"+ptr].value;
 4902:     formname.submit();
 4903: }
 4904: 
 4905: </script>
 4906: LISTJAVASCRIPT
 4907:     &commonJSfunctions($request);
 4908:     my ($symb) = &get_symb($request);
 4909:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4910:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4911:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4912: 
 4913:     my $result='<h3><span class="LC_info">&nbsp;'.
 4914: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4915: 
 4916:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4917:     my $map_error;
 4918:     my ($titles,$symbx) = &getSymbMap($map_error);
 4919:     if ($map_error) {
 4920:         $request->print(&navmap_errormsg());
 4921:         return; 
 4922:     }
 4923:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4924: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4925: #    my $type=($curpage =~ /\.(page|sequence)/);
 4926:     my $select = '<select name="selectpage">'."\n";
 4927:     my $ctr=0;
 4928:     foreach (@$titles) {
 4929: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4930: 	$select.='<option value="'.$ctr.'" '.
 4931: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4932: 	    '>'.$showtitle.'</option>'."\n";
 4933: 	$ctr++;
 4934:     }
 4935:     $select.= '</select>';
 4936:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4937: 
 4938:     $ctr=0;
 4939:     foreach (@$titles) {
 4940: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4941: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4942: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4943: 	$ctr++;
 4944:     }
 4945:     $result.='<input type="hidden" name="page" />'."\n".
 4946: 	'<input type="hidden" name="title" />'."\n";
 4947: 
 4948:     my $options =
 4949: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4950: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4951:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4952: 
 4953:     $options =
 4954: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4955: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4956: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4957:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4958:     
 4959:     $result.=&build_section_inputs();
 4960:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4961:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4962: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4963: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4964: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4965: 
 4966:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4967: 
 4968:     $result.='&nbsp;<input type="button" '.
 4969:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4970: 
 4971:     $request->print($result);
 4972: 
 4973:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4974: 	&Apache::loncommon::start_data_table().
 4975: 	&Apache::loncommon::start_data_table_header_row().
 4976: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4977: 	'<th>'.&nameUserString('header').'</th>'.
 4978: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4979: 	'<th>'.&nameUserString('header').'</th>'.
 4980: 	&Apache::loncommon::end_data_table_header_row();
 4981:  
 4982:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4983:     my $ptr = 1;
 4984:     foreach my $student (sort 
 4985: 			 {
 4986: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4987: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4988: 			     }
 4989: 			     return $a cmp $b;
 4990: 			 } (keys(%$fullname))) {
 4991: 	my ($uname,$udom) = split(/:/,$student);
 4992: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4993:                                   : '</td>');
 4994: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4995: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4996: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4997: 	$studentTable.=
 4998: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4999:                          : '');
 5000: 	$ptr++;
 5001:     }
 5002:     if ($ptr%2 == 0) {
 5003: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5004: 	    &Apache::loncommon::end_data_table_row();
 5005:     }
 5006:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5007:     $studentTable.='<input type="button" '.
 5008:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5009: 
 5010:     $studentTable.=&show_grading_menu_form($symb);
 5011:     $request->print($studentTable);
 5012: 
 5013:     return '';
 5014: }
 5015: 
 5016: sub getSymbMap {
 5017:     my ($map_error) = @_;
 5018:     my $navmap = Apache::lonnavmaps::navmap->new();
 5019:     unless (ref($navmap)) {
 5020:         if (ref($map_error)) {
 5021:             $$map_error = 'navmap';
 5022:         }
 5023:         return;
 5024:     }
 5025:     my %symbx = ();
 5026:     my @titles = ();
 5027:     my $minder = 0;
 5028: 
 5029:     # Gather every sequence that has problems.
 5030:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5031: 					       1,0,1);
 5032:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5033: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 5034: 	    my $title = $minder.'.'.
 5035: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5036: 	    push(@titles, $title); # minder in case two titles are identical
 5037: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5038: 	    $minder++;
 5039: 	}
 5040:     }
 5041:     return \@titles,\%symbx;
 5042: }
 5043: 
 5044: #
 5045: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5046: sub displayPage {
 5047:     my ($request) = shift;
 5048: 
 5049:     my ($symb) = &get_symb($request);
 5050:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5051:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5052:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5053:     my $pageTitle = $env{'form.page'};
 5054:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5055:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5056:     my $usec=$classlist->{$env{'form.student'}}[5];
 5057: 
 5058:     #need to make sure we have the correct data for later EXT calls, 
 5059:     #thus invalidate the cache
 5060:     &Apache::lonnet::devalidatecourseresdata(
 5061:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5062:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5063:     &Apache::lonnet::clear_EXT_cache_status();
 5064: 
 5065:     if (!&canview($usec)) {
 5066: 	$request->print('<span class="LC_warning">'.
 5067:                         &mt('Unable to view requested student. ([_1])',
 5068:                             $env{'form.student'}).
 5069:                         '</span>');
 5070:         $request->print(&show_grading_menu_form($symb));
 5071:         return;
 5072:     }
 5073:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5074:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5075: 	'</h3>'."\n";
 5076:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5077:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5078: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5079:     } else {
 5080: 	delete($env{'form.CODE'});
 5081:     }
 5082:     &sub_page_js($request);
 5083:     $request->print($result);
 5084: 
 5085:     my $navmap = Apache::lonnavmaps::navmap->new();
 5086:     unless (ref($navmap)) {
 5087:         $request->print(&navmap_errormsg());
 5088:         $request->print(&show_grading_menu_form($symb));
 5089:         return;
 5090:     }
 5091:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5092:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5093:     if (!$map) {
 5094: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5095: 	$request->print(&show_grading_menu_form($symb));
 5096: 	return; 
 5097:     }
 5098:     my $iterator = $navmap->getIterator($map->map_start(),
 5099: 					$map->map_finish());
 5100: 
 5101:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5102: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5103: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5104: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5105: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5106: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5107: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5108: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 5109: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 5110: 
 5111:     if (defined($env{'form.CODE'})) {
 5112: 	$studentTable.=
 5113: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5114:     }
 5115:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5116: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5117: 
 5118:     $studentTable.='&nbsp;<span class="LC_info">'.
 5119:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5120:         '</span>'."\n".
 5121: 	&Apache::loncommon::start_data_table().
 5122: 	&Apache::loncommon::start_data_table_header_row().
 5123: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 5124: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5125: 	&Apache::loncommon::end_data_table_header_row();
 5126: 
 5127:     &Apache::lonxml::clear_problem_counter();
 5128:     my ($depth,$question,$prob) = (1,1,1);
 5129:     $iterator->next(); # skip the first BEGIN_MAP
 5130:     my $curRes = $iterator->next(); # for "current resource"
 5131:     while ($depth > 0) {
 5132:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5133:         if($curRes == $iterator->END_MAP) { $depth--; }
 5134: 
 5135:         if (ref($curRes) && $curRes->is_problem()) {
 5136: 	    my $parts = $curRes->parts();
 5137:             my $title = $curRes->compTitle();
 5138: 	    my $symbx = $curRes->symb();
 5139: 	    $studentTable.=
 5140: 		&Apache::loncommon::start_data_table_row().
 5141: 		'<td align="center" valign="top" >'.$prob.
 5142: 		(scalar(@{$parts}) == 1 ? '' 
 5143: 		                        : '<br />('.&mt('[_1]parts',
 5144: 							scalar(@{$parts}).'&nbsp;').')'
 5145: 		 ).
 5146: 		 '</td>';
 5147: 	    $studentTable.='<td valign="top">';
 5148: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5149: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5150: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5151: 					     undef,'both',\%form);
 5152: 	    } else {
 5153: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5154: 		$companswer =~ s|<form(.*?)>||g;
 5155: 		$companswer =~ s|</form>||g;
 5156: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5157: #		    $companswer =~ s/$1/ /ms;
 5158: #		    $request->print('match='.$1."<br />\n");
 5159: #		}
 5160: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5161: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5162: 	    }
 5163: 
 5164: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5165: 
 5166: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5167: 		if ($record{'version'} eq '') {
 5168: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5169: 		} else {
 5170: 		    my %responseType = ();
 5171: 		    foreach my $partid (@{$parts}) {
 5172: 			my @responseIds =$curRes->responseIds($partid);
 5173: 			my @responseType =$curRes->responseType($partid);
 5174: 			my %responseIds;
 5175: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5176: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5177: 			}
 5178: 			$responseType{$partid} = \%responseIds;
 5179: 		    }
 5180: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5181: 
 5182: 		}
 5183: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5184: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5185:                 my $identifier = (&canmodify($usec)? $prob : '');
 5186: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5187: 									$env{'request.course.id'},
 5188: 									'','.submission',undef,
 5189:                                                                         $usec,$identifier);
 5190:  
 5191: 	    }
 5192: 	    if (&canmodify($usec)) {
 5193:             $studentTable.=&gradeBox_start();
 5194: 		foreach my $partid (@{$parts}) {
 5195: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5196: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5197: 		    $question++;
 5198: 		}
 5199:             $studentTable.=&gradeBox_end();
 5200: 		$prob++;
 5201: 	    }
 5202: 	    $studentTable.='</td></tr>';
 5203: 
 5204: 	}
 5205:         $curRes = $iterator->next();
 5206:     }
 5207: 
 5208:     $studentTable.=
 5209:         '</table>'."\n".
 5210:         '<input type="button" value="'.&mt('Save').'" '.
 5211:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5212:         '</form>'."\n";
 5213:     $studentTable.=&show_grading_menu_form($symb);
 5214:     $request->print($studentTable);
 5215: 
 5216:     return '';
 5217: }
 5218: 
 5219: sub displaySubByDates {
 5220:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5221:     my $isCODE=0;
 5222:     my $isTask = ($symb =~/\.task$/);
 5223:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5224:     my $studentTable=&Apache::loncommon::start_data_table().
 5225: 	&Apache::loncommon::start_data_table_header_row().
 5226: 	'<th>'.&mt('Date/Time').'</th>'.
 5227: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5228:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5229: 	'<th>'.&mt('Submission').'</th>'.
 5230: 	'<th>'.&mt('Status').'</th>'.
 5231: 	&Apache::loncommon::end_data_table_header_row();
 5232:     my ($version);
 5233:     my %mark;
 5234:     my %orders;
 5235:     $mark{'correct_by_student'} = $checkIcon;
 5236:     if (!exists($$record{'1:timestamp'})) {
 5237: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5238:     }
 5239: 
 5240:     my $interaction;
 5241:     my $no_increment = 1;
 5242:     my (%lastrndseed,%lasttype);
 5243:     for ($version=1;$version<=$$record{'version'};$version++) {
 5244: 	my $timestamp = 
 5245: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5246: 	if (exists($$record{$version.':resource.0.version'})) {
 5247: 	    $interaction = $$record{$version.':resource.0.version'};
 5248: 	}
 5249:         if ($isTask && $env{'form.previousversion'}) {
 5250:             next unless ($interaction == $env{'form.previousversion'});
 5251:         }
 5252: 	my $where = ($isTask ? "$version:resource.$interaction"
 5253: 		             : "$version:resource");
 5254: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5255: 	    '<td>'.$timestamp.'</td>';
 5256: 	if ($isCODE) {
 5257: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5258: 	}
 5259:         if ($isTask) {
 5260:             $studentTable.='<td>'.$interaction.'</td>';
 5261:         }
 5262: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5263: 	my @displaySub = ();
 5264: 	foreach my $partid (@{$parts}) {
 5265:             my ($hidden,$type);
 5266:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5267:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5268:                 $hidden = 1;
 5269:             }
 5270: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 5271: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5272: 	    
 5273: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5274: 	    my $display_part=&get_display_part($partid,$symb);
 5275: 	    foreach my $matchKey (@matchKey) {
 5276: 		if (exists($$record{$version.':'.$matchKey}) &&
 5277: 		    $$record{$version.':'.$matchKey} ne '') {
 5278:                     
 5279: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5280: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5281:                     $displaySub[0].='<span class="LC_nobreak">';
 5282:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5283:                                    .' <span class="LC_internal_info">'
 5284:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5285:                                    .'</span>'
 5286:                                    .' <b>';
 5287:                     if ($hidden) {
 5288:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5289:                     } else {
 5290:                         my ($trial,$rndseed,$newvariation);
 5291:                         if ($type eq 'randomizetry') {
 5292:                             $trial = $$record{"$where.$partid.tries"};
 5293:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5294:                         }
 5295: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5296: 			    $displaySub[0].=&mt('Trial not counted');
 5297: 		        } else {
 5298: 			    $displaySub[0].=&mt('Trial: [_1]',
 5299: 					    $$record{"$where.$partid.tries"});
 5300:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5301:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5302:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5303:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5304:                                 }
 5305:                             }
 5306:                             $lastrndseed{$partid} = $rndseed;
 5307:                             $lasttype{$partid} = $type;
 5308: 		        }
 5309: 		        my $responseType=($isTask ? 'Task'
 5310:                                               : $responseType->{$partid}->{$responseId});
 5311: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5312: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5313: 			    $orders{$partid}->{$responseId}=
 5314: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5315:                                            $no_increment,$type,$trial,$rndseed);
 5316: 		        }
 5317: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5318: 		        $displaySub[0].='&nbsp; '.
 5319: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5320:                     }
 5321: 		}
 5322: 	    }
 5323: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5324: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5325: 				    $$record{"$where.$partid.checkedin"},
 5326: 				    $$record{"$where.$partid.checkedin.slot"}).
 5327: 					'<br />';
 5328: 	    }
 5329: 	    if (exists $$record{"$where.$partid.award"}) {
 5330: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5331: 		    lc($$record{"$where.$partid.award"}).' '.
 5332: 		    $mark{$$record{"$where.$partid.solved"}}.
 5333: 		    '<br />';
 5334: 	    }
 5335: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5336: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5337: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5338: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5339: 		$displaySub[2].=
 5340: 		    $$record{"$version:resource.$partid.regrader"}.
 5341: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5342: 	    }
 5343: 	}
 5344: 	# needed because old essay regrader has not parts info
 5345: 	if (exists $$record{"$version:resource.regrader"}) {
 5346: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5347: 	}
 5348: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5349: 	if ($displaySub[2]) {
 5350: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5351: 	}
 5352: 	$studentTable.='&nbsp;</td>'.
 5353: 	    &Apache::loncommon::end_data_table_row();
 5354:     }
 5355:     $studentTable.=&Apache::loncommon::end_data_table();
 5356:     return $studentTable;
 5357: }
 5358: 
 5359: sub updateGradeByPage {
 5360:     my ($request) = shift;
 5361: 
 5362:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5363:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5364:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5365:     my $pageTitle = $env{'form.page'};
 5366:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5367:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5368:     my $usec=$classlist->{$env{'form.student'}}[5];
 5369:     if (!&canmodify($usec)) {
 5370: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5371: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5372: 	return;
 5373:     }
 5374:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5375:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5376: 	'</h3>'."\n";
 5377: 
 5378:     $request->print($result);
 5379: 
 5380: 
 5381:     my $navmap = Apache::lonnavmaps::navmap->new();
 5382:     unless (ref($navmap)) {
 5383:         $request->print(&navmap_errormsg());
 5384:         return;
 5385:     }
 5386:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5387:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5388:     if (!$map) {
 5389: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5390: 	my ($symb)=&get_symb($request);
 5391: 	$request->print(&show_grading_menu_form($symb));
 5392: 	return; 
 5393:     }
 5394:     my $iterator = $navmap->getIterator($map->map_start(),
 5395: 					$map->map_finish());
 5396: 
 5397:     my $studentTable=
 5398: 	&Apache::loncommon::start_data_table().
 5399: 	&Apache::loncommon::start_data_table_header_row().
 5400: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5401: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5402: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5403: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5404: 	&Apache::loncommon::end_data_table_header_row();
 5405: 
 5406:     $iterator->next(); # skip the first BEGIN_MAP
 5407:     my $curRes = $iterator->next(); # for "current resource"
 5408:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5409:     while ($depth > 0) {
 5410:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5411:         if($curRes == $iterator->END_MAP) { $depth--; }
 5412: 
 5413:         if (ref($curRes) && $curRes->is_problem()) {
 5414: 	    my $parts = $curRes->parts();
 5415:             my $title = $curRes->compTitle();
 5416: 	    my $symbx = $curRes->symb();
 5417: 	    $studentTable.=
 5418: 		&Apache::loncommon::start_data_table_row().
 5419: 		'<td align="center" valign="top" >'.$prob.
 5420: 		(scalar(@{$parts}) == 1 ? '' 
 5421:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5422: 		.')').'</td>';
 5423: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5424: 
 5425: 	    my %newrecord=();
 5426: 	    my @displayPts=();
 5427:             my %aggregate = ();
 5428:             my $aggregateflag = 0;
 5429:             if ($env{'form.HIDE'.$prob}) {
 5430:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5431:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5432:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5433:                 $hideflag += $numchgs;
 5434:             }
 5435: 	    foreach my $partid (@{$parts}) {
 5436: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5437: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5438: 
 5439: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5440: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5441: 		my $partial = $newpts/$wgt;
 5442: 		my $score;
 5443: 		if ($partial > 0) {
 5444: 		    $score = 'correct_by_override';
 5445: 		} elsif ($newpts ne '') { #empty is taken as 0
 5446: 		    $score = 'incorrect_by_override';
 5447: 		}
 5448: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5449: 		if ($dropMenu eq 'excused') {
 5450: 		    $partial = '';
 5451: 		    $score = 'excused';
 5452: 		} elsif ($dropMenu eq 'reset status'
 5453: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5454: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5455: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5456: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5457: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5458: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5459: 		    $changeflag++;
 5460: 		    $newpts = '';
 5461:                     
 5462:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5463:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5464:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5465:                     if ($aggtries > 0) {
 5466:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5467:                         $aggregateflag = 1;
 5468:                     }
 5469: 		}
 5470: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5471: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5472: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5473: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5474: 		    '&nbsp;<br />';
 5475: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5476: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5477: 		    '&nbsp;<br />';
 5478: 		$question++;
 5479: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5480: 
 5481: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5482: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5483: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5484: 		    if (scalar(keys(%newrecord)) > 0);
 5485: 
 5486: 		$changeflag++;
 5487: 	    }
 5488: 	    if (scalar(keys(%newrecord)) > 0) {
 5489: 		my %record = 
 5490: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5491: 					     $udom,$uname);
 5492: 
 5493: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5494: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5495: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5496: 		    $newrecord{'resource.CODE'} = '';
 5497: 		}
 5498: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5499: 					$udom,$uname);
 5500: 		%record = &Apache::lonnet::restore($symbx,
 5501: 						   $env{'request.course.id'},
 5502: 						   $udom,$uname);
 5503: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5504: 					     $cdom,$cnum,$udom,$uname);
 5505: 	    }
 5506: 	    
 5507:             if ($aggregateflag) {
 5508:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5509:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5510:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5511:             }
 5512: 
 5513: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5514: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5515: 		&Apache::loncommon::end_data_table_row();
 5516: 
 5517: 	    $prob++;
 5518: 	}
 5519:         $curRes = $iterator->next();
 5520:     }
 5521: 
 5522:     $studentTable.=&Apache::loncommon::end_data_table();
 5523:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5524:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5525: 		  &mt('The scores were changed for [quant,_1,problem].',
 5526: 		  $changeflag).'<br />');
 5527:     my $hidemsg=($hideflag == 0 ? '' :
 5528:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5529:                      $hideflag).'<br />');
 5530:     $request->print($hidemsg.$grademsg.$studentTable);
 5531: 
 5532:     return '';
 5533: }
 5534: 
 5535: #-------- end of section for handling grading by page/sequence ---------
 5536: #
 5537: #-------------------------------------------------------------------
 5538: 
 5539: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5540: #
 5541: #------ start of section for handling grading by page/sequence ---------
 5542: 
 5543: =pod
 5544: 
 5545: =head1 Bubble sheet grading routines
 5546: 
 5547:   For this documentation:
 5548: 
 5549:    'scanline' refers to the full line of characters
 5550:    from the file that we are parsing that represents one entire sheet
 5551: 
 5552:    'bubble line' refers to the data
 5553:    representing the line of bubbles that are on the physical bubblesheet
 5554: 
 5555: 
 5556: The overall process is that a scanned in bubblesheet data is uploaded
 5557: into a course. When a user wants to grade, they select a
 5558: sequence/folder of resources, a file of bubblesheet info, and pick
 5559: one of the predefined configurations for what each scanline looks
 5560: like.
 5561: 
 5562: Next each scanline is checked for any errors of either 'missing
 5563: bubbles' (it's an error because it may have been mis-scanned
 5564: because too light bubbling), 'double bubble' (each bubble line should
 5565: have no more than one letter picked), invalid or duplicated CODE,
 5566: invalid student/employee ID
 5567: 
 5568: If the CODE option is used that determines the randomization of the
 5569: homework problems, either way the student/employee ID is looked up into a
 5570: username:domain.
 5571: 
 5572: During the validation phase the instructor can choose to skip scanlines. 
 5573: 
 5574: After the validation phase, there are now 3 bubblesheet files
 5575: 
 5576:   scantron_original_filename (unmodified original file)
 5577:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5578:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5579: 
 5580: Also there is a separate hash nohist_scantrondata that contains extra
 5581: correction information that isn't representable in the bubblesheet
 5582: file (see &scantron_getfile() for more information)
 5583: 
 5584: After all scanlines are either valid, marked as valid or skipped, then
 5585: foreach line foreach problem in the picked sequence, an ssi request is
 5586: made that simulates a user submitting their selected letter(s) against
 5587: the homework problem.
 5588: 
 5589: =over 4
 5590: 
 5591: 
 5592: 
 5593: =item defaultFormData
 5594: 
 5595:   Returns html hidden inputs used to hold context/default values.
 5596: 
 5597:  Arguments:
 5598:   $symb - $symb of the current resource 
 5599: 
 5600: =cut
 5601: 
 5602: sub defaultFormData {
 5603:     my ($symb)=@_;
 5604:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5605:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5606:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5607: }
 5608: 
 5609: 
 5610: =pod 
 5611: 
 5612: =item getSequenceDropDown
 5613: 
 5614:    Return html dropdown of possible sequences to grade
 5615:  
 5616:  Arguments:
 5617:    $symb - $symb of the current resource
 5618:    $map_error - ref to scalar which will container error if
 5619:                 $navmap object is unavailable in &getSymbMap().
 5620: 
 5621: =cut
 5622: 
 5623: sub getSequenceDropDown {
 5624:     my ($symb,$map_error)=@_;
 5625:     my $result='<select name="selectpage">'."\n";
 5626:     my ($titles,$symbx) = &getSymbMap($map_error);
 5627:     if (ref($map_error)) {
 5628:         return if ($$map_error);
 5629:     }
 5630:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5631:     my $ctr=0;
 5632:     foreach (@$titles) {
 5633: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5634: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5635: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5636: 	    '>'.$showtitle.'</option>'."\n";
 5637: 	$ctr++;
 5638:     }
 5639:     $result.= '</select>';
 5640:     return $result;
 5641: }
 5642: 
 5643: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5644:                                    # key is zero-based index - 0, 1, 2 ...
 5645: 
 5646: my %first_bubble_line;             # First bubble line no. for each bubble.
 5647: 
 5648: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5649:                                    # matchresponse or rankresponse, where 
 5650:                                    # an individual response can have multiple 
 5651:                                    # lines
 5652: 
 5653: my %responsetype_per_response;     # responsetype for each response
 5654: 
 5655: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5656:                                    # numbered response. Needed when randomorder
 5657:                                    # or randompick are in use. Key is ID, value 
 5658:                                    # is response number.
 5659: 
 5660: # Save and restore the bubble lines array to the form env.
 5661: 
 5662: 
 5663: sub save_bubble_lines {
 5664:     foreach my $line (keys(%bubble_lines_per_response)) {
 5665: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5666: 	$env{"form.scantron.first_bubble_line.$line"} =
 5667: 	    $first_bubble_line{$line};
 5668:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5669:             $subdivided_bubble_lines{$line};
 5670:         $env{"form.scantron.responsetype.$line"} =
 5671:             $responsetype_per_response{$line};
 5672:     }
 5673:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5674:         my $line = $masterseq_id_responsenum{$resid};
 5675:         $env{"form.scantron.residpart.$line"} = $resid;
 5676:     }
 5677: }
 5678: 
 5679: 
 5680: sub restore_bubble_lines {
 5681:     my $line = 0;
 5682:     %bubble_lines_per_response = ();
 5683:     %masterseq_id_responsenum = ();
 5684:     while ($env{"form.scantron.bubblelines.$line"}) {
 5685: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5686: 	$bubble_lines_per_response{$line} = $value;
 5687: 	$first_bubble_line{$line}  =
 5688: 	    $env{"form.scantron.first_bubble_line.$line"};
 5689:         $subdivided_bubble_lines{$line} =
 5690:             $env{"form.scantron.sub_bubblelines.$line"};
 5691:         $responsetype_per_response{$line} =
 5692:             $env{"form.scantron.responsetype.$line"};
 5693:         my $id = $env{"form.scantron.residpart.$line"};
 5694:         $masterseq_id_responsenum{$id} = $line;
 5695: 	$line++;
 5696:     }
 5697: }
 5698: 
 5699: =pod 
 5700: 
 5701: =item scantron_filenames
 5702: 
 5703:    Returns a list of the scantron files in the current course 
 5704: 
 5705: =cut
 5706: 
 5707: sub scantron_filenames {
 5708:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5709:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5710:     my $getpropath = 1;
 5711:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5712:                                                         $cname,$getpropath);
 5713:     my @possiblenames;
 5714:     if (ref($dirlist) eq 'ARRAY') {
 5715:         foreach my $filename (sort(@{$dirlist})) {
 5716: 	    ($filename)=split(/&/,$filename);
 5717: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5718: 	    $filename=~s/^scantron_orig_//;
 5719: 	    push(@possiblenames,$filename);
 5720:         }
 5721:     }
 5722:     return @possiblenames;
 5723: }
 5724: 
 5725: =pod 
 5726: 
 5727: =item scantron_uploads
 5728: 
 5729:    Returns  html drop-down list of scantron files in current course.
 5730: 
 5731:  Arguments:
 5732:    $file2grade - filename to set as selected in the dropdown
 5733: 
 5734: =cut
 5735: 
 5736: sub scantron_uploads {
 5737:     my ($file2grade) = @_;
 5738:     my $result=	'<select name="scantron_selectfile">';
 5739:     $result.="<option></option>";
 5740:     foreach my $filename (sort(&scantron_filenames())) {
 5741: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5742:     }
 5743:     $result.="</select>";
 5744:     return $result;
 5745: }
 5746: 
 5747: =pod 
 5748: 
 5749: =item scantron_scantab
 5750: 
 5751:   Returns html drop down of the scantron formats in the scantronformat.tab
 5752:   file.
 5753: 
 5754: =cut
 5755: 
 5756: sub scantron_scantab {
 5757:     my $result='<select name="scantron_format">'."\n";
 5758:     $result.='<option></option>'."\n";
 5759:     my @lines = &get_scantronformat_file();
 5760:     if (@lines > 0) {
 5761:         foreach my $line (@lines) {
 5762:             next if (($line =~ /^\#/) || ($line eq ''));
 5763: 	    my ($name,$descrip)=split(/:/,$line);
 5764: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5765:         }
 5766:     }
 5767:     $result.='</select>'."\n";
 5768:     return $result;
 5769: }
 5770: 
 5771: =pod
 5772: 
 5773: =item get_scantronformat_file
 5774: 
 5775:   Returns an array containing lines from the scantron format file for
 5776:   the domain of the course.
 5777: 
 5778:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5779:   lines are from this file.
 5780: 
 5781:   Otherwise, if a default.tab has been published in RES space by the 
 5782:   domainconfig user, lines are from this file.
 5783: 
 5784:   Otherwise, fall back to getting lines from the legacy file on the
 5785:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5786: 
 5787: =cut
 5788: 
 5789: sub get_scantronformat_file {
 5790:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5791:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5792:     my $gottab = 0;
 5793:     my @lines;
 5794:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5795:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5796:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5797:             if ($formatfile ne '-1') {
 5798:                 @lines = split("\n",$formatfile,-1);
 5799:                 $gottab = 1;
 5800:             }
 5801:         }
 5802:     }
 5803:     if (!$gottab) {
 5804:         my $confname = $cdom.'-domainconfig';
 5805:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5806:         my $formatfile =  &Apache::lonnet::getfile($default);
 5807:         if ($formatfile ne '-1') {
 5808:             @lines = split("\n",$formatfile,-1);
 5809:             $gottab = 1;
 5810:         }
 5811:     }
 5812:     if (!$gottab) {
 5813:         my @domains = &Apache::lonnet::current_machine_domains();
 5814:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5815:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5816:             @lines = <$fh>;
 5817:             close($fh);
 5818:         } else {
 5819:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5820:             @lines = <$fh>;
 5821:             close($fh);
 5822:         }
 5823:     }
 5824:     return @lines;
 5825: }
 5826: 
 5827: =pod 
 5828: 
 5829: =item scantron_CODElist
 5830: 
 5831:   Returns html drop down of the saved CODE lists from current course,
 5832:   generated from earlier printings.
 5833: 
 5834: =cut
 5835: 
 5836: sub scantron_CODElist {
 5837:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5838:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5839:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5840:     my $namechoice='<option></option>';
 5841:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5842: 	if ($name =~ /^error: 2 /) { next; }
 5843: 	if ($name =~ /^type\0/) { next; }
 5844: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5845:     }
 5846:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5847:     return $namechoice;
 5848: }
 5849: 
 5850: =pod 
 5851: 
 5852: =item scantron_CODEunique
 5853: 
 5854:   Returns the html for "Each CODE to be used once" radio.
 5855: 
 5856: =cut
 5857: 
 5858: sub scantron_CODEunique {
 5859:     my $result='<span class="LC_nobreak">
 5860:                  <label><input type="radio" name="scantron_CODEunique"
 5861:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5862:                 </span>
 5863:                 <span class="LC_nobreak">
 5864:                  <label><input type="radio" name="scantron_CODEunique"
 5865:                         value="no" />'.&mt('No').' </label>
 5866:                 </span>';
 5867:     return $result;
 5868: }
 5869: 
 5870: =pod 
 5871: 
 5872: =item scantron_selectphase
 5873: 
 5874:   Generates the initial screen to start the bubblesheet process.
 5875:   Allows for - starting a grading run.
 5876:              - downloading existing scan data (original, corrected
 5877:                                                 or skipped info)
 5878: 
 5879:              - uploading new scan data
 5880: 
 5881:  Arguments:
 5882:   $r          - The Apache request object
 5883:   $file2grade - name of the file that contain the scanned data to score
 5884: 
 5885: =cut
 5886: 
 5887: sub scantron_selectphase {
 5888:     my ($r,$file2grade) = @_;
 5889:     my ($symb)=&get_symb($r);
 5890:     if (!$symb) {return '';}
 5891:     my $map_error;
 5892:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5893:     if ($map_error) {
 5894:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5895:         return;
 5896:     }
 5897:     my $default_form_data=&defaultFormData($symb);
 5898:     my $grading_menu_button=&show_grading_menu_form($symb);
 5899:     my $file_selector=&scantron_uploads($file2grade);
 5900:     my $format_selector=&scantron_scantab();
 5901:     my $CODE_selector=&scantron_CODElist();
 5902:     my $CODE_unique=&scantron_CODEunique();
 5903:     my $result;
 5904: 
 5905:     $ssi_error = 0;
 5906: 
 5907:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5908:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5909: 
 5910:         # Chunk of form to prompt for a scantron file upload.
 5911: 
 5912:         $r->print('
 5913:     <br />
 5914:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5915:        '.&Apache::loncommon::start_data_table_header_row().'
 5916:             <th>
 5917:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5918:             </th>
 5919:        '.&Apache::loncommon::end_data_table_header_row().'
 5920:        '.&Apache::loncommon::start_data_table_row().'
 5921:             <td>
 5922: ');
 5923:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5924:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5925:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5926:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5927:     &js_escape(\$alertmsg);
 5928:     $r->print('
 5929:               <script type="text/javascript" language="javascript">
 5930:     function checkUpload(formname) {
 5931:         if (formname.upfile.value == "") {
 5932:             alert("'.$alertmsg.'");
 5933:             return false;
 5934:         }
 5935:         formname.submit();
 5936:     }
 5937:               </script>
 5938: 
 5939:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5940:                 '.$default_form_data.'
 5941:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5942:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5943:                 <input name="command" value="scantronupload_save" type="hidden" />
 5944:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5945:                 <br />
 5946:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5947:               </form>
 5948: ');
 5949: 
 5950:         $r->print('
 5951:             </td>
 5952:        '.&Apache::loncommon::end_data_table_row().'
 5953:        '.&Apache::loncommon::end_data_table().'
 5954: ');
 5955:     }
 5956: 
 5957:     # Chunk of form to prompt for a file to grade and how:
 5958: 
 5959:     $result.= '
 5960:     <br />
 5961:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5962:     <input type="hidden" name="command" value="scantron_warning" />
 5963:     '.$default_form_data.'
 5964:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5965:        '.&Apache::loncommon::start_data_table_header_row().'
 5966:             <th colspan="2">
 5967:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5968:             </th>
 5969:        '.&Apache::loncommon::end_data_table_header_row().'
 5970:        '.&Apache::loncommon::start_data_table_row().'
 5971:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5972:        '.&Apache::loncommon::end_data_table_row().'
 5973:        '.&Apache::loncommon::start_data_table_row().'
 5974:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5975:        '.&Apache::loncommon::end_data_table_row().'
 5976:        '.&Apache::loncommon::start_data_table_row().'
 5977:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5978:        '.&Apache::loncommon::end_data_table_row().'
 5979:        '.&Apache::loncommon::start_data_table_row().'
 5980:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5981:        '.&Apache::loncommon::end_data_table_row().'
 5982:        '.&Apache::loncommon::start_data_table_row().'
 5983:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5984:        '.&Apache::loncommon::end_data_table_row().'
 5985:        '.&Apache::loncommon::start_data_table_row().'
 5986: 	    <td> '.&mt('Options:').' </td>
 5987:             <td>
 5988: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5989:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5990:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5991: 	    </td>
 5992:        '.&Apache::loncommon::end_data_table_row().'
 5993:        '.&Apache::loncommon::start_data_table_row().'
 5994:             <td colspan="2">
 5995:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5996:             </td>
 5997:        '.&Apache::loncommon::end_data_table_row().'
 5998:     '.&Apache::loncommon::end_data_table().'
 5999:     </form>
 6000: ';
 6001:    
 6002:     $r->print($result);
 6003: 
 6004:     # Chunk of the form that prompts to view a scoring office file,
 6005:     # corrected file, skipped records in a file.
 6006: 
 6007:     $r->print('
 6008:    <br />
 6009:    <form action="/adm/grades" name="scantron_download">
 6010:      '.$default_form_data.'
 6011:      <input type="hidden" name="command" value="scantron_download" />
 6012:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6013:        '.&Apache::loncommon::start_data_table_header_row().'
 6014:               <th>
 6015:                 &nbsp;'.&mt('Download a scoring office file').'
 6016:               </th>
 6017:        '.&Apache::loncommon::end_data_table_header_row().'
 6018:        '.&Apache::loncommon::start_data_table_row().'
 6019:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6020:                 <br />
 6021:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6022:        '.&Apache::loncommon::end_data_table_row().'
 6023:      '.&Apache::loncommon::end_data_table().'
 6024:    </form>
 6025:    <br />
 6026: ');
 6027: 
 6028:     &Apache::lonpickcode::code_list($r,2);
 6029: 
 6030:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6031:              $default_form_data."\n".
 6032:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6033:              &Apache::loncommon::start_data_table_header_row()."\n".
 6034:              '<th colspan="2">
 6035:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6036:              '</th>'."\n".
 6037:               &Apache::loncommon::end_data_table_header_row()."\n".
 6038:               &Apache::loncommon::start_data_table_row()."\n".
 6039:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6040:               '<td> '.$sequence_selector.' </td>'.
 6041:               &Apache::loncommon::end_data_table_row()."\n".
 6042:               &Apache::loncommon::start_data_table_row()."\n".
 6043:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6044:               '<td> '.$file_selector.' </td>'."\n".
 6045:               &Apache::loncommon::end_data_table_row()."\n".
 6046:               &Apache::loncommon::start_data_table_row()."\n".
 6047:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6048:               '<td> '.$format_selector.' </td>'."\n".
 6049:               &Apache::loncommon::end_data_table_row()."\n".
 6050:               &Apache::loncommon::start_data_table_row()."\n".
 6051:               '<td> '.&mt('Options').' </td>'."\n".
 6052:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6053:               &Apache::loncommon::end_data_table_row()."\n".
 6054:               &Apache::loncommon::start_data_table_row()."\n".
 6055:               '<td colspan="2">'."\n".
 6056:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6057:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6058:               '</td>'."\n".
 6059:               &Apache::loncommon::end_data_table_row()."\n".
 6060:               &Apache::loncommon::end_data_table()."\n".
 6061:               '</form><br />');
 6062:     $r->print($grading_menu_button);
 6063:     return;
 6064: }
 6065: 
 6066: =pod
 6067: 
 6068: =item get_scantron_config
 6069: 
 6070:    Parse and return the scantron configuration line selected as a
 6071:    hash of configuration file fields.
 6072: 
 6073:  Arguments:
 6074:     which - the name of the configuration to parse from the file.
 6075: 
 6076: 
 6077:  Returns:
 6078:             If the named configuration is not in the file, an empty
 6079:             hash is returned.
 6080:     a hash with the fields
 6081:       name         - internal name for the this configuration setup
 6082:       description  - text to display to operator that describes this config
 6083:       CODElocation - if 0 or the string 'none'
 6084:                           - no CODE exists for this config
 6085:                      if -1 || the string 'letter'
 6086:                           - a CODE exists for this config and is
 6087:                             a string of letters
 6088:                      Unsupported value (but planned for future support)
 6089:                           if a positive integer
 6090:                                - The CODE exists as the first n items from
 6091:                                  the question section of the form
 6092:                           if the string 'number'
 6093:                                - The CODE exists for this config and is
 6094:                                  a string of numbers
 6095:       CODEstart   - (only matter if a CODE exists) column in the line where
 6096:                      the CODE starts
 6097:       CODElength  - length of the CODE
 6098:       IDstart     - column where the student/employee ID starts
 6099:       IDlength    - length of the student/employee ID info
 6100:       Qstart      - column where the information from the bubbled
 6101:                     'questions' start
 6102:       Qlength     - number of columns comprising a single bubble line from
 6103:                     the sheet. (usually either 1 or 10)
 6104:       Qon         - either a single character representing the character used
 6105:                     to signal a bubble was chosen in the positional setup, or
 6106:                     the string 'letter' if the letter of the chosen bubble is
 6107:                     in the final, or 'number' if a number representing the
 6108:                     chosen bubble is in the file (1->A 0->J)
 6109:       Qoff        - the character used to represent that a bubble was
 6110:                     left blank
 6111:       PaperID     - if the scanning process generates a unique number for each
 6112:                     sheet scanned the column that this ID number starts in
 6113:       PaperIDlength - number of columns that comprise the unique ID number
 6114:                       for the sheet of paper
 6115:       FirstName   - column that the first name starts in
 6116:       FirstNameLength - number of columns that the first name spans
 6117:  
 6118:       LastName    - column that the last name starts in
 6119:       LastNameLength - number of columns that the last name spans
 6120:       BubblesPerRow - number of bubbles available in each row used to
 6121:                       bubble an answer. (If not specified, 10 assumed).
 6122: 
 6123: =cut
 6124: 
 6125: sub get_scantron_config {
 6126:     my ($which) = @_;
 6127:     my @lines = &get_scantronformat_file();
 6128:     my %config;
 6129:     #FIXME probably should move to XML it has already gotten a bit much now
 6130:     foreach my $line (@lines) {
 6131: 	my ($name,$descrip)=split(/:/,$line);
 6132: 	if ($name ne $which ) { next; }
 6133: 	chomp($line);
 6134: 	my @config=split(/:/,$line);
 6135: 	$config{'name'}=$config[0];
 6136: 	$config{'description'}=$config[1];
 6137: 	$config{'CODElocation'}=$config[2];
 6138: 	$config{'CODEstart'}=$config[3];
 6139: 	$config{'CODElength'}=$config[4];
 6140: 	$config{'IDstart'}=$config[5];
 6141: 	$config{'IDlength'}=$config[6];
 6142: 	$config{'Qstart'}=$config[7];
 6143:  	$config{'Qlength'}=$config[8];
 6144: 	$config{'Qoff'}=$config[9];
 6145: 	$config{'Qon'}=$config[10];
 6146: 	$config{'PaperID'}=$config[11];
 6147: 	$config{'PaperIDlength'}=$config[12];
 6148: 	$config{'FirstName'}=$config[13];
 6149: 	$config{'FirstNamelength'}=$config[14];
 6150: 	$config{'LastName'}=$config[15];
 6151: 	$config{'LastNamelength'}=$config[16];
 6152:         $config{'BubblesPerRow'}=$config[17];
 6153: 	last;
 6154:     }
 6155:     return %config;
 6156: }
 6157: 
 6158: =pod 
 6159: 
 6160: =item username_to_idmap
 6161: 
 6162:     creates a hash keyed by student/employee ID with values of the corresponding
 6163:     student username:domain.
 6164: 
 6165:   Arguments:
 6166: 
 6167:     $classlist - reference to the class list hash. This is a hash
 6168:                  keyed by student name:domain  whose elements are references
 6169:                  to arrays containing various chunks of information
 6170:                  about the student. (See loncoursedata for more info).
 6171: 
 6172:   Returns
 6173:     %idmap - the constructed hash
 6174: 
 6175: =cut
 6176: 
 6177: sub username_to_idmap {
 6178:     my ($classlist)= @_;
 6179:     my %idmap;
 6180:     foreach my $student (keys(%$classlist)) {
 6181:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6182:         unless ($id eq '') {
 6183:             if (!exists($idmap{$id})) {
 6184:                 $idmap{$id} = $student;
 6185:             } else {
 6186:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6187:                 if ($status eq 'Active') {
 6188:                     $idmap{$id} = $student;
 6189:                 }
 6190:             }
 6191:         }
 6192:     }
 6193:     return %idmap;
 6194: }
 6195: 
 6196: =pod
 6197: 
 6198: =item scantron_fixup_scanline
 6199: 
 6200:    Process a requested correction to a scanline.
 6201: 
 6202:   Arguments:
 6203:     $scantron_config   - hash from &get_scantron_config()
 6204:     $scan_data         - hash of correction information 
 6205:                           (see &scantron_getfile())
 6206:     $line              - existing scanline
 6207:     $whichline         - line number of the passed in scanline
 6208:     $field             - type of change to process 
 6209:                          (either 
 6210:                           'ID'     -> correct the student/employee ID
 6211:                           'CODE'   -> correct the CODE
 6212:                           'answer' -> fixup the submitted answers)
 6213:     
 6214:    $args               - hash of additional info,
 6215:                           - 'ID' 
 6216:                                'newid' -> studentID to use in replacement
 6217:                                           of existing one
 6218:                           - 'CODE' 
 6219:                                'CODE_ignore_dup' - set to true if duplicates
 6220:                                                    should be ignored.
 6221: 	                       'CODE' - is new code or 'use_unfound'
 6222:                                         if the existing unfound code should
 6223:                                         be used as is
 6224:                           - 'answer'
 6225:                                'response' - new answer or 'none' if blank
 6226:                                'question' - the bubble line to change
 6227:                                'questionnum' - the question identifier,
 6228:                                                may include subquestion. 
 6229: 
 6230:   Returns:
 6231:     $line - the modified scanline
 6232: 
 6233:   Side effects: 
 6234:     $scan_data - may be updated
 6235: 
 6236: =cut
 6237: 
 6238: 
 6239: sub scantron_fixup_scanline {
 6240:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6241:     if ($field eq 'ID') {
 6242: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6243: 	    return ($line,1,'New value too large');
 6244: 	}
 6245: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6246: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6247: 				     $args->{'newid'});
 6248: 	}
 6249: 	substr($line,$$scantron_config{'IDstart'}-1,
 6250: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6251: 	if ($args->{'newid'}=~/^\s*$/) {
 6252: 	    &scan_data($scan_data,"$whichline.user",
 6253: 		       $args->{'username'}.':'.$args->{'domain'});
 6254: 	}
 6255:     } elsif ($field eq 'CODE') {
 6256: 	if ($args->{'CODE_ignore_dup'}) {
 6257: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6258: 	}
 6259: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6260: 	if ($args->{'CODE'} ne 'use_unfound') {
 6261: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6262: 		return ($line,1,'New CODE value too large');
 6263: 	    }
 6264: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6265: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6266: 	    }
 6267: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6268: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6269: 	}
 6270:     } elsif ($field eq 'answer') {
 6271: 	my $length=$scantron_config->{'Qlength'};
 6272: 	my $off=$scantron_config->{'Qoff'};
 6273: 	my $on=$scantron_config->{'Qon'};
 6274: 	my $answer=${off}x$length;
 6275: 	if ($args->{'response'} eq 'none') {
 6276: 	    &scan_data($scan_data,
 6277: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6278: 	} else {
 6279: 	    if ($on eq 'letter') {
 6280: 		my @alphabet=('A'..'Z');
 6281: 		$answer=$alphabet[$args->{'response'}];
 6282: 	    } elsif ($on eq 'number') {
 6283: 		$answer=$args->{'response'}+1;
 6284: 		if ($answer == 10) { $answer = '0'; }
 6285: 	    } else {
 6286: 		substr($answer,$args->{'response'},1)=$on;
 6287: 	    }
 6288: 	    &scan_data($scan_data,
 6289: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6290: 	}
 6291: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6292: 	substr($line,$where-1,$length)=$answer;
 6293:     }
 6294:     return $line;
 6295: }
 6296: 
 6297: =pod
 6298: 
 6299: =item scan_data
 6300: 
 6301:     Edit or look up  an item in the scan_data hash.
 6302: 
 6303:   Arguments:
 6304:     $scan_data  - The hash (see scantron_getfile)
 6305:     $key        - shorthand of the key to edit (actual key is
 6306:                   scantronfilename_key).
 6307:     $data        - New value of the hash entry.
 6308:     $delete      - If true, the entry is removed from the hash.
 6309: 
 6310:   Returns:
 6311:     The new value of the hash table field (undefined if deleted).
 6312: 
 6313: =cut
 6314: 
 6315: 
 6316: sub scan_data {
 6317:     my ($scan_data,$key,$value,$delete)=@_;
 6318:     my $filename=$env{'form.scantron_selectfile'};
 6319:     if (defined($value)) {
 6320: 	$scan_data->{$filename.'_'.$key} = $value;
 6321:     }
 6322:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6323:     return $scan_data->{$filename.'_'.$key};
 6324: }
 6325: 
 6326: # ----- These first few routines are general use routines.----
 6327: 
 6328: # Return the number of occurences of a pattern in a string.
 6329: 
 6330: sub occurence_count {
 6331:     my ($string, $pattern) = @_;
 6332: 
 6333:     my @matches = ($string =~ /$pattern/g);
 6334: 
 6335:     return scalar(@matches);
 6336: }
 6337: 
 6338: 
 6339: # Take a string known to have digits and convert all the
 6340: # digits into letters in the range J,A..I.
 6341: 
 6342: sub digits_to_letters {
 6343:     my ($input) = @_;
 6344: 
 6345:     my @alphabet = ('J', 'A'..'I');
 6346: 
 6347:     my @input    = split(//, $input);
 6348:     my $output ='';
 6349:     for (my $i = 0; $i < scalar(@input); $i++) {
 6350: 	if ($input[$i] =~ /\d/) {
 6351: 	    $output .= $alphabet[$input[$i]];
 6352: 	} else {
 6353: 	    $output .= $input[$i];
 6354: 	}
 6355:     }
 6356:     return $output;
 6357: }
 6358: 
 6359: =pod 
 6360: 
 6361: =item scantron_parse_scanline
 6362: 
 6363:   Decodes a scanline from the selected scantron file
 6364: 
 6365:  Arguments:
 6366:     line             - The text of the scantron file line to process
 6367:     whichline        - Line number
 6368:     scantron_config  - Hash describing the format of the scantron lines.
 6369:     scan_data        - Hash of extra information about the scanline
 6370:                        (see scantron_getfile for more information)
 6371:     just_header      - True if should not process question answers but only
 6372:                        the stuff to the left of the answers.
 6373:     randomorder      - True if randomorder in use
 6374:     randompick       - True if randompick in use
 6375:     sequence         - Exam folder URL
 6376:     master_seq       - Ref to array containing symbs in exam folder
 6377:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6378:                        (corresponding values are resource objects)
 6379:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6380:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6381:                        are refs to an array of resource objects, ordered
 6382:                        according to order used for CODE, when randomorder
 6383:                        and or randompick are in use.
 6384:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6385:                        for current line to question number used for same question
 6386:                         in "Master Sequence" (as seen by Course Coordinator).
 6387:     startline        - Ref to hash where key is question number (0 is first)
 6388:                        and value is number of first bubble line for current 
 6389:                        student or code-based randompick and/or randomorder.
 6390:     totalref         - Ref of scalar used to score total number of bubble
 6391:                        lines needed for responses in a scan line (used when
 6392:                        randompick in use. 
 6393: 
 6394:  Returns:
 6395:    Hash containing the result of parsing the scanline
 6396: 
 6397:    Keys are all proceeded by the string 'scantron.'
 6398: 
 6399:        CODE    - the CODE in use for this scanline
 6400:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6401:                  by the operator
 6402:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6403:                             CODEs were selected, but the usage has been
 6404:                             forced by the operator
 6405:        ID  - student/employee ID
 6406:        PaperID - if used, the ID number printed on the sheet when the 
 6407:                  paper was scanned
 6408:        FirstName - first name from the sheet
 6409:        LastName  - last name from the sheet
 6410: 
 6411:      if just_header was not true these key may also exist
 6412: 
 6413:        missingerror - a list of bubble ranges that are considered to be answers
 6414:                       to a single question that don't have any bubbles filled in.
 6415:                       Of the form questionnumber:firstbubblenumber:count.
 6416:        doubleerror  - a list of bubble ranges that are considered to be answers
 6417:                       to a single question that have more than one bubble filled in.
 6418:                       Of the form questionnumber::firstbubblenumber:count
 6419:    
 6420:                 In the above, count is the number of bubble responses in the
 6421:                 input line needed to represent the possible answers to the question.
 6422:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6423:                 per line would have count = 2.
 6424: 
 6425:        maxquest     - the number of the last bubble line that was parsed
 6426: 
 6427:        (<number> starts at 1)
 6428:        <number>.answer - zero or more letters representing the selected
 6429:                          letters from the scanline for the bubble line 
 6430:                          <number>.
 6431:                          if blank there was either no bubble or there where
 6432:                          multiple bubbles, (consult the keys missingerror and
 6433:                          doubleerror if this is an error condition)
 6434: 
 6435: =cut
 6436: 
 6437: sub scantron_parse_scanline {
 6438:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6439:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6440:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6441: 
 6442:     my %record;
 6443:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6444:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6445: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6446: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6447: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6448: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6449: 	    $record{'scantron.CODE'}=substr($data,
 6450: 					    $$scantron_config{'CODEstart'}-1,
 6451: 					    $$scantron_config{'CODElength'});
 6452: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6453: 		$record{'scantron.useCODE'}=1;
 6454: 	    }
 6455: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6456: 		$record{'scantron.CODE_ignore_dup'}=1;
 6457: 	    }
 6458: 	} else {
 6459: 	    #FIXME interpret first N questions
 6460: 	}
 6461:     }
 6462:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6463: 				  $$scantron_config{'IDlength'});
 6464:     $record{'scantron.PaperID'}=
 6465: 	substr($data,$$scantron_config{'PaperID'}-1,
 6466: 	       $$scantron_config{'PaperIDlength'});
 6467:     $record{'scantron.FirstName'}=
 6468: 	substr($data,$$scantron_config{'FirstName'}-1,
 6469: 	       $$scantron_config{'FirstNamelength'});
 6470:     $record{'scantron.LastName'}=
 6471: 	substr($data,$$scantron_config{'LastName'}-1,
 6472: 	       $$scantron_config{'LastNamelength'});
 6473:     if ($just_header) { return \%record; }
 6474: 
 6475:     my @alphabet=('A'..'Z');
 6476:     my $questnum=0;
 6477:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6478: 
 6479:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6480:     if ($randompick || $randomorder) {
 6481:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6482:                                          $master_seq,$symb_to_resource,
 6483:                                          $partids_by_symb,$orderedforcode,
 6484:                                          $respnumlookup,$startline);
 6485:         if ($total) {
 6486:             $lastpos = $total*$$scantron_config{'Qlength'};
 6487:         }
 6488:         if (ref($totalref)) {
 6489:             $$totalref = $total;
 6490:         }
 6491:     }
 6492:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6493:     chomp($questions);		# Get rid of any trailing \n.
 6494:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6495:     while (length($questions)) {
 6496:         my $answers_needed;
 6497:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6498:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6499:         } else {
 6500:             $answers_needed = $bubble_lines_per_response{$questnum};
 6501:         }
 6502:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6503:                              || 1;
 6504:         $questnum++;
 6505:         my $quest_id = $questnum;
 6506:         my $currentquest = substr($questions,0,$answer_length);
 6507:         $questions       = substr($questions,$answer_length);
 6508:         if (length($currentquest) < $answer_length) { next; }
 6509: 
 6510:         my $subdivided;
 6511:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6512:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6513:         } else {
 6514:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6515:         }
 6516:         if ($subdivided =~ /,/) {
 6517:             my $subquestnum = 1;
 6518:             my $subquestions = $currentquest;
 6519:             my @subanswers_needed = split(/,/,$subdivided);
 6520:             foreach my $subans (@subanswers_needed) {
 6521:                 my $subans_length =
 6522:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6523:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6524:                 $subquestions   = substr($subquestions,$subans_length);
 6525:                 $quest_id = "$questnum.$subquestnum";
 6526:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6527:                     ($$scantron_config{'Qon'} eq 'number')) {
 6528:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6529:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6530:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6531:                         $randomorder,$randompick,$respnumlookup);
 6532:                 } else {
 6533:                     $ansnum = &scantron_validator_positional($ansnum,
 6534:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6535:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6536:                         $randomorder,$randompick,$respnumlookup);
 6537:                 }
 6538:                 $subquestnum ++;
 6539:             }
 6540:         } else {
 6541:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6542:                 ($$scantron_config{'Qon'} eq 'number')) {
 6543:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6544:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6545:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6546:                     $randomorder,$randompick,$respnumlookup);
 6547:             } else {
 6548:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6549:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6550:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6551:                     $randomorder,$randompick,$respnumlookup);
 6552:             }
 6553:         }
 6554:     }
 6555:     $record{'scantron.maxquest'}=$questnum;
 6556:     return \%record;
 6557: }
 6558: 
 6559: sub get_master_seq {
 6560:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6561:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6562:                    (ref($symb_to_resource) eq 'HASH'));
 6563:     my $resource_error;
 6564:     foreach my $resource (@{$resources}) {
 6565:         my $ressymb;
 6566:         if (ref($resource)) {
 6567:             $ressymb = $resource->symb();
 6568:             push(@{$master_seq},$ressymb);
 6569:             $symb_to_resource->{$ressymb} = $resource;
 6570:         } else {
 6571:             $resource_error = 1;
 6572:             last;
 6573:         }
 6574:     }
 6575:     return $resource_error;
 6576: }
 6577: 
 6578: sub get_respnum_lookups {
 6579:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6580:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6581:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6582:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6583:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6584:                    (ref($startline) eq 'HASH'));
 6585:     my ($user,$scancode);
 6586:     if ((exists($record->{'scantron.CODE'})) &&
 6587:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6588:         $scancode = $record->{'scantron.CODE'};
 6589:     } else {
 6590:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6591:     }
 6592:     my @mapresources =
 6593:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6594:                      $orderedforcode);
 6595:     my $total = 0;
 6596:     my $count = 0;
 6597:     foreach my $resource (@mapresources) {
 6598:         my $id = $resource->id();
 6599:         my $symb = $resource->symb();
 6600:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6601:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6602:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6603:                 if ($respnum ne '') {
 6604:                     $respnumlookup->{$count} = $respnum;
 6605:                     $startline->{$count} = $total;
 6606:                     $total += $bubble_lines_per_response{$respnum};
 6607:                     $count ++;
 6608:                 }
 6609:             }
 6610:         }
 6611:     }
 6612:     return $total;
 6613: }
 6614: 
 6615: sub scantron_validator_lettnum {
 6616:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6617:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6618:         $randompick,$respnumlookup) = @_;
 6619: 
 6620:     # Qon 'letter' implies for each slot in currquest we have:
 6621:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6622:     #    about anything else (esp. a value of Qoff) for missing
 6623:     #    bubbles.
 6624:     #
 6625:     # Qon 'number' implies each slot gives a digit that indexes the
 6626:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6627:     #    and * or ? for double bubbles on a single line.
 6628:     #
 6629: 
 6630:     my $matchon;
 6631:     if ($$scantron_config{'Qon'} eq 'letter') {
 6632:         $matchon = '[A-Z]';
 6633:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6634:         $matchon = '\d';
 6635:     }
 6636:     my $occurrences = 0;
 6637:     my $responsenum = $questnum-1;
 6638:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6639:        $responsenum = $respnumlookup->{$questnum-1}
 6640:     }
 6641:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6642:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6643:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6644:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6645:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6646:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6647:         my @singlelines = split('',$currquest);
 6648:         foreach my $entry (@singlelines) {
 6649:             $occurrences = &occurence_count($entry,$matchon);
 6650:             if ($occurrences > 1) {
 6651:                 last;
 6652:             }
 6653:         }
 6654:     } else {
 6655:         $occurrences = &occurence_count($currquest,$matchon); 
 6656:     }
 6657:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6658:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6659:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6660:             my $bubble = substr($currquest,$ans,1);
 6661:             if ($bubble =~ /$matchon/ ) {
 6662:                 if ($$scantron_config{'Qon'} eq 'number') {
 6663:                     if ($bubble == 0) {
 6664:                         $bubble = 10; 
 6665:                     }
 6666:                     $record->{"scantron.$ansnum.answer"} = 
 6667:                         $alphabet->[$bubble-1];
 6668:                 } else {
 6669:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6670:                 }
 6671:             } else {
 6672:                 $record->{"scantron.$ansnum.answer"}='';
 6673:             }
 6674:             $ansnum++;
 6675:         }
 6676:     } elsif (!defined($currquest)
 6677:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6678:             || (&occurence_count($currquest,$matchon) == 0)) {
 6679:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6680:             $record->{"scantron.$ansnum.answer"}='';
 6681:             $ansnum++;
 6682:         }
 6683:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6684:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6685:         }
 6686:     } else {
 6687:         if ($$scantron_config{'Qon'} eq 'number') {
 6688:             $currquest = &digits_to_letters($currquest);            
 6689:         }
 6690:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6691:             my $bubble = substr($currquest,$ans,1);
 6692:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6693:             $ansnum++;
 6694:         }
 6695:     }
 6696:     return $ansnum;
 6697: }
 6698: 
 6699: sub scantron_validator_positional {
 6700:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6701:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6702:         $randomorder,$randompick,$respnumlookup) = @_;
 6703: 
 6704:     # Otherwise there's a positional notation;
 6705:     # each bubble line requires Qlength items, and there are filled in
 6706:     # bubbles for each case where there 'Qon' characters.
 6707:     #
 6708: 
 6709:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6710: 
 6711:     # If the split only gives us one element.. the full length of the
 6712:     # answer string, no bubbles are filled in:
 6713: 
 6714:     if ($answers_needed eq '') {
 6715:         return;
 6716:     }
 6717: 
 6718:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6719:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6720:             $record->{"scantron.$ansnum.answer"}='';
 6721:             $ansnum++;
 6722:         }
 6723:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6724:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6725:         }
 6726:     } elsif (scalar(@array) == 2) {
 6727:         my $location = length($array[0]);
 6728:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6729:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6730:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6731:             if ($ans eq $line_num) {
 6732:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6733:             } else {
 6734:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6735:             }
 6736:             $ansnum++;
 6737:          }
 6738:     } else {
 6739:         #  If there's more than one instance of a bubble character
 6740:         #  That's a double bubble; with positional notation we can
 6741:         #  record all the bubbles filled in as well as the
 6742:         #  fact this response consists of multiple bubbles.
 6743:         #
 6744:         my $responsenum = $questnum-1;
 6745:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6746:             $responsenum = $respnumlookup->{$questnum-1}
 6747:         }
 6748:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6749:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6750:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6751:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6752:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6753:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6754:             my $doubleerror = 0;
 6755:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6756:                    (!$doubleerror)) {
 6757:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6758:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6759:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6760:                if (length(@currarray) > 2) {
 6761:                    $doubleerror = 1;
 6762:                } 
 6763:             }
 6764:             if ($doubleerror) {
 6765:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6766:             }
 6767:         } else {
 6768:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6769:         }
 6770:         my $item = $ansnum;
 6771:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6772:             $record->{"scantron.$item.answer"} = '';
 6773:             $item ++;
 6774:         }
 6775: 
 6776:         my @ans=@array;
 6777:         my $i=0;
 6778:         my $increment = 0;
 6779:         while ($#ans) {
 6780:             $i+=length($ans[0]) + $increment;
 6781:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6782:             my $bubble = $i%$$scantron_config{'Qlength'};
 6783:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6784:             shift(@ans);
 6785:             $increment = 1;
 6786:         }
 6787:         $ansnum += $answers_needed;
 6788:     }
 6789:     return $ansnum;
 6790: }
 6791: 
 6792: =pod
 6793: 
 6794: =item scantron_add_delay
 6795: 
 6796:    Adds an error message that occurred during the grading phase to a
 6797:    queue of messages to be shown after grading pass is complete
 6798: 
 6799:  Arguments:
 6800:    $delayqueue  - arrary ref of hash ref of error messages
 6801:    $scanline    - the scanline that caused the error
 6802:    $errormesage - the error message
 6803:    $errorcode   - a numeric code for the error
 6804: 
 6805:  Side Effects:
 6806:    updates the $delayqueue to have a new hash ref of the error
 6807: 
 6808: =cut
 6809: 
 6810: sub scantron_add_delay {
 6811:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6812:     push(@$delayqueue,
 6813: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6814: 	  'ecode' => $errorcode }
 6815: 	 );
 6816: }
 6817: 
 6818: =pod
 6819: 
 6820: =item scantron_find_student
 6821: 
 6822:    Finds the username for the current scanline
 6823: 
 6824:   Arguments:
 6825:    $scantron_record - hash result from scantron_parse_scanline
 6826:    $scan_data       - hash of correction information 
 6827:                       (see &scantron_getfile() form more information)
 6828:    $idmap           - hash from &username_to_idmap()
 6829:    $line            - number of current scanline
 6830:  
 6831:   Returns:
 6832:    Either 'username:domain' or undef if unknown
 6833: 
 6834: =cut
 6835: 
 6836: sub scantron_find_student {
 6837:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6838:     my $scanID=$$scantron_record{'scantron.ID'};
 6839:     if ($scanID =~ /^\s*$/) {
 6840:  	return &scan_data($scan_data,"$line.user");
 6841:     }
 6842:     foreach my $id (keys(%$idmap)) {
 6843:  	if (lc($id) eq lc($scanID)) {
 6844:  	    return $$idmap{$id};
 6845:  	}
 6846:     }
 6847:     return undef;
 6848: }
 6849: 
 6850: =pod
 6851: 
 6852: =item scantron_filter
 6853: 
 6854:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6855:    hidden resources was selected
 6856: 
 6857: =cut
 6858: 
 6859: sub scantron_filter {
 6860:     my ($curres)=@_;
 6861: 
 6862:     if (ref($curres) && $curres->is_problem()) {
 6863: 	# if the user has asked to not have either hidden
 6864: 	# or 'randomout' controlled resources to be graded
 6865: 	# don't include them
 6866: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6867: 	    && $curres->randomout) {
 6868: 	    return 0;
 6869: 	}
 6870: 	return 1;
 6871:     }
 6872:     return 0;
 6873: }
 6874: 
 6875: =pod
 6876: 
 6877: =item scantron_process_corrections
 6878: 
 6879:    Gets correction information out of submitted form data and corrects
 6880:    the scanline
 6881: 
 6882: =cut
 6883: 
 6884: sub scantron_process_corrections {
 6885:     my ($r) = @_;
 6886:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6887:     my ($scanlines,$scan_data)=&scantron_getfile();
 6888:     my $classlist=&Apache::loncoursedata::get_classlist();
 6889:     my $which=$env{'form.scantron_line'};
 6890:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6891:     my ($skip,$err,$errmsg);
 6892:     if ($env{'form.scantron_skip_record'}) {
 6893: 	$skip=1;
 6894:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6895: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6896: 	    $env{'form.scantron_domain'};
 6897: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6898: 	($line,$err,$errmsg)=
 6899: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6900: 				     'ID',{'newid'=>$newid,
 6901: 				    'username'=>$env{'form.scantron_username'},
 6902: 				    'domain'=>$env{'form.scantron_domain'}});
 6903:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6904: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6905: 	my $newCODE;
 6906: 	my %args;
 6907: 	if      ($resolution eq 'use_unfound') {
 6908: 	    $newCODE='use_unfound';
 6909: 	} elsif ($resolution eq 'use_found') {
 6910: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6911: 	} elsif ($resolution eq 'use_typed') {
 6912: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6913: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6914: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6915: 	}
 6916: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6917: 	    $args{'CODE_ignore_dup'}=1;
 6918: 	}
 6919: 	$args{'CODE'}=$newCODE;
 6920: 	($line,$err,$errmsg)=
 6921: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6922: 				     'CODE',\%args);
 6923:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6924: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6925: 	    ($line,$err,$errmsg)=
 6926: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6927: 					 $which,'answer',
 6928: 					 { 'question'=>$question,
 6929: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6930:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6931: 	    if ($err) { last; }
 6932: 	}
 6933:     }
 6934:     if ($err) {
 6935: 	$r->print(
 6936:             '<p class="LC_error">'
 6937:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6938:                 $errmsg)
 6939:            .'</p>');
 6940:     } else {
 6941: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6942: 	&scantron_putfile($scanlines,$scan_data);
 6943:     }
 6944: }
 6945: 
 6946: =pod
 6947: 
 6948: =item reset_skipping_status
 6949: 
 6950:    Forgets the current set of remember skipped scanlines (and thus
 6951:    reverts back to considering all lines in the
 6952:    scantron_skipped_<filename> file)
 6953: 
 6954: =cut
 6955: 
 6956: sub reset_skipping_status {
 6957:     my ($scanlines,$scan_data)=&scantron_getfile();
 6958:     &scan_data($scan_data,'remember_skipping',undef,1);
 6959:     &scantron_putfile(undef,$scan_data);
 6960: }
 6961: 
 6962: =pod
 6963: 
 6964: =item start_skipping
 6965: 
 6966:    Marks a scanline to be skipped. 
 6967: 
 6968: =cut
 6969: 
 6970: sub start_skipping {
 6971:     my ($scan_data,$i)=@_;
 6972:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6973:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6974: 	$remembered{$i}=2;
 6975:     } else {
 6976: 	$remembered{$i}=1;
 6977:     }
 6978:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6979: }
 6980: 
 6981: =pod
 6982: 
 6983: =item should_be_skipped
 6984: 
 6985:    Checks whether a scanline should be skipped.
 6986: 
 6987: =cut
 6988: 
 6989: sub should_be_skipped {
 6990:     my ($scanlines,$scan_data,$i)=@_;
 6991:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6992: 	# not redoing old skips
 6993: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6994: 	return 0;
 6995:     }
 6996:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6997: 
 6998:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6999: 	return 0;
 7000:     }
 7001:     return 1;
 7002: }
 7003: 
 7004: =pod
 7005: 
 7006: =item remember_current_skipped
 7007: 
 7008:    Discovers what scanlines are in the scantron_skipped_<filename>
 7009:    file and remembers them into scan_data for later use.
 7010: 
 7011: =cut
 7012: 
 7013: sub remember_current_skipped {
 7014:     my ($scanlines,$scan_data)=&scantron_getfile();
 7015:     my %to_remember;
 7016:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7017: 	if ($scanlines->{'skipped'}[$i]) {
 7018: 	    $to_remember{$i}=1;
 7019: 	}
 7020:     }
 7021: 
 7022:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7023:     &scantron_putfile(undef,$scan_data);
 7024: }
 7025: 
 7026: =pod
 7027: 
 7028: =item check_for_error
 7029: 
 7030:     Checks if there was an error when attempting to remove a specific
 7031:     scantron_.. bubblesheet data file. Prints out an error if
 7032:     something went wrong.
 7033: 
 7034: =cut
 7035: 
 7036: sub check_for_error {
 7037:     my ($r,$result)=@_;
 7038:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7039: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7040:     }
 7041: }
 7042: 
 7043: =pod
 7044: 
 7045: =item scantron_warning_screen
 7046: 
 7047:    Interstitial screen to make sure the operator has selected the
 7048:    correct options before we start the validation phase.
 7049: 
 7050: =cut
 7051: 
 7052: sub scantron_warning_screen {
 7053:     my ($button_text)=@_;
 7054:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7055:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7056:     my $CODElist;
 7057:     if ($scantron_config{'CODElocation'} &&
 7058: 	$scantron_config{'CODEstart'} &&
 7059: 	$scantron_config{'CODElength'}) {
 7060: 	$CODElist=$env{'form.scantron_CODElist'};
 7061: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7062: 	$CODElist=
 7063: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7064: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7065:     }
 7066:     my $lastbubblepoints;
 7067:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7068:         $lastbubblepoints =
 7069:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7070:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7071:     }
 7072:     return ('
 7073: <p>
 7074: <span class="LC_warning">
 7075: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7076: </p>
 7077: <table>
 7078: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7079: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7080: '.$CODElist.$lastbubblepoints.'
 7081: </table>
 7082: <br />
 7083: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 7084: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 7085: 
 7086: <br />
 7087: ');
 7088: }
 7089: 
 7090: =pod
 7091: 
 7092: =item scantron_do_warning
 7093: 
 7094:    Check if the operator has picked something for all required
 7095:    fields. Error out if something is missing.
 7096: 
 7097: =cut
 7098: 
 7099: sub scantron_do_warning {
 7100:     my ($r)=@_;
 7101:     my ($symb)=&get_symb($r);
 7102:     if (!$symb) {return '';}
 7103:     my $default_form_data=&defaultFormData($symb);
 7104:     $r->print(&scantron_form_start().$default_form_data);
 7105:     if ( $env{'form.selectpage'} eq '' ||
 7106: 	 $env{'form.scantron_selectfile'} eq '' ||
 7107: 	 $env{'form.scantron_format'} eq '' ) {
 7108: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7109: 	if ( $env{'form.selectpage'} eq '') {
 7110: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7111: 	} 
 7112: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7113: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7114: 	} 
 7115: 	if ( $env{'form.scantron_format'} eq '') {
 7116: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7117: 	} 
 7118:     } else {
 7119: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 7120:         my $bubbledbyhand=&hand_bubble_option();
 7121: 	$r->print('
 7122: '.$warning.$bubbledbyhand.'
 7123: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7124: <input type="hidden" name="command" value="scantron_validate" />
 7125: ');
 7126:     }
 7127:     $r->print("</form><br />".&show_grading_menu_form($symb));
 7128:     return '';
 7129: }
 7130: 
 7131: =pod
 7132: 
 7133: =item scantron_form_start
 7134: 
 7135:     html hidden input for remembering all selected grading options
 7136: 
 7137: =cut
 7138: 
 7139: sub scantron_form_start {
 7140:     my ($max_bubble)=@_;
 7141:     my $result= <<SCANTRONFORM;
 7142: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7143:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7144:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7145:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7146:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7147:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7148:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7149:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7150:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7151:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7152: SCANTRONFORM
 7153: 
 7154:   my $line = 0;
 7155:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7156:        my $chunk =
 7157: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7158:        $chunk .=
 7159: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7160:        $chunk .= 
 7161:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7162:        $chunk .=
 7163:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7164:        $chunk .=
 7165:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7166:        $result .= $chunk;
 7167:        $line++;
 7168:     }
 7169:     return $result;
 7170: }
 7171: 
 7172: =pod
 7173: 
 7174: =item scantron_validate_file
 7175: 
 7176:     Dispatch routine for doing validation of a bubblesheet data file.
 7177: 
 7178:     Also processes any necessary information resets that need to
 7179:     occur before validation begins (ignore previous corrections,
 7180:     restarting the skipped records processing)
 7181: 
 7182: =cut
 7183: 
 7184: sub scantron_validate_file {
 7185:     my ($r) = @_;
 7186:     my ($symb)=&get_symb($r);
 7187:     if (!$symb) {return '';}
 7188:     my $default_form_data=&defaultFormData($symb);
 7189:     
 7190:     # do the detection of only doing skipped records first before we delete
 7191:     # them when doing the corrections reset
 7192:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7193: 	&reset_skipping_status();
 7194:     }
 7195:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7196: 	&remember_current_skipped();
 7197: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7198:     }
 7199: 
 7200:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7201: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7202: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7203: 	&check_for_error($r,&scantron_remove_scan_data());
 7204: 	$env{'form.scantron_options_ignore'}='done';
 7205:     }
 7206: 
 7207:     if ($env{'form.scantron_corrections'}) {
 7208: 	&scantron_process_corrections($r);
 7209:     }
 7210:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7211:     #get the student pick code ready
 7212:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7213:     my $nav_error;
 7214:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7215:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7216:     if ($nav_error) {
 7217:         $r->print(&navmap_errormsg());
 7218:         return '';
 7219:     }
 7220:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7221:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7222:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7223:     }
 7224:     $r->print($result);
 7225:     
 7226:     my @validate_phases=( 'sequence',
 7227: 			  'ID',
 7228: 			  'CODE',
 7229: 			  'doublebubble',
 7230: 			  'missingbubbles');
 7231:     if (!$env{'form.validatepass'}) {
 7232: 	$env{'form.validatepass'} = 0;
 7233:     }
 7234:     my $currentphase=$env{'form.validatepass'};
 7235: 
 7236: 
 7237:     my $stop=0;
 7238:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7239: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7240: 	$r->rflush();
 7241: 
 7242: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7243: 	{
 7244: 	    no strict 'refs';
 7245: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7246: 	}
 7247:     }
 7248:     if (!$stop) {
 7249: 	my $warning=&scantron_warning_screen('Start Grading');
 7250: 	$r->print(&mt('Validation process complete.').'<br />'.
 7251:                   $warning.
 7252:                   &mt('Perform verification for each student after storage of submissions?').
 7253:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7254:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7255:                   ('&nbsp;'x3).'<label>'.
 7256:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7257:                   '</label></span><br />'.
 7258:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7259:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 7260:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7261:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7262:     } else {
 7263: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7264: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7265:     }
 7266:     if ($stop) {
 7267: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7268: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7269: 	    $r->print(' '.&mt('this error').' <br />');
 7270: 
 7271: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 7272: 	} else {
 7273:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7274: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7275:             } else {
 7276:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7277:             }
 7278: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7279: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7280: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7281: 	}
 7282:     }
 7283:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 7284:     return '';
 7285: }
 7286: 
 7287: 
 7288: =pod
 7289: 
 7290: =item scantron_remove_file
 7291: 
 7292:    Removes the requested bubblesheet data file, makes sure that
 7293:    scantron_original_<filename> is never removed
 7294: 
 7295: 
 7296: =cut
 7297: 
 7298: sub scantron_remove_file {
 7299:     my ($which)=@_;
 7300:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7301:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7302:     my $file='scantron_';
 7303:     if ($which eq 'corrected' || $which eq 'skipped') {
 7304: 	$file.=$which.'_';
 7305:     } else {
 7306: 	return 'refused';
 7307:     }
 7308:     $file.=$env{'form.scantron_selectfile'};
 7309:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7310: }
 7311: 
 7312: 
 7313: =pod
 7314: 
 7315: =item scantron_remove_scan_data
 7316: 
 7317:    Removes all scan_data correction for the requested bubblesheet
 7318:    data file.  (In the case that both the are doing skipped records we need
 7319:    to remember the old skipped lines for the time being so that element
 7320:    persists for a while.)
 7321: 
 7322: =cut
 7323: 
 7324: sub scantron_remove_scan_data {
 7325:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7326:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7327:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7328:     my @todelete;
 7329:     my $filename=$env{'form.scantron_selectfile'};
 7330:     foreach my $key (@keys) {
 7331: 	if ($key=~/^\Q$filename\E_/) {
 7332: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7333: 		$key=~/remember_skipping/) {
 7334: 		next;
 7335: 	    }
 7336: 	    push(@todelete,$key);
 7337: 	}
 7338:     }
 7339:     my $result;
 7340:     if (@todelete) {
 7341: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7342: 				       \@todelete,$cdom,$cname);
 7343:     } else {
 7344: 	$result = 'ok';
 7345:     }
 7346:     return $result;
 7347: }
 7348: 
 7349: 
 7350: =pod
 7351: 
 7352: =item scantron_getfile
 7353: 
 7354:     Fetches the requested bubblesheet data file (all 3 versions), and
 7355:     the scan_data hash
 7356:   
 7357:   Arguments:
 7358:     None
 7359: 
 7360:   Returns:
 7361:     2 hash references
 7362: 
 7363:      - first one has 
 7364:          orig      -
 7365:          corrected -
 7366:          skipped   -  each of which points to an array ref of the specified
 7367:                       file broken up into individual lines
 7368:          count     - number of scanlines
 7369:  
 7370:      - second is the scan_data hash possible keys are
 7371:        ($number refers to scanline numbered $number and thus the key affects
 7372:         only that scanline
 7373:         $bubline refers to the specific bubble line element and the aspects
 7374:         refers to that specific bubble line element)
 7375: 
 7376:        $number.user - username:domain to use
 7377:        $number.CODE_ignore_dup 
 7378:                     - ignore the duplicate CODE error 
 7379:        $number.useCODE
 7380:                     - use the CODE in the scanline as is
 7381:        $number.no_bubble.$bubline
 7382:                     - it is valid that there is no bubbled in bubble
 7383:                       at $number $bubline
 7384:        remember_skipping
 7385:                     - a frozen hash containing keys of $number and values
 7386:                       of either 
 7387:                         1 - we are on a 'do skipped records pass' and plan
 7388:                             on processing this line
 7389:                         2 - we are on a 'do skipped records pass' and this
 7390:                             scanline has been marked to skip yet again
 7391: 
 7392: =cut
 7393: 
 7394: sub scantron_getfile {
 7395:     #FIXME really would prefer a scantron directory
 7396:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7397:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7398:     my $lines;
 7399:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7400: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7401:     my %scanlines;
 7402:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7403:     my $temp=$scanlines{'orig'};
 7404:     $scanlines{'count'}=$#$temp;
 7405: 
 7406:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7407: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7408:     if ($lines eq '-1') {
 7409: 	$scanlines{'corrected'}=[];
 7410:     } else {
 7411: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7412:     }
 7413:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7414: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7415:     if ($lines eq '-1') {
 7416: 	$scanlines{'skipped'}=[];
 7417:     } else {
 7418: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7419:     }
 7420:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7421:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7422:     my %scan_data = @tmp;
 7423:     return (\%scanlines,\%scan_data);
 7424: }
 7425: 
 7426: =pod
 7427: 
 7428: =item lonnet_putfile
 7429: 
 7430:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7431: 
 7432:  Arguments:
 7433:    $contents - data to store
 7434:    $filename - filename to store $contents into
 7435: 
 7436:  Returns:
 7437:    result value from &Apache::lonnet::finishuserfileupload
 7438: 
 7439: =cut
 7440: 
 7441: sub lonnet_putfile {
 7442:     my ($contents,$filename)=@_;
 7443:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7444:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7445:     $env{'form.sillywaytopassafilearound'}=$contents;
 7446:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7447: 
 7448: }
 7449: 
 7450: =pod
 7451: 
 7452: =item scantron_putfile
 7453: 
 7454:     Stores the current version of the bubblesheet data files, and the
 7455:     scan_data hash. (Does not modify the original version only the
 7456:     corrected and skipped versions.
 7457: 
 7458:  Arguments:
 7459:     $scanlines - hash ref that looks like the first return value from
 7460:                  &scantron_getfile()
 7461:     $scan_data - hash ref that looks like the second return value from
 7462:                  &scantron_getfile()
 7463: 
 7464: =cut
 7465: 
 7466: sub scantron_putfile {
 7467:     my ($scanlines,$scan_data) = @_;
 7468:     #FIXME really would prefer a scantron directory
 7469:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7470:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7471:     if ($scanlines) {
 7472: 	my $prefix='scantron_';
 7473: # no need to update orig, shouldn't change
 7474: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7475: #		    $env{'form.scantron_selectfile'});
 7476: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7477: 			$prefix.'corrected_'.
 7478: 			$env{'form.scantron_selectfile'});
 7479: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7480: 			$prefix.'skipped_'.
 7481: 			$env{'form.scantron_selectfile'});
 7482:     }
 7483:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7484: }
 7485: 
 7486: =pod
 7487: 
 7488: =item scantron_get_line
 7489: 
 7490:    Returns the correct version of the scanline
 7491: 
 7492:  Arguments:
 7493:     $scanlines - hash ref that looks like the first return value from
 7494:                  &scantron_getfile()
 7495:     $scan_data - hash ref that looks like the second return value from
 7496:                  &scantron_getfile()
 7497:     $i         - number of the requested line (starts at 0)
 7498: 
 7499:  Returns:
 7500:    A scanline, (either the original or the corrected one if it
 7501:    exists), or undef if the requested scanline should be
 7502:    skipped. (Either because it's an skipped scanline, or it's an
 7503:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7504:    pass.
 7505: 
 7506: =cut
 7507: 
 7508: sub scantron_get_line {
 7509:     my ($scanlines,$scan_data,$i)=@_;
 7510:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7511:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7512:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7513:     return $scanlines->{'orig'}[$i]; 
 7514: }
 7515: 
 7516: =pod
 7517: 
 7518: =item scantron_todo_count
 7519: 
 7520:     Counts the number of scanlines that need processing.
 7521: 
 7522:  Arguments:
 7523:     $scanlines - hash ref that looks like the first return value from
 7524:                  &scantron_getfile()
 7525:     $scan_data - hash ref that looks like the second return value from
 7526:                  &scantron_getfile()
 7527: 
 7528:  Returns:
 7529:     $count - number of scanlines to process
 7530: 
 7531: =cut
 7532: 
 7533: sub get_todo_count {
 7534:     my ($scanlines,$scan_data)=@_;
 7535:     my $count=0;
 7536:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7537: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7538: 	if ($line=~/^[\s\cz]*$/) { next; }
 7539: 	$count++;
 7540:     }
 7541:     return $count;
 7542: }
 7543: 
 7544: =pod
 7545: 
 7546: =item scantron_put_line
 7547: 
 7548:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7549:     data file.
 7550: 
 7551:  Arguments:
 7552:     $scanlines - hash ref that looks like the first return value from
 7553:                  &scantron_getfile()
 7554:     $scan_data - hash ref that looks like the second return value from
 7555:                  &scantron_getfile()
 7556:     $i         - line number to update
 7557:     $newline   - contents of the updated scanline
 7558:     $skip      - if true make the line for skipping and update the
 7559:                  'skipped' file
 7560: 
 7561: =cut
 7562: 
 7563: sub scantron_put_line {
 7564:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7565:     if ($skip) {
 7566: 	$scanlines->{'skipped'}[$i]=$newline;
 7567: 	&start_skipping($scan_data,$i);
 7568: 	return;
 7569:     }
 7570:     $scanlines->{'corrected'}[$i]=$newline;
 7571: }
 7572: 
 7573: =pod
 7574: 
 7575: =item scantron_clear_skip
 7576: 
 7577:    Remove a line from the 'skipped' file
 7578: 
 7579:  Arguments:
 7580:     $scanlines - hash ref that looks like the first return value from
 7581:                  &scantron_getfile()
 7582:     $scan_data - hash ref that looks like the second return value from
 7583:                  &scantron_getfile()
 7584:     $i         - line number to update
 7585: 
 7586: =cut
 7587: 
 7588: sub scantron_clear_skip {
 7589:     my ($scanlines,$scan_data,$i)=@_;
 7590:     if (exists($scanlines->{'skipped'}[$i])) {
 7591: 	undef($scanlines->{'skipped'}[$i]);
 7592: 	return 1;
 7593:     }
 7594:     return 0;
 7595: }
 7596: 
 7597: =pod
 7598: 
 7599: =item scantron_filter_not_exam
 7600: 
 7601:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7602:    filter out resources that are not marked as 'exam' mode
 7603: 
 7604: =cut
 7605: 
 7606: sub scantron_filter_not_exam {
 7607:     my ($curres)=@_;
 7608:     
 7609:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7610: 	# if the user has asked to not have either hidden
 7611: 	# or 'randomout' controlled resources to be graded
 7612: 	# don't include them
 7613: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7614: 	    && $curres->randomout) {
 7615: 	    return 0;
 7616: 	}
 7617: 	return 1;
 7618:     }
 7619:     return 0;
 7620: }
 7621: 
 7622: =pod
 7623: 
 7624: =item scantron_validate_sequence
 7625: 
 7626:     Validates the selected sequence, checking for resource that are
 7627:     not set to exam mode.
 7628: 
 7629: =cut
 7630: 
 7631: sub scantron_validate_sequence {
 7632:     my ($r,$currentphase) = @_;
 7633: 
 7634:     my $navmap=Apache::lonnavmaps::navmap->new();
 7635:     unless (ref($navmap)) {
 7636:         $r->print(&navmap_errormsg());
 7637:         return (1,$currentphase);
 7638:     }
 7639:     my (undef,undef,$sequence)=
 7640: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7641: 
 7642:     my $map=$navmap->getResourceByUrl($sequence);
 7643: 
 7644:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7645:                                     value="ignore" />');
 7646:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7647: 	my @resources=
 7648: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7649: 	if (@resources) {
 7650: 	    $r->print('<p class="LC_warning">'
 7651:                .&mt('Some resources in the sequence currently are not set to'
 7652:                    .' exam mode. Grading these resources currently may not'
 7653:                    .' work correctly.')
 7654:                .'</p>'
 7655:             );
 7656: 	    return (1,$currentphase);
 7657: 	}
 7658:     }
 7659: 
 7660:     return (0,$currentphase+1);
 7661: }
 7662: 
 7663: 
 7664: 
 7665: sub scantron_validate_ID {
 7666:     my ($r,$currentphase) = @_;
 7667:     
 7668:     #get student info
 7669:     my $classlist=&Apache::loncoursedata::get_classlist();
 7670:     my %idmap=&username_to_idmap($classlist);
 7671: 
 7672:     #get scantron line setup
 7673:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7674:     my ($scanlines,$scan_data)=&scantron_getfile();
 7675: 
 7676:     my $nav_error;
 7677:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7678:     if ($nav_error) {
 7679:         $r->print(&navmap_errormsg());
 7680:         return(1,$currentphase);
 7681:     }
 7682: 
 7683:     my %found=('ids'=>{},'usernames'=>{});
 7684:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7685: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7686: 	if ($line=~/^[\s\cz]*$/) { next; }
 7687: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7688: 						 $scan_data);
 7689: 	my $id=$$scan_record{'scantron.ID'};
 7690: 	my $found;
 7691: 	foreach my $checkid (keys(%idmap)) {
 7692: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7693: 	}
 7694: 	if ($found) {
 7695: 	    my $username=$idmap{$found};
 7696: 	    if ($found{'ids'}{$found}) {
 7697: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7698: 					 $line,'duplicateID',$found);
 7699: 		return(1,$currentphase);
 7700: 	    } elsif ($found{'usernames'}{$username}) {
 7701: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7702: 					 $line,'duplicateID',$username);
 7703: 		return(1,$currentphase);
 7704: 	    }
 7705: 	    #FIXME store away line we previously saw the ID on to use above
 7706: 	    $found{'ids'}{$found}++;
 7707: 	    $found{'usernames'}{$username}++;
 7708: 	} else {
 7709: 	    if ($id =~ /^\s*$/) {
 7710: 		my $username=&scan_data($scan_data,"$i.user");
 7711: 		if (defined($username) && $found{'usernames'}{$username}) {
 7712: 		    &scantron_get_correction($r,$i,$scan_record,
 7713: 					     \%scantron_config,
 7714: 					     $line,'duplicateID',$username);
 7715: 		    return(1,$currentphase);
 7716: 		} elsif (!defined($username)) {
 7717: 		    &scantron_get_correction($r,$i,$scan_record,
 7718: 					     \%scantron_config,
 7719: 					     $line,'incorrectID');
 7720: 		    return(1,$currentphase);
 7721: 		}
 7722: 		$found{'usernames'}{$username}++;
 7723: 	    } else {
 7724: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7725: 					 $line,'incorrectID');
 7726: 		return(1,$currentphase);
 7727: 	    }
 7728: 	}
 7729:     }
 7730: 
 7731:     return (0,$currentphase+1);
 7732: }
 7733: 
 7734: 
 7735: sub scantron_get_correction {
 7736:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7737:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7738: #FIXME in the case of a duplicated ID the previous line, probably need
 7739: #to show both the current line and the previous one and allow skipping
 7740: #the previous one or the current one
 7741: 
 7742:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7743:         $r->print(
 7744:             '<p class="LC_warning">'
 7745:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7746:                 "<b>$error</b>",
 7747:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7748:            ."</p> \n");
 7749:     } else {
 7750:         $r->print(
 7751:             '<p class="LC_warning">'
 7752:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7753:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7754:            ."</p> \n");
 7755:     }
 7756:     my $message =
 7757:         '<p>'
 7758:        .&mt('The ID on the form is [_1]',
 7759:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7760:        .'<br />'
 7761:        .&mt('The name on the paper is [_1], [_2]',
 7762:             $$scan_record{'scantron.LastName'},
 7763:             $$scan_record{'scantron.FirstName'})
 7764:        .'</p>';
 7765: 
 7766:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7767:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7768:                            # Array populated for doublebubble or
 7769:     my @lines_to_correct;  # missingbubble errors to build javascript
 7770:                            # to validate radio button checking   
 7771: 
 7772:     if ($error =~ /ID$/) {
 7773: 	if ($error eq 'incorrectID') {
 7774: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7775: 		      "</p>\n");
 7776: 	} elsif ($error eq 'duplicateID') {
 7777: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7778: 	}
 7779: 	$r->print($message);
 7780: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7781: 	$r->print("\n<ul><li> ");
 7782: 	#FIXME it would be nice if this sent back the user ID and
 7783: 	#could do partial userID matches
 7784: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7785: 				       'scantron_username','scantron_domain'));
 7786: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7787: 	$r->print("\n:\n".
 7788: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7789: 
 7790: 	$r->print('</li>');
 7791:     } elsif ($error =~ /CODE$/) {
 7792: 	if ($error eq 'incorrectCODE') {
 7793: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7794: 	} elsif ($error eq 'duplicateCODE') {
 7795: 	    $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");
 7796: 	}
 7797:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7798:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7799:                  ."</p>\n");
 7800: 	$r->print($message);
 7801: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7802: 	$r->print("\n<br /> ");
 7803: 	my $i=0;
 7804: 	if ($error eq 'incorrectCODE' 
 7805: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7806: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7807: 	    if ($closest > 0) {
 7808: 		foreach my $testcode (@{$closest}) {
 7809: 		    my $checked='';
 7810: 		    if (!$i) { $checked=' checked="checked"'; }
 7811: 		    $r->print("
 7812:    <label>
 7813:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7814:        ".&mt("Use the similar CODE [_1] instead.",
 7815: 	    "<b><tt>".$testcode."</tt></b>")."
 7816:     </label>
 7817:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7818: 		    $r->print("\n<br />");
 7819: 		    $i++;
 7820: 		}
 7821: 	    }
 7822: 	}
 7823: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7824: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7825: 	    $r->print("
 7826:     <label>
 7827:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7828:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7829: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7830:     </label>");
 7831: 	    $r->print("\n<br />");
 7832: 	}
 7833: 
 7834: 	$r->print(<<ENDSCRIPT);
 7835: <script type="text/javascript">
 7836: function change_radio(field) {
 7837:     var slct=document.scantronupload.scantron_CODE_resolution;
 7838:     var i;
 7839:     for (i=0;i<slct.length;i++) {
 7840:         if (slct[i].value==field) { slct[i].checked=true; }
 7841:     }
 7842: }
 7843: </script>
 7844: ENDSCRIPT
 7845: 	my $href="/adm/pickcode?".
 7846: 	   "form=".&escape("scantronupload").
 7847: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7848: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7849: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7850: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7851: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7852: 	    $r->print("
 7853:     <label>
 7854:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7855:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7856: 	     "<a target='_blank' href='$href'>","</a>")."
 7857:     </label> 
 7858:     ".&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\')" />'));
 7859: 	    $r->print("\n<br />");
 7860: 	}
 7861: 	$r->print("
 7862:     <label>
 7863:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7864:        ".&mt("Use [_1] as the CODE.",
 7865: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7866: 	$r->print("\n<br /><br />");
 7867:     } elsif ($error eq 'doublebubble') {
 7868: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7869: 
 7870: 	# The form field scantron_questions is acutally a list of line numbers.
 7871: 	# represented by this form so:
 7872: 
 7873: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7874:                                                 $respnumlookup,$startline);
 7875: 
 7876: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7877: 		  $line_list.'" />');
 7878: 	$r->print($message);
 7879: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7880: 	foreach my $question (@{$arg}) {
 7881: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7882:                                                    $scan_record, $error,
 7883:                                                    $randomorder,$randompick,
 7884:                                                    $respnumlookup,$startline);
 7885:             push(@lines_to_correct,@linenums);
 7886: 	}
 7887:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7888:     } elsif ($error eq 'missingbubble') {
 7889: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7890: 	$r->print($message);
 7891: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7892: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7893: 
 7894: 	# The form field scantron_questions is actually a list of line numbers not
 7895: 	# a list of question numbers. Therefore:
 7896: 	#
 7897: 	
 7898: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7899:                                                 $respnumlookup,$startline);
 7900: 
 7901: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7902: 		  $line_list.'" />');
 7903: 	foreach my $question (@{$arg}) {
 7904: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7905:                                                    $scan_record, $error,
 7906:                                                    $randomorder,$randompick,
 7907:                                                    $respnumlookup,$startline);
 7908:             push(@lines_to_correct,@linenums);
 7909: 	}
 7910:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7911:     } else {
 7912: 	$r->print("\n<ul>");
 7913:     }
 7914:     $r->print("\n</li></ul>");
 7915: }
 7916: 
 7917: sub verify_bubbles_checked {
 7918:     my (@ansnums) = @_;
 7919:     my $ansnumstr = join('","',@ansnums);
 7920:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7921:     &js_escape(\$warning);
 7922:     my $output = (<<ENDSCRIPT);
 7923: <script type="text/javascript">
 7924: function verify_bubble_radio(form) {
 7925:     var ansnumArray = new Array ("$ansnumstr");
 7926:     var need_bubble_count = 0;
 7927:     for (var i=0; i<ansnumArray.length; i++) {
 7928:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7929:             var bubble_picked = 0; 
 7930:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7931:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7932:                     bubble_picked = 1;
 7933:                 }
 7934:             }
 7935:             if (bubble_picked == 0) {
 7936:                 need_bubble_count ++;
 7937:             }
 7938:         }
 7939:     }
 7940:     if (need_bubble_count) {
 7941:         alert("$warning");
 7942:         return;
 7943:     }
 7944:     form.submit(); 
 7945: }
 7946: </script>
 7947: ENDSCRIPT
 7948:     return $output;
 7949: }
 7950: 
 7951: =pod
 7952: 
 7953: =item  questions_to_line_list
 7954: 
 7955: Converts a list of questions into a string of comma separated
 7956: line numbers in the answer sheet used by the questions.  This is
 7957: used to fill in the scantron_questions form field.
 7958: 
 7959:   Arguments:
 7960:      questions    - Reference to an array of questions.
 7961:      randomorder  - True if randomorder in use.
 7962:      randompick   - True if randompick in use.
 7963:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7964:                      for current line to question number used for same question
 7965:                      in "Master Seqence" (as seen by Course Coordinator).
 7966:      startline    - Reference to hash where key is question number (0 is first)
 7967:                     and key is number of first bubble line for current student
 7968:                     or code-based randompick and/or randomorder.
 7969: 
 7970: =cut
 7971: 
 7972: 
 7973: sub questions_to_line_list {
 7974:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7975:     my @lines;
 7976: 
 7977:     foreach my $item (@{$questions}) {
 7978:         my $question = $item;
 7979:         my ($first,$count,$last);
 7980:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7981:             $question = $1;
 7982:             my $subquestion = $2;
 7983:             my $responsenum = $question-1;
 7984:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7985:                 $responsenum = $respnumlookup->{$question-1};
 7986:                 if (ref($startline) eq 'HASH') {
 7987:                     $first = $startline->{$question-1} + 1;
 7988:                 }
 7989:             } else {
 7990:                 $first = $first_bubble_line{$responsenum} + 1;
 7991:             }
 7992:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7993:             my $subcount = 1;
 7994:             while ($subcount<$subquestion) {
 7995:                 $first += $subans[$subcount-1];
 7996:                 $subcount ++;
 7997:             }
 7998:             $count = $subans[$subquestion-1];
 7999:         } else {
 8000:             my $responsenum = $question-1;
 8001:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8002:                 $responsenum = $respnumlookup->{$question-1};
 8003:                 if (ref($startline) eq 'HASH') {
 8004:                     $first = $startline->{$question-1} + 1;
 8005:                 }
 8006:             } else {
 8007:                 $first = $first_bubble_line{$responsenum} + 1;
 8008:             }
 8009:             $count   = $bubble_lines_per_response{$responsenum};
 8010:         }
 8011:         $last = $first+$count-1;
 8012:         push(@lines, ($first..$last));
 8013:     }
 8014:     return join(',', @lines);
 8015: }
 8016: 
 8017: =pod 
 8018: 
 8019: =item prompt_for_corrections
 8020: 
 8021: Prompts for a potentially multiline correction to the
 8022: user's bubbling (factors out common code from scantron_get_correction
 8023: for multi and missing bubble cases).
 8024: 
 8025:  Arguments:
 8026:    $r           - Apache request object.
 8027:    $question    - The question number to prompt for.
 8028:    $scan_config - The scantron file configuration hash.
 8029:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8030:    $error       - Type of error
 8031:    $randomorder - True if randomorder in use.
 8032:    $randompick  - True if randompick in use.
 8033:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8034:                     for current line to question number used for same question
 8035:                     in "Master Seqence" (as seen by Course Coordinator).
 8036:    $startline   - Reference to hash where key is question number (0 is first)
 8037:                   and value is number of first bubble line for current student
 8038:                   or code-based randompick and/or randomorder.
 8039: 
 8040:  Implicit inputs:
 8041:    %bubble_lines_per_response   - Starting line numbers for each question.
 8042:                                   Numbered from 0 (but question numbers are from
 8043:                                   1.
 8044:    %first_bubble_line           - Starting bubble line for each question.
 8045:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8046:                                   type problems render as separate sub-questions, 
 8047:                                   in exam mode. This hash contains a 
 8048:                                   comma-separated list of the lines per 
 8049:                                   sub-question.
 8050:    %responsetype_per_response   - essayresponse, formularesponse,
 8051:                                   stringresponse, imageresponse, reactionresponse,
 8052:                                   and organicresponse type problem parts can have
 8053:                                   multiple lines per response if the weight
 8054:                                   assigned exceeds 10.  In this case, only
 8055:                                   one bubble per line is permitted, but more 
 8056:                                   than one line might contain bubbles, e.g.
 8057:                                   bubbling of: line 1 - J, line 2 - J, 
 8058:                                   line 3 - B would assign 22 points.  
 8059: 
 8060: =cut
 8061: 
 8062: sub prompt_for_corrections {
 8063:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8064:         $randompick, $respnumlookup, $startline) = @_;
 8065:     my ($current_line,$lines);
 8066:     my @linenums;
 8067:     my $questionnum = $question;
 8068:     my ($first,$responsenum);
 8069:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8070:         $question = $1;
 8071:         my $subquestion = $2;
 8072:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8073:             $responsenum = $respnumlookup->{$question-1};
 8074:             if (ref($startline) eq 'HASH') {
 8075:                 $first = $startline->{$question-1};
 8076:             }
 8077:         } else {
 8078:             $responsenum = $question-1;
 8079:             $first = $first_bubble_line{$responsenum};
 8080:         }
 8081:         $current_line = $first + 1 ;
 8082:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8083:         my $subcount = 1;
 8084:         while ($subcount<$subquestion) {
 8085:             $current_line += $subans[$subcount-1];
 8086:             $subcount ++;
 8087:         }
 8088:         $lines = $subans[$subquestion-1];
 8089:     } else {
 8090:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8091:             $responsenum = $respnumlookup->{$question-1};
 8092:             if (ref($startline) eq 'HASH') {
 8093:                 $first = $startline->{$question-1};
 8094:             }
 8095:         } else {
 8096:             $responsenum = $question-1;
 8097:             $first = $first_bubble_line{$responsenum};
 8098:         }
 8099:         $current_line = $first + 1;
 8100:         $lines        = $bubble_lines_per_response{$responsenum};
 8101:     }
 8102:     if ($lines > 1) {
 8103:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8104:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8105:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8106:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8107:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8108:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8109:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8110:             $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 />');
 8111:         } else {
 8112:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8113:         }
 8114:     }
 8115:     for (my $i =0; $i < $lines; $i++) {
 8116:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8117: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8118: 	        		  $questionnum,$error,split('', $selected));
 8119:         push(@linenums,$current_line);
 8120: 	$current_line++;
 8121:     }
 8122:     if ($lines > 1) {
 8123: 	$r->print("<hr /><br />");
 8124:     }
 8125:     return @linenums;
 8126: }
 8127: 
 8128: =pod
 8129: 
 8130: =item scantron_bubble_selector
 8131:   
 8132:    Generates the html radiobuttons to correct a single bubble line
 8133:    possibly showing the existing the selected bubbles if known
 8134: 
 8135:  Arguments:
 8136:     $r           - Apache request object
 8137:     $scan_config - hash from &get_scantron_config()
 8138:     $line        - Number of the line being displayed.
 8139:     $questionnum - Question number (may include subquestion)
 8140:     $error       - Type of error.
 8141:     @selected    - Array of bubbles picked on this line.
 8142: 
 8143: =cut
 8144: 
 8145: sub scantron_bubble_selector {
 8146:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8147:     my $max=$$scan_config{'Qlength'};
 8148: 
 8149:     my $scmode=$$scan_config{'Qon'};
 8150:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8151:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8152:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8153:             $max=$$scan_config{'BubblesPerRow'};
 8154:             if (($scmode eq 'number') && ($max > 10)) {
 8155:                 $max = 10;
 8156:             } elsif (($scmode eq 'letter') && $max > 26) {
 8157:                 $max = 26;
 8158:             }
 8159:         } else {
 8160:             $max = 10;
 8161:         }
 8162:     }
 8163: 
 8164:     my @alphabet=('A'..'Z');
 8165:     $r->print(&Apache::loncommon::start_data_table().
 8166:               &Apache::loncommon::start_data_table_row());
 8167:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8168:     for (my $i=0;$i<$max+1;$i++) {
 8169: 	$r->print("\n".'<td align="center">');
 8170: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8171: 	else { $r->print('&nbsp;'); }
 8172: 	$r->print('</td>');
 8173:     }
 8174:     $r->print(&Apache::loncommon::end_data_table_row().
 8175:               &Apache::loncommon::start_data_table_row());
 8176:     for (my $i=0;$i<$max;$i++) {
 8177: 	$r->print("\n".
 8178: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8179: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8180:     }
 8181:     my $nobub_checked = ' ';
 8182:     if ($error eq 'missingbubble') {
 8183:         $nobub_checked = ' checked = "checked" ';
 8184:     }
 8185:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8186: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8187:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8188:               $line.'" value="'.$questionnum.'" /></td>');
 8189:     $r->print(&Apache::loncommon::end_data_table_row().
 8190:               &Apache::loncommon::end_data_table());
 8191: }
 8192: 
 8193: =pod
 8194: 
 8195: =item num_matches
 8196: 
 8197:    Counts the number of characters that are the same between the two arguments.
 8198: 
 8199:  Arguments:
 8200:    $orig - CODE from the scanline
 8201:    $code - CODE to match against
 8202: 
 8203:  Returns:
 8204:    $count - integer count of the number of same characters between the
 8205:             two arguments
 8206: 
 8207: =cut
 8208: 
 8209: sub num_matches {
 8210:     my ($orig,$code) = @_;
 8211:     my @code=split(//,$code);
 8212:     my @orig=split(//,$orig);
 8213:     my $same=0;
 8214:     for (my $i=0;$i<scalar(@code);$i++) {
 8215: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8216:     }
 8217:     return $same;
 8218: }
 8219: 
 8220: =pod
 8221: 
 8222: =item scantron_get_closely_matching_CODEs
 8223: 
 8224:    Cycles through all CODEs and finds the set that has the greatest
 8225:    number of same characters as the provided CODE
 8226: 
 8227:  Arguments:
 8228:    $allcodes - hash ref returned by &get_codes()
 8229:    $CODE     - CODE from the current scanline
 8230: 
 8231:  Returns:
 8232:    2 element list
 8233:     - first elements is number of how closely matching the best fit is 
 8234:       (5 means best set has 5 matching characters)
 8235:     - second element is an arrary ref containing the set of valid CODEs
 8236:       that best fit the passed in CODE
 8237: 
 8238: =cut
 8239: 
 8240: sub scantron_get_closely_matching_CODEs {
 8241:     my ($allcodes,$CODE)=@_;
 8242:     my @CODEs;
 8243:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8244: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8245:     }
 8246: 
 8247:     return ($#CODEs,$CODEs[-1]);
 8248: }
 8249: 
 8250: =pod
 8251: 
 8252: =item get_codes
 8253: 
 8254:    Builds a hash which has keys of all of the valid CODEs from the selected
 8255:    set of remembered CODEs.
 8256: 
 8257:  Arguments:
 8258:   $old_name - name of the set of remembered CODEs
 8259:   $cdom     - domain of the course
 8260:   $cnum     - internal course name
 8261: 
 8262:  Returns:
 8263:   %allcodes - keys are the valid CODEs, values are all 1
 8264: 
 8265: =cut
 8266: 
 8267: sub get_codes {
 8268:     my ($old_name, $cdom, $cnum) = @_;
 8269:     if (!$old_name) {
 8270: 	$old_name=$env{'form.scantron_CODElist'};
 8271:     }
 8272:     if (!$cdom) {
 8273: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8274:     }
 8275:     if (!$cnum) {
 8276: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8277:     }
 8278:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8279: 				    $cdom,$cnum);
 8280:     my %allcodes;
 8281:     if ($result{"type\0$old_name"} eq 'number') {
 8282: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8283:     } else {
 8284: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8285:     }
 8286:     return %allcodes;
 8287: }
 8288: 
 8289: =pod
 8290: 
 8291: =item scantron_validate_CODE
 8292: 
 8293:    Validates all scanlines in the selected file to not have any
 8294:    invalid or underspecified CODEs and that none of the codes are
 8295:    duplicated if this was requested.
 8296: 
 8297: =cut
 8298: 
 8299: sub scantron_validate_CODE {
 8300:     my ($r,$currentphase) = @_;
 8301:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8302:     if ($scantron_config{'CODElocation'} &&
 8303: 	$scantron_config{'CODEstart'} &&
 8304: 	$scantron_config{'CODElength'}) {
 8305: 	if (!defined($env{'form.scantron_CODElist'})) {
 8306: 	    &FIXME_blow_up()
 8307: 	}
 8308:     } else {
 8309: 	return (0,$currentphase+1);
 8310:     }
 8311:     
 8312:     my %usedCODEs;
 8313: 
 8314:     my %allcodes=&get_codes();
 8315: 
 8316:     my $nav_error;
 8317:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8318:     if ($nav_error) {
 8319:         $r->print(&navmap_errormsg());
 8320:         return(1,$currentphase);
 8321:     }
 8322: 
 8323:     my ($scanlines,$scan_data)=&scantron_getfile();
 8324:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8325: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8326: 	if ($line=~/^[\s\cz]*$/) { next; }
 8327: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8328: 						 $scan_data);
 8329: 	my $CODE=$$scan_record{'scantron.CODE'};
 8330: 	my $error=0;
 8331: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8332: 	    &scantron_get_correction($r,$i,$scan_record,
 8333: 				     \%scantron_config,
 8334: 				     $line,'incorrectCODE',\%allcodes);
 8335: 	    return(1,$currentphase);
 8336: 	}
 8337: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8338: 	    && !$$scan_record{'scantron.useCODE'}) {
 8339: 	    &scantron_get_correction($r,$i,$scan_record,
 8340: 				     \%scantron_config,
 8341: 				     $line,'incorrectCODE',\%allcodes);
 8342: 	    return(1,$currentphase);
 8343: 	}
 8344: 	if (exists($usedCODEs{$CODE}) 
 8345: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8346: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8347: 	    &scantron_get_correction($r,$i,$scan_record,
 8348: 				     \%scantron_config,
 8349: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8350: 	    return(1,$currentphase);
 8351: 	}
 8352: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8353:     }
 8354:     return (0,$currentphase+1);
 8355: }
 8356: 
 8357: =pod
 8358: 
 8359: =item scantron_validate_doublebubble
 8360: 
 8361:    Validates all scanlines in the selected file to not have any
 8362:    bubble lines with multiple bubbles marked.
 8363: 
 8364: =cut
 8365: 
 8366: sub scantron_validate_doublebubble {
 8367:     my ($r,$currentphase) = @_;
 8368:     #get student info
 8369:     my $classlist=&Apache::loncoursedata::get_classlist();
 8370:     my %idmap=&username_to_idmap($classlist);
 8371:     my (undef,undef,$sequence)=
 8372:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8373: 
 8374:     #get scantron line setup
 8375:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8376:     my ($scanlines,$scan_data)=&scantron_getfile();
 8377: 
 8378:     my $navmap = Apache::lonnavmaps::navmap->new();
 8379:     unless (ref($navmap)) {
 8380:         $r->print(&navmap_errormsg());
 8381:         return(1,$currentphase);
 8382:     }
 8383:     my $map=$navmap->getResourceByUrl($sequence);
 8384:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8385:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8386:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8387:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8388: 
 8389:     my $nav_error;
 8390:     if (ref($map)) {
 8391:         $randomorder = $map->randomorder();
 8392:         $randompick = $map->randompick();
 8393:         if ($randomorder || $randompick) {
 8394:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8395:             if ($nav_error) {
 8396:                 $r->print(&navmap_errormsg());
 8397:                 return(1,$currentphase);
 8398:             }
 8399:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8400:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8401:         }
 8402:     } else {
 8403:         $r->print(&navmap_errormsg());
 8404:         return(1,$currentphase);
 8405:     }
 8406: 
 8407:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8408:     if ($nav_error) {
 8409:         $r->print(&navmap_errormsg());
 8410:         return(1,$currentphase);
 8411:     }
 8412: 
 8413:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8414: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8415: 	if ($line=~/^[\s\cz]*$/) { next; }
 8416: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8417: 						 $scan_data,undef,\%idmap,$randomorder,
 8418:                                                  $randompick,$sequence,\@master_seq,
 8419:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8420:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8421: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8422: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8423: 				 'doublebubble',
 8424: 				 $$scan_record{'scantron.doubleerror'},
 8425:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8426:     	return (1,$currentphase);
 8427:     }
 8428:     return (0,$currentphase+1);
 8429: }
 8430: 
 8431: 
 8432: sub scantron_get_maxbubble {
 8433:     my ($nav_error,$scantron_config) = @_;
 8434:     if (defined($env{'form.scantron_maxbubble'}) &&
 8435: 	$env{'form.scantron_maxbubble'}) {
 8436: 	&restore_bubble_lines();
 8437: 	return $env{'form.scantron_maxbubble'};
 8438:     }
 8439: 
 8440:     my (undef, undef, $sequence) =
 8441: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8442: 
 8443:     my $navmap=Apache::lonnavmaps::navmap->new();
 8444:     unless (ref($navmap)) {
 8445:         if (ref($nav_error)) {
 8446:             $$nav_error = 1;
 8447:         }
 8448:         return;
 8449:     }
 8450:     my $map=$navmap->getResourceByUrl($sequence);
 8451:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8452:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8453: 
 8454:     &Apache::lonxml::clear_problem_counter();
 8455: 
 8456:     my $uname       = $env{'user.name'};
 8457:     my $udom        = $env{'user.domain'};
 8458:     my $cid         = $env{'request.course.id'};
 8459:     my $total_lines = 0;
 8460:     %bubble_lines_per_response = ();
 8461:     %first_bubble_line         = ();
 8462:     %subdivided_bubble_lines   = ();
 8463:     %responsetype_per_response = ();
 8464:     %masterseq_id_responsenum  = ();
 8465: 
 8466:     my $response_number = 0;
 8467:     my $bubble_line     = 0;
 8468:     foreach my $resource (@resources) {
 8469:         my $resid = $resource->id();
 8470:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8471:                                                           $udom,undef,$bubbles_per_row);
 8472:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8473: 	    foreach my $part_id (@{$parts}) {
 8474:                 my $lines;
 8475: 
 8476: 	        # TODO - make this a persistent hash not an array.
 8477: 
 8478:                 # optionresponse, matchresponse and rankresponse type items 
 8479:                 # render as separate sub-questions in exam mode.
 8480:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8481:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8482:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8483:                     my ($numbub,$numshown);
 8484:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8485:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8486:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8487:                         }
 8488:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8489:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8490:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8491:                         }
 8492:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8493:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8494:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8495:                         }
 8496:                     }
 8497:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8498:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8499:                     }
 8500:                     my $bubbles_per_row =
 8501:                         &bubblesheet_bubbles_per_row($scantron_config);
 8502:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8503:                     if (($numbub % $bubbles_per_row) != 0) {
 8504:                         $inner_bubble_lines++;
 8505:                     }
 8506:                     for (my $i=0; $i<$numshown; $i++) {
 8507:                         $subdivided_bubble_lines{$response_number} .= 
 8508:                             $inner_bubble_lines.',';
 8509:                     }
 8510:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8511:                     $lines = $numshown * $inner_bubble_lines;
 8512:                 } else {
 8513:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8514:                 }
 8515: 
 8516:                 $first_bubble_line{$response_number} = $bubble_line;
 8517: 	        $bubble_lines_per_response{$response_number} = $lines;
 8518:                 $responsetype_per_response{$response_number} = 
 8519:                     $analysis->{$part_id.'.type'};
 8520:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8521: 	        $response_number++;
 8522: 
 8523: 	        $bubble_line +=  $lines;
 8524: 	        $total_lines +=  $lines;
 8525: 	    }
 8526:         }
 8527:     }
 8528:     &Apache::lonnet::delenv('scantron.');
 8529: 
 8530:     &save_bubble_lines();
 8531:     $env{'form.scantron_maxbubble'} =
 8532: 	$total_lines;
 8533:     return $env{'form.scantron_maxbubble'};
 8534: }
 8535: 
 8536: sub bubblesheet_bubbles_per_row {
 8537:     my ($scantron_config) = @_;
 8538:     my $bubbles_per_row;
 8539:     if (ref($scantron_config) eq 'HASH') {
 8540:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8541:     }
 8542:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8543:         $bubbles_per_row = 10;
 8544:     }
 8545:     return $bubbles_per_row;
 8546: }
 8547: 
 8548: sub scantron_validate_missingbubbles {
 8549:     my ($r,$currentphase) = @_;
 8550:     #get student info
 8551:     my $classlist=&Apache::loncoursedata::get_classlist();
 8552:     my %idmap=&username_to_idmap($classlist);
 8553:     my (undef,undef,$sequence)=
 8554:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8555: 
 8556:     #get scantron line setup
 8557:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8558:     my ($scanlines,$scan_data)=&scantron_getfile();
 8559: 
 8560:     my $navmap = Apache::lonnavmaps::navmap->new();
 8561:     unless (ref($navmap)) {
 8562:         $r->print(&navmap_errormsg());
 8563:         return(1,$currentphase);
 8564:     }
 8565: 
 8566:     my $map=$navmap->getResourceByUrl($sequence);
 8567:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8568:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8569:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8570:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8571: 
 8572:     my $nav_error;
 8573:     if (ref($map)) {
 8574:         $randomorder = $map->randomorder();
 8575:         $randompick = $map->randompick();
 8576:         if ($randomorder || $randompick) {
 8577:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8578:             if ($nav_error) {
 8579:                 $r->print(&navmap_errormsg());
 8580:                 return(1,$currentphase);
 8581:             }
 8582:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8583:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8584:         }
 8585:     } else {
 8586:         $r->print(&navmap_errormsg());
 8587:         return(1,$currentphase);
 8588:     }
 8589: 
 8590: 
 8591:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8592:     if ($nav_error) {
 8593:         $r->print(&navmap_errormsg());
 8594:         return(1,$currentphase);
 8595:     }
 8596: 
 8597:     if (!$max_bubble) { $max_bubble=2**31; }
 8598:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8599: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8600: 	if ($line=~/^[\s\cz]*$/) { next; }
 8601:         my $scan_record =
 8602:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8603:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8604:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8605:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8606: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8607: 	my @to_correct;
 8608: 	
 8609: 	# Probably here's where the error is...
 8610: 
 8611: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8612:             my $lastbubble;
 8613:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8614:                 my $question = $1;
 8615:                 my $subquestion = $2;
 8616:                 my ($first,$responsenum);
 8617:                 if ($randomorder || $randompick) {
 8618:                     $responsenum = $respnumlookup{$question-1};
 8619:                     $first = $startline{$question-1};
 8620:                 } else {
 8621:                     $responsenum = $question-1;
 8622:                     $first = $first_bubble_line{$responsenum};
 8623:                 }
 8624:                 if (!defined($first)) { next; }
 8625:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8626:                 my $subcount = 1;
 8627:                 while ($subcount<$subquestion) {
 8628:                     $first += $subans[$subcount-1];
 8629:                     $subcount ++;
 8630:                 }
 8631:                 my $count = $subans[$subquestion-1];
 8632:                 $lastbubble = $first + $count;
 8633:             } else {
 8634:                 my ($first,$responsenum);
 8635:                 if ($randomorder || $randompick) {
 8636:                     $responsenum = $respnumlookup{$missing-1};
 8637:                     $first = $startline{$missing-1};
 8638:                 } else {
 8639:                     $responsenum = $missing-1;
 8640:                     $first = $first_bubble_line{$responsenum};
 8641:                 }
 8642:                 if (!defined($first)) { next; }
 8643:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8644:             }
 8645:             if ($lastbubble > $max_bubble) { next; }
 8646: 	    push(@to_correct,$missing);
 8647: 	}
 8648: 	if (@to_correct) {
 8649: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8650: 				     $line,'missingbubble',\@to_correct,
 8651:                                      $randomorder,$randompick,\%respnumlookup,
 8652:                                      \%startline);
 8653: 	    return (1,$currentphase);
 8654: 	}
 8655: 
 8656:     }
 8657:     return (0,$currentphase+1);
 8658: }
 8659: 
 8660: sub hand_bubble_option {
 8661:     my (undef, undef, $sequence) =
 8662:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8663:     return if ($sequence eq '');
 8664:     my $navmap = Apache::lonnavmaps::navmap->new();
 8665:     unless (ref($navmap)) {
 8666:         return;
 8667:     }
 8668:     my $needs_hand_bubbles;
 8669:     my $map=$navmap->getResourceByUrl($sequence);
 8670:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8671:     foreach my $res (@resources) {
 8672:         if (ref($res)) {
 8673:             if ($res->is_problem()) {
 8674:                 my $partlist = $res->parts();
 8675:                 foreach my $part (@{ $partlist }) {
 8676:                     my @types = $res->responseType($part);
 8677:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8678:                         $needs_hand_bubbles = 1;
 8679:                         last;
 8680:                     }
 8681:                 }
 8682:             }
 8683:         }
 8684:     }
 8685:     if ($needs_hand_bubbles) {
 8686:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8687:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8688:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8689:                &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 />').
 8690:                '<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;'.
 8691:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8692:     }
 8693:     return;
 8694: }
 8695: 
 8696: sub scantron_process_students {
 8697:     my ($r) = @_;
 8698: 
 8699:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8700:     my ($symb)=&get_symb($r);
 8701:     if (!$symb) {
 8702: 	return '';
 8703:     }
 8704:     my $default_form_data=&defaultFormData($symb);
 8705: 
 8706:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8707:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8708:     my ($scanlines,$scan_data)=&scantron_getfile();
 8709:     my $classlist=&Apache::loncoursedata::get_classlist();
 8710:     my %idmap=&username_to_idmap($classlist);
 8711:     my $navmap=Apache::lonnavmaps::navmap->new();
 8712:     unless (ref($navmap)) {
 8713:         $r->print(&navmap_errormsg());
 8714:         return '';
 8715:     }
 8716:     my $map=$navmap->getResourceByUrl($sequence);
 8717:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8718:         %grader_randomlists_by_symb);
 8719:     if (ref($map)) {
 8720:         $randomorder = $map->randomorder();
 8721:         $randompick = $map->randompick();
 8722:     } else {
 8723:         $r->print(&navmap_errormsg());
 8724:         return '';
 8725:     }
 8726:     my $nav_error;
 8727:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8728:     if ($randomorder || $randompick) {
 8729:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8730:         if ($nav_error) {
 8731:             $r->print(&navmap_errormsg());
 8732:             return '';
 8733:         }
 8734:     }
 8735:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8736:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8737: 
 8738:     my ($uname,$udom);
 8739:     my $result= <<SCANTRONFORM;
 8740: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8741:   <input type="hidden" name="command" value="scantron_configphase" />
 8742:   $default_form_data
 8743: SCANTRONFORM
 8744:     $r->print($result);
 8745: 
 8746:     my @delayqueue;
 8747:     my (%completedstudents,%scandata);
 8748:     
 8749:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8750:     my $count=&get_todo_count($scanlines,$scan_data);
 8751:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8752:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8753: 					  'Processing first student');
 8754:     $r->print('<br />');
 8755:     my $start=&Time::HiRes::time();
 8756:     my $i=-1;
 8757:     my $started;
 8758: 
 8759:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8760:     if ($nav_error) {
 8761:         $r->print(&navmap_errormsg());
 8762:         return '';
 8763:     }
 8764: 
 8765:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8766:     # the user and return.
 8767: 
 8768:     if ($ssi_error) {
 8769: 	$r->print("</form>");
 8770: 	&ssi_print_error($r);
 8771: 	$r->print(&show_grading_menu_form($symb));
 8772:         &Apache::lonnet::remove_lock($lock);
 8773: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8774:     }
 8775: 
 8776:     my %lettdig = &letter_to_digits();
 8777:     my $numletts = scalar(keys(%lettdig));
 8778:     my %orderedforcode;
 8779: 
 8780:     while ($i<$scanlines->{'count'}) {
 8781:  	($uname,$udom)=('','');
 8782:  	$i++;
 8783:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8784:  	if ($line=~/^[\s\cz]*$/) { next; }
 8785: 	if ($started) {
 8786: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8787: 						     'last student');
 8788: 	}
 8789: 	$started=1;
 8790:         my %respnumlookup = ();
 8791:         my %startline = ();
 8792:         my $total;
 8793:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8794:  						 $scan_data,undef,\%idmap,$randomorder,
 8795:                                                  $randompick,$sequence,\@master_seq,
 8796:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8797:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8798:                                                  \$total);
 8799:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8800:  					      \%idmap,$i)) {
 8801:   	    &scantron_add_delay(\@delayqueue,$line,
 8802:  				'Unable to find a student that matches',1);
 8803:  	    next;
 8804:   	}
 8805:  	if (exists $completedstudents{$uname}) {
 8806:  	    &scantron_add_delay(\@delayqueue,$line,
 8807:  				'Student '.$uname.' has multiple sheets',2);
 8808:  	    next;
 8809:  	}
 8810:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8811:         my $user = $uname.':'.$usec;
 8812:   	($uname,$udom)=split(/:/,$uname);
 8813: 
 8814:         my $scancode;
 8815:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8816:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8817:             $scancode = $scan_record->{'scantron.CODE'};
 8818:         } else {
 8819:             $scancode = '';
 8820:         }
 8821: 
 8822:         my @mapresources = @resources;
 8823:         if ($randomorder || $randompick) {
 8824:             @mapresources =
 8825:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8826:                              \%orderedforcode);
 8827:         }
 8828:         my (%partids_by_symb,$res_error);
 8829:         foreach my $resource (@mapresources) {
 8830:             my $ressymb;
 8831:             if (ref($resource)) {
 8832:                 $ressymb = $resource->symb();
 8833:             } else {
 8834:                 $res_error = 1;
 8835:                 last;
 8836:             }
 8837:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8838:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8839:                 my $currcode;
 8840:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8841:                     $currcode = $scancode;
 8842:                 }
 8843:                 my ($analysis,$parts) =
 8844:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8845:                                               $uname,$udom,undef,$bubbles_per_row,
 8846:                                               $currcode);
 8847:                 $partids_by_symb{$ressymb} = $parts;
 8848:             } else {
 8849:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8850:             }
 8851:         }
 8852: 
 8853:         if ($res_error) {
 8854:             &scantron_add_delay(\@delayqueue,$line,
 8855:                                 'An error occurred while grading student '.$uname,2);
 8856:             next;
 8857:         }
 8858: 
 8859: 	&Apache::lonxml::clear_problem_counter();
 8860:   	&Apache::lonnet::appenv($scan_record);
 8861: 
 8862: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8863: 	    &scantron_putfile($scanlines,$scan_data);
 8864: 	}
 8865: 	
 8866:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8867:                                    \@mapresources,\%partids_by_symb,
 8868:                                    $bubbles_per_row,$randomorder,$randompick,
 8869:                                    \%respnumlookup,\%startline) 
 8870:             eq 'ssi_error') {
 8871:             $ssi_error = 0; # So end of handler error message does not trigger.
 8872:             $r->print("</form>");
 8873:             &ssi_print_error($r);
 8874:             $r->print(&show_grading_menu_form($symb));
 8875:             &Apache::lonnet::remove_lock($lock);
 8876:             return '';      # Why return ''?  Beats me.
 8877:         }
 8878: 
 8879:         if (($scancode) && ($randomorder || $randompick)) {
 8880:             my $parmresult =
 8881:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8882:                                                        '0_examcode',2,$scancode,
 8883:                                                        'string_examcode',$uname,
 8884:                                                        $udom);
 8885:         }
 8886: 	$completedstudents{$uname}={'line'=>$line};
 8887:         if ($env{'form.verifyrecord'}) {
 8888:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8889:             if ($randompick) {
 8890:                 if ($total) {
 8891:                     $lastpos = $total*$scantron_config{'Qlength'};
 8892:                 }
 8893:             }
 8894: 
 8895:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8896:             chomp($studentdata);
 8897:             $studentdata =~ s/\r$//;
 8898:             my $studentrecord = '';
 8899:             my $counter = -1;
 8900:             foreach my $resource (@mapresources) {
 8901:                 my $ressymb = $resource->symb();
 8902:                 ($counter,my $recording) =
 8903:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8904:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8905:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8906:                                              $randompick,\%respnumlookup,\%startline);
 8907:                 $studentrecord .= $recording;
 8908:             }
 8909:             if ($studentrecord ne $studentdata) {
 8910:                 &Apache::lonxml::clear_problem_counter();
 8911:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8912:                                            \@mapresources,\%partids_by_symb,
 8913:                                            $bubbles_per_row,$randomorder,$randompick,
 8914:                                            \%respnumlookup,\%startline)
 8915:                     eq 'ssi_error') {
 8916:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8917:                     $r->print("</form>");
 8918:                     &ssi_print_error($r);
 8919:                     $r->print(&show_grading_menu_form($symb));
 8920:                     &Apache::lonnet::remove_lock($lock);
 8921:                     delete($completedstudents{$uname});
 8922:                     return '';
 8923:                 }
 8924:                 $counter = -1;
 8925:                 $studentrecord = '';
 8926:                 foreach my $resource (@mapresources) {
 8927:                     my $ressymb = $resource->symb();
 8928:                     ($counter,my $recording) =
 8929:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8930:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8931:                                                  \%scantron_config,\%lettdig,$numletts,
 8932:                                                  $randomorder,$randompick,\%respnumlookup,
 8933:                                                  \%startline);
 8934:                     $studentrecord .= $recording;
 8935:                 }
 8936:                 if ($studentrecord ne $studentdata) {
 8937:                     $r->print('<p><span class="LC_warning">');
 8938:                     if ($scancode eq '') {
 8939:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8940:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8941:                     } else {
 8942:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8943:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8944:                     }
 8945:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8946:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8947:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8948:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8949:                               &Apache::loncommon::start_data_table_row().
 8950:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8951:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8952:                               &Apache::loncommon::end_data_table_row().
 8953:                               &Apache::loncommon::start_data_table_row().
 8954:                               '<td>'.&mt('Stored submissions').'</td>'.
 8955:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8956:                               &Apache::loncommon::end_data_table_row().
 8957:                               &Apache::loncommon::end_data_table().'</p>');
 8958:                 } else {
 8959:                     $r->print('<br /><span class="LC_warning">'.
 8960:                              &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 />'.
 8961:                              &mt("As a consequence, this user's submission history records two tries.").
 8962:                                  '</span><br />');
 8963:                 }
 8964:             }
 8965:         }
 8966:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8967:     } continue {
 8968: 	&Apache::lonxml::clear_problem_counter();
 8969: 	&Apache::lonnet::delenv('scantron.');
 8970:     }
 8971:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8972:     &Apache::lonnet::remove_lock($lock);
 8973: #    my $lasttime = &Time::HiRes::time()-$start;
 8974: #    $r->print("<p>took $lasttime</p>");
 8975: 
 8976:     $r->print("</form>");
 8977:     $r->print(&show_grading_menu_form($symb));
 8978:     return '';
 8979: }
 8980: 
 8981: sub graders_resources_pass {
 8982:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8983:         $bubbles_per_row) = @_;
 8984:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8985:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8986:         foreach my $resource (@{$resources}) {
 8987:             my $ressymb = $resource->symb();
 8988:             my ($analysis,$parts) =
 8989:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8990:                                           $env{'user.name'},$env{'user.domain'},
 8991:                                           1,$bubbles_per_row);
 8992:             $grader_partids_by_symb->{$ressymb} = $parts;
 8993:             if (ref($analysis) eq 'HASH') {
 8994:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8995:                     $grader_randomlists_by_symb->{$ressymb} =
 8996:                         $analysis->{'parts_withrandomlist'};
 8997:                 }
 8998:             }
 8999:         }
 9000:     }
 9001:     return;
 9002: }
 9003: 
 9004: =pod
 9005: 
 9006: =item users_order
 9007: 
 9008:   Returns array of resources in current map, ordered based on either CODE,
 9009:   if this is a CODEd exam, or based on student's identity if this is a
 9010:   "NAMEd" exam.
 9011: 
 9012:   Should be used when randomorder and/or randompick applied when the 
 9013:   corresponding exam was printed, prior to students completing bubblesheets 
 9014:   for the version of the exam the student received.
 9015: 
 9016: =cut
 9017: 
 9018: sub users_order  {
 9019:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9020:     my @mapresources;
 9021:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9022:         return @mapresources;
 9023:     }
 9024:     if ($scancode) {
 9025:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9026:             @mapresources = @{$orderedforcode->{$scancode}};
 9027:         } else {
 9028:             $env{'form.CODE'} = $scancode;
 9029:             my $actual_seq =
 9030:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9031:                                                                $master_seq,
 9032:                                                                $user,$scancode,1);
 9033:             if (ref($actual_seq) eq 'ARRAY') {
 9034:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9035:                 if (ref($orderedforcode) eq 'HASH') {
 9036:                     if (@mapresources > 0) {
 9037:                         $orderedforcode->{$scancode} = \@mapresources;
 9038:                     }
 9039:                 }
 9040:             }
 9041:             delete($env{'form.CODE'});
 9042:         }
 9043:     } else {
 9044:         my $actual_seq =
 9045:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9046:                                                            $master_seq,
 9047:                                                            $user,undef,1);
 9048:         if (ref($actual_seq) eq 'ARRAY') {
 9049:             @mapresources =
 9050:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9051:         }
 9052:     }
 9053:     return @mapresources;
 9054: }
 9055: 
 9056: sub grade_student_bubbles {
 9057:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9058:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9059:     my $uselookup = 0;
 9060:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9061:         (ref($startline) eq 'HASH')) {
 9062:         $uselookup = 1;
 9063:     }
 9064: 
 9065:     if (ref($resources) eq 'ARRAY') {
 9066:         my $count = 0;
 9067:         foreach my $resource (@{$resources}) {
 9068:             my $ressymb = $resource->symb();
 9069:             my %form = ('submitted'      => 'scantron',
 9070:                         'grade_target'   => 'grade',
 9071:                         'grade_username' => $uname,
 9072:                         'grade_domain'   => $udom,
 9073:                         'grade_courseid' => $env{'request.course.id'},
 9074:                         'grade_symb'     => $ressymb,
 9075:                         'CODE'           => $scancode
 9076:                        );
 9077:             if ($bubbles_per_row ne '') {
 9078:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9079:             }
 9080:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9081:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9082:             }
 9083:             if (ref($parts) eq 'HASH') {
 9084:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9085:                     foreach my $part (@{$parts->{$ressymb}}) {
 9086:                         if ($uselookup) {
 9087:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9088:                         } else {
 9089:                             $form{'scantron_questnum_start.'.$part} =
 9090:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9091:                         }
 9092:                         $count++;
 9093:                     }
 9094:                 }
 9095:             }
 9096:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9097:             return 'ssi_error' if ($ssi_error);
 9098:             last if (&Apache::loncommon::connection_aborted($r));
 9099:         }
 9100:     }
 9101:     return;
 9102: }
 9103: 
 9104: sub scantron_upload_scantron_data {
 9105:     my ($r)=@_;
 9106:     my $dom = $env{'request.role.domain'};
 9107:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9108:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9109:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9110: 							  'domainid',
 9111: 							  'coursename',$dom);
 9112:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9113:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9114:     my ($symb) = &get_symb($r,1);
 9115:     my $default_form_data=&defaultFormData($symb);
 9116:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9117:     &js_escape(\$nofile_alert);
 9118:     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.");
 9119:     &js_escape(\$nocourseid_alert);
 9120:     $r->print('
 9121: <script type="text/javascript" language="javascript">
 9122:     function checkUpload(formname) {
 9123: 	if (formname.upfile.value == "") {
 9124: 	    alert("'.$nofile_alert.'");
 9125: 	    return false;
 9126: 	}
 9127:         if (formname.courseid.value == "") {
 9128:             alert("'.$nocourseid_alert.'");
 9129:             return false;
 9130:         }
 9131: 	formname.submit();
 9132:     }
 9133: 
 9134:     function ToSyllabus() {
 9135:         var cdom = '."'$dom'".';
 9136:         var cnum = document.rules.courseid.value;
 9137:         if (cdom == "" || cdom == null) {
 9138:             return;
 9139:         }
 9140:         if (cnum == "" || cnum == null) {
 9141:            return;
 9142:         }
 9143:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9144:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9145:         return;
 9146:     }
 9147: 
 9148: </script>
 9149: 
 9150: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9151: 
 9152: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9153: '.$default_form_data.
 9154:   &Apache::lonhtmlcommon::start_pick_box().
 9155:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9156:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9157:   &Apache::lonhtmlcommon::row_closure().
 9158:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9159:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9160:   &Apache::lonhtmlcommon::row_closure().
 9161:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9162:   '<input name="domainid" type="hidden" />'.$domdesc.
 9163:   &Apache::lonhtmlcommon::row_closure().
 9164:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9165:   '<input type="file" name="upfile" size="50" />'.
 9166:   &Apache::lonhtmlcommon::row_closure(1).
 9167:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9168: 
 9169: <input name="command" value="scantronupload_save" type="hidden" />
 9170: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9171: </form>
 9172: ');
 9173:     return '';
 9174: }
 9175: 
 9176: 
 9177: sub scantron_upload_scantron_data_save {
 9178:     my($r)=@_;
 9179:     my ($symb)=&get_symb($r,1);
 9180:     my $doanotherupload=
 9181: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9182: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9183: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9184: 	'</form>'."\n";
 9185:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9186: 	!&Apache::lonnet::allowed('usc',
 9187: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9188: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9189: 	if ($symb) {
 9190: 	    $r->print(&show_grading_menu_form($symb));
 9191: 	} else {
 9192: 	    $r->print($doanotherupload);
 9193: 	}
 9194: 	return '';
 9195:     }
 9196:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9197:     my $uploadedfile;
 9198:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9199:     if (length($env{'form.upfile'}) < 2) {
 9200:         $r->print(
 9201:             &Apache::lonhtmlcommon::confirm_success(
 9202:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9203:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9204:     } else {
 9205:         my $result = 
 9206:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 9207:                                             $env{'form.courseid'},$env{'form.domainid'});
 9208: 	if ($result =~ m{^/uploaded/}) {
 9209:             $r->print(
 9210:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9211:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9212:                         (length($env{'form.upfile'})-1),
 9213:                         '<span class="LC_filename">'.$result.'</span>'));
 9214:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9215:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9216:                                                        $env{'form.courseid'},$uploadedfile));
 9217: 	} else {
 9218:             $r->print(
 9219:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9220:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9221:                           $result,
 9222: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9223: 	}
 9224:     }
 9225:     if ($symb) {
 9226: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 9227:     } else {
 9228: 	$r->print($doanotherupload);
 9229:     }
 9230:     return '';
 9231: }
 9232: 
 9233: sub validate_uploaded_scantron_file {
 9234:     my ($cdom,$cname,$fname) = @_;
 9235:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9236:     my @lines;
 9237:     if ($scanlines ne '-1') {
 9238:         @lines=split("\n",$scanlines,-1);
 9239:     }
 9240:     my $output;
 9241:     if (@lines) {
 9242:         my (%counts,$max_match_format);
 9243:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9244:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9245:         my %idmap = &username_to_idmap($classlist);
 9246:         foreach my $key (keys(%idmap)) {
 9247:             my $lckey = lc($key);
 9248:             $idmap{$lckey} = $idmap{$key};
 9249:         }
 9250:         my %unique_formats;
 9251:         my @formatlines = &get_scantronformat_file();
 9252:         foreach my $line (@formatlines) {
 9253:             chomp($line);
 9254:             my @config = split(/:/,$line);
 9255:             my $idstart = $config[5];
 9256:             my $idlength = $config[6];
 9257:             if (($idstart ne '') && ($idlength > 0)) {
 9258:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9259:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9260:                 } else {
 9261:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9262:                 }
 9263:             }
 9264:         }
 9265:         foreach my $key (keys(%unique_formats)) {
 9266:             my ($idstart,$idlength) = split(':',$key);
 9267:             %{$counts{$key}} = (
 9268:                                'found'   => 0,
 9269:                                'total'   => 0,
 9270:                               );
 9271:             foreach my $line (@lines) {
 9272:                 next if ($line =~ /^#/);
 9273:                 next if ($line =~ /^[\s\cz]*$/);
 9274:                 my $id = substr($line,$idstart-1,$idlength);
 9275:                 $id = lc($id);
 9276:                 if (exists($idmap{$id})) {
 9277:                     $counts{$key}{'found'} ++;
 9278:                 }
 9279:                 $counts{$key}{'total'} ++;
 9280:             }
 9281:             if ($counts{$key}{'total'}) {
 9282:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9283:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9284:                     $max_match_pct = $percent_match;
 9285:                     $max_match_format = $key;
 9286:                     $found_match_count = $counts{$key}{'found'};
 9287:                     $max_match_count = $counts{$key}{'total'};
 9288:                 }
 9289:             }
 9290:         }
 9291:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9292:             my $format_descs;
 9293:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9294:             for (my $i=0; $i<$numwithformat; $i++) {
 9295:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9296:                 if ($i<$numwithformat-2) {
 9297:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9298:                 } elsif ($i==$numwithformat-2) {
 9299:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9300:                 } elsif ($i==$numwithformat-1) {
 9301:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9302:                 }
 9303:             }
 9304:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9305:             $output .= '<br />';
 9306:             if ($found_match_count == $max_match_count) {
 9307:                 # 100% matching entries
 9308:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9309:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9310:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9311:                 &mt('Comparison of student IDs in the uploaded file with'.
 9312:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9313:                     ' in the file (for the format defined for [_3]).',
 9314:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9315:             } else {
 9316:                 # Not all entries matching? -> Show warning and additional info
 9317:                 $output .=
 9318:                     &Apache::lonhtmlcommon::confirm_success(
 9319:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9320:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9321:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9322:                     &mt('Comparison of student IDs in the uploaded file with'.
 9323:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9324:                         ' in the file (for the format defined for [_3]).',
 9325:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9326:                     '<p class="LC_info">'.
 9327:                     &mt('A low percentage of matches results from one of the following:').
 9328:                     '</p><ul>'.
 9329:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9330:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9331:                                '<i>'.$cdom.'</i>').'</li>'.
 9332:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9333:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9334:                     '</ul>';
 9335:             }
 9336:         }
 9337:     } else {
 9338:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9339:     }
 9340:     return $output;
 9341: }
 9342: 
 9343: sub valid_file {
 9344:     my ($requested_file)=@_;
 9345:     foreach my $filename (sort(&scantron_filenames())) {
 9346: 	if ($requested_file eq $filename) { return 1; }
 9347:     }
 9348:     return 0;
 9349: }
 9350: 
 9351: sub scantron_download_scantron_data {
 9352:     my ($r)=@_;
 9353:     my ($symb) = &get_symb($r,1);
 9354:     my $default_form_data=&defaultFormData($symb);
 9355:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9356:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9357:     my $file=$env{'form.scantron_selectfile'};
 9358:     if (! &valid_file($file)) {
 9359: 	$r->print('
 9360: 	<p>
 9361: 	    '.&mt('The requested filename was invalid.').'
 9362:         </p>
 9363: ');
 9364: 	$r->print(&show_grading_menu_form($symb));
 9365: 	return;
 9366:     }
 9367:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9368:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9369:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9370:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9371:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9372:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9373:     $r->print('
 9374:     <p>
 9375: 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
 9376: 	      '<a href="'.$orig.'">','</a>').'
 9377:     </p>
 9378:     <p>
 9379: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9380: 	      '<a href="'.$corrected.'">','</a>').'
 9381:     </p>
 9382:     <p>
 9383: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9384: 	      '<a href="'.$skipped.'">','</a>').'
 9385:     </p>
 9386: ');
 9387:     $r->print(&show_grading_menu_form($symb));
 9388:     return '';
 9389: }
 9390: 
 9391: sub checkscantron_results {
 9392:     my ($r) = @_;
 9393:     my ($symb)=&get_symb($r);
 9394:     if (!$symb) {return '';}
 9395:     my $grading_menu_button=&show_grading_menu_form($symb);
 9396:     my $cid = $env{'request.course.id'};
 9397:     my %lettdig = &letter_to_digits();
 9398:     my $numletts = scalar(keys(%lettdig));
 9399:     my $cnum = $env{'course.'.$cid.'.num'};
 9400:     my $cdom = $env{'course.'.$cid.'.domain'};
 9401:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9402:     my %record;
 9403:     my %scantron_config =
 9404:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9405:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9406:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9407:     my $classlist=&Apache::loncoursedata::get_classlist();
 9408:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9409:     my $navmap=Apache::lonnavmaps::navmap->new();
 9410:     unless (ref($navmap)) {
 9411:         $r->print(&navmap_errormsg());
 9412:         return '';
 9413:     }
 9414:     my $map=$navmap->getResourceByUrl($sequence);
 9415:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9416:         %grader_randomlists_by_symb,%orderedforcode);
 9417:     if (ref($map)) {
 9418:         $randomorder=$map->randomorder();
 9419:         $randompick=$map->randompick();
 9420:     }
 9421:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9422:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9423:     if ($nav_error) {
 9424:         $r->print(&navmap_errormsg());
 9425:         return '';
 9426:     }
 9427:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9428:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9429:     my ($uname,$udom);
 9430:     my (%scandata,%lastname,%bylast);
 9431:     $r->print('
 9432: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9433: 
 9434:     my @delayqueue;
 9435:     my %completedstudents;
 9436: 
 9437:     my $count=&get_todo_count($scanlines,$scan_data);
 9438:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9439:     my ($username,$domain,$started);
 9440:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9441:     if ($nav_error) {
 9442:         $r->print(&navmap_errormsg());
 9443:         return '';
 9444:     }
 9445: 
 9446:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9447:                                           'Processing first student');
 9448:     my $start=&Time::HiRes::time();
 9449:     my $i=-1;
 9450: 
 9451:     while ($i<$scanlines->{'count'}) {
 9452:         ($username,$domain,$uname)=('','','');
 9453:         $i++;
 9454:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9455:         if ($line=~/^[\s\cz]*$/) { next; }
 9456:         if ($started) {
 9457:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9458:                                                      'last student');
 9459:         }
 9460:         $started=1;
 9461:         my $scan_record=
 9462:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9463:                                                      $scan_data);
 9464:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9465:                                               \%idmap,$i)) {
 9466:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9467:                                 'Unable to find a student that matches',1);
 9468:             next;
 9469:         }
 9470:         if (exists $completedstudents{$uname}) {
 9471:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9472:                                 'Student '.$uname.' has multiple sheets',2);
 9473:             next;
 9474:         }
 9475:         my $pid = $scan_record->{'scantron.ID'};
 9476:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9477:         push(@{$bylast{$lastname{$pid}}},$pid);
 9478:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9479:         my $user = $uname.':'.$usec;
 9480:         ($username,$domain)=split(/:/,$uname);
 9481: 
 9482:         my $scancode;
 9483:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9484:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9485:             $scancode = $scan_record->{'scantron.CODE'};
 9486:         } else {
 9487:             $scancode = '';
 9488:         }
 9489: 
 9490:         my @mapresources = @resources;
 9491:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9492:         my %respnumlookup=();
 9493:         my %startline=();
 9494:         if ($randomorder || $randompick) {
 9495:             @mapresources =
 9496:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9497:                              \%orderedforcode);
 9498:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9499:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9500:                                              \%grader_partids_by_symb,\%orderedforcode,
 9501:                                              \%respnumlookup,\%startline);
 9502:             if ($randompick && $total) {
 9503:                 $lastpos = $total*$scantron_config{'Qlength'};
 9504:             }
 9505:         }
 9506:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9507:         chomp($scandata{$pid});
 9508:         $scandata{$pid} =~ s/\r$//;
 9509: 
 9510:         my $counter = -1;
 9511:         foreach my $resource (@mapresources) {
 9512:             my $parts;
 9513:             my $ressymb = $resource->symb();
 9514:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9515:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9516:                 my $currcode;
 9517:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9518:                     $currcode = $scancode;
 9519:                 }
 9520:                 (my $analysis,$parts) =
 9521:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9522:                                               $username,$domain,undef,
 9523:                                               $bubbles_per_row,$currcode);
 9524:             } else {
 9525:                 $parts = $grader_partids_by_symb{$ressymb};
 9526:             }
 9527:             ($counter,my $recording) =
 9528:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9529:                                          $scandata{$pid},$parts,
 9530:                                          \%scantron_config,\%lettdig,$numletts,
 9531:                                          $randomorder,$randompick,
 9532:                                          \%respnumlookup,\%startline);
 9533:             $record{$pid} .= $recording;
 9534:         }
 9535:     }
 9536:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9537:     $r->print('<br />');
 9538:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9539:     $passed = 0;
 9540:     $failed = 0;
 9541:     $numstudents = 0;
 9542:     foreach my $last (sort(keys(%bylast))) {
 9543:         if (ref($bylast{$last}) eq 'ARRAY') {
 9544:             foreach my $pid (sort(@{$bylast{$last}})) {
 9545:                 my $showscandata = $scandata{$pid};
 9546:                 my $showrecord = $record{$pid};
 9547:                 $showscandata =~ s/\s/&nbsp;/g;
 9548:                 $showrecord =~ s/\s/&nbsp;/g;
 9549:                 if ($scandata{$pid} eq $record{$pid}) {
 9550:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9551:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9552: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9553: '</tr>'."\n".
 9554: '<tr class="'.$css_class.'">'."\n".
 9555: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9556:                     $passed ++;
 9557:                 } else {
 9558:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9559:                     $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".
 9560: '</tr>'."\n".
 9561: '<tr class="'.$css_class.'">'."\n".
 9562: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9563: '</tr>'."\n";
 9564:                     $failed ++;
 9565:                 }
 9566:                 $numstudents ++;
 9567:             }
 9568:         }
 9569:     }
 9570:     $r->print('<p>'.
 9571:               &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).',
 9572:                   '<b>',
 9573:                   $numstudents,
 9574:                   '</b>',
 9575:                   $env{'form.scantron_maxbubble'}).
 9576:               '</p>'
 9577:     );
 9578:     $r->print('<p>'
 9579:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9580:              .'<br />'
 9581:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9582:              .'</p>');
 9583:     if ($passed) {
 9584:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9585:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9586:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9587:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9588:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9589:                  $okstudents."\n".
 9590:                  &Apache::loncommon::end_data_table().'<br />');
 9591:     }
 9592:     if ($failed) {
 9593:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9594:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9595:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9596:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9597:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9598:                  $badstudents."\n".
 9599:                  &Apache::loncommon::end_data_table()).'<br />'.
 9600:                  &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.');  
 9601:     }
 9602:     $r->print('</form><br />'.$grading_menu_button);
 9603:     return;
 9604: }
 9605: 
 9606: sub verify_scantron_grading {
 9607:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9608:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9609:         $respnumlookup,$startline) = @_;
 9610:     my ($record,%expected,%startpos);
 9611:     return ($counter,$record) if (!ref($resource));
 9612:     return ($counter,$record) if (!$resource->is_problem());
 9613:     my $symb = $resource->symb();
 9614:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9615:     foreach my $part_id (@{$partids}) {
 9616:         $counter ++;
 9617:         $expected{$part_id} = 0;
 9618:         my $respnum = $counter;
 9619:         if ($randomorder || $randompick) {
 9620:             $respnum = $respnumlookup->{$counter};
 9621:             $startpos{$part_id} = $startline->{$counter} + 1;
 9622:         } else {
 9623:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9624:         }
 9625:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9626:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9627:             foreach my $item (@sub_lines) {
 9628:                 $expected{$part_id} += $item;
 9629:             }
 9630:         } else {
 9631:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9632:         }
 9633:     }
 9634:     if ($symb) {
 9635:         my %recorded;
 9636:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9637:         if ($returnhash{'version'}) {
 9638:             my %lasthash=();
 9639:             my $version;
 9640:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9641:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9642:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9643:                 }
 9644:             }
 9645:             foreach my $key (keys(%lasthash)) {
 9646:                 if ($key =~ /\.scantron$/) {
 9647:                     my $value = &unescape($lasthash{$key});
 9648:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9649:                     if ($value eq '') {
 9650:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9651:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9652:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9653:                             }
 9654:                         }
 9655:                     } else {
 9656:                         my @tocheck;
 9657:                         my @items = split(//,$value);
 9658:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9659:                             ($scantron_config->{'Qon'} eq 'number')) {
 9660:                             if (@items < $expected{$part_id}) {
 9661:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9662:                                 my @singles = split(//,$fragment);
 9663:                                 foreach my $pos (@singles) {
 9664:                                     if ($pos eq ' ') {
 9665:                                         push(@tocheck,$pos);
 9666:                                     } else {
 9667:                                         my $next = shift(@items);
 9668:                                         push(@tocheck,$next);
 9669:                                     }
 9670:                                 }
 9671:                             } else {
 9672:                                 @tocheck = @items;
 9673:                             }
 9674:                             foreach my $letter (@tocheck) {
 9675:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9676:                                     if ($letter !~ /^[A-J]$/) {
 9677:                                         $letter = $scantron_config->{'Qoff'};
 9678:                                     }
 9679:                                     $recorded{$part_id} .= $letter;
 9680:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9681:                                     my $digit;
 9682:                                     if ($letter !~ /^[A-J]$/) {
 9683:                                         $digit = $scantron_config->{'Qoff'};
 9684:                                     } else {
 9685:                                         $digit = $lettdig->{$letter};
 9686:                                     }
 9687:                                     $recorded{$part_id} .= $digit;
 9688:                                 }
 9689:                             }
 9690:                         } else {
 9691:                             @tocheck = @items;
 9692:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9693:                                 my $curr_sub = shift(@tocheck);
 9694:                                 my $digit;
 9695:                                 if ($curr_sub =~ /^[A-J]$/) {
 9696:                                     $digit = $lettdig->{$curr_sub}-1;
 9697:                                 }
 9698:                                 if ($curr_sub eq 'J') {
 9699:                                     $digit += scalar($numletts);
 9700:                                 }
 9701:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9702:                                     if ($j == $digit) {
 9703:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9704:                                     } else {
 9705:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9706:                                     }
 9707:                                 }
 9708:                             }
 9709:                         }
 9710:                     }
 9711:                 }
 9712:             }
 9713:         }
 9714:         foreach my $part_id (@{$partids}) {
 9715:             if ($recorded{$part_id} eq '') {
 9716:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9717:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9718:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9719:                     }
 9720:                 }
 9721:             }
 9722:             $record .= $recorded{$part_id};
 9723:         }
 9724:     }
 9725:     return ($counter,$record);
 9726: }
 9727: 
 9728: sub letter_to_digits {
 9729:     my %lettdig = (
 9730:                     A => 1,
 9731:                     B => 2,
 9732:                     C => 3,
 9733:                     D => 4,
 9734:                     E => 5,
 9735:                     F => 6,
 9736:                     G => 7,
 9737:                     H => 8,
 9738:                     I => 9,
 9739:                     J => 0,
 9740:                   );
 9741:     return %lettdig;
 9742: }
 9743: 
 9744: 
 9745: #-------- end of section for handling grading scantron forms -------
 9746: #
 9747: #-------------------------------------------------------------------
 9748: 
 9749: #-------------------------- Menu interface -------------------------
 9750: #
 9751: #--- Show a Grading Menu button - Calls the next routine ---
 9752: sub show_grading_menu_form {
 9753:     my ($symb)=@_;
 9754:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9755: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9756: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9757: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9758: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9759: 	'</form>'."\n";
 9760:     return $result;
 9761: }
 9762: 
 9763: # -- Retrieve choices for grading form
 9764: sub savedState {
 9765:     my %savedState = ();
 9766:     if ($env{'form.saveState'}) {
 9767: 	foreach (split(/:/,$env{'form.saveState'})) {
 9768: 	    my ($key,$value) = split(/=/,$_,2);
 9769: 	    $savedState{$key} = $value;
 9770: 	}
 9771:     }
 9772:     return \%savedState;
 9773: }
 9774: 
 9775: #--- Href with symb and command ---
 9776: 
 9777: sub href_symb_cmd {
 9778:     my ($symb,$cmd)=@_;
 9779:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9780: }
 9781: 
 9782: sub grading_menu {
 9783:     my ($request) = @_;
 9784:     my ($symb)=&get_symb($request);
 9785:     if (!$symb) {return '';}
 9786:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9787:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9788: 
 9789:     $request->print($table);
 9790:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9791:                   'handgrade'=>$hdgrade,
 9792:                   'probTitle'=>$probTitle,
 9793:                   'command'=>'submit_options',
 9794:                   'saveState'=>"",
 9795:                   'gradingMenu'=>1,
 9796:                   'showgrading'=>"yes");
 9797:     
 9798:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9799:     
 9800:     $fields{'command'} = 'csvform';
 9801:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9802:     
 9803:     $fields{'command'} = 'processclicker';
 9804:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9805:     
 9806:     $fields{'command'} = 'scantron_selectphase';
 9807:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9808:     
 9809:     my @menu = ({	categorytitle=>'Course Grading',
 9810:             items =>[
 9811:                         {	linktext => 'Manual Grading/View Submissions',
 9812:                     		url => $url1,
 9813:                     		permission => 'F',
 9814:                     		icon => 'edit-find-replace.png',
 9815:                     		linktitle => 'Start the process of hand grading submissions.'
 9816:                         },
 9817:                 	    {	linktext => 'Upload Scores',
 9818:                     		url => $url2,
 9819:                     		permission => 'F',
 9820:                     		icon => 'uploadscores.png',
 9821:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9822:                 	    },
 9823:                 	    {	linktext => 'Process Clicker',
 9824:                     		url => $url3,
 9825:                     		permission => 'F',
 9826:                     		icon => 'addClickerInfoFile.png',
 9827:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9828:                 	    },
 9829:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9830:                     		url => $url4,
 9831:                     		permission => 'F',
 9832:                     		icon => 'stat.png',
 9833:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9834:                 	    }
 9835:                     ]
 9836:             });
 9837: 
 9838:     #$fields{'command'} = 'verify';
 9839:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9840:     #
 9841:     # Create the menu
 9842:     my $Str;
 9843:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9844:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9845:     $Str .= '<input type="hidden" name="command" value="" />'.
 9846:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9847: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9848: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9849: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9850: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9851: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9852: 
 9853:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9854:     #$menudata->{'jscript'}
 9855:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9856:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9857:         ' /> '.
 9858:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9859:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9860: 
 9861:     $Str .="</form>\n";
 9862:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9863:     $request->print(<<GRADINGMENUJS);
 9864: <script type="text/javascript" language="javascript">
 9865:     function checkChoice(formname,val,cmdx) {
 9866: 	if (val <= 2) {
 9867: 	    var cmd = radioSelection(formname.radioChoice);
 9868: 	    var cmdsave = cmd;
 9869: 	} else {
 9870: 	    cmd = cmdx;
 9871: 	    cmdsave = 'submission';
 9872: 	}
 9873: 	formname.command.value = cmd;
 9874: 	if (val < 5) formname.submit();
 9875: 	if (val == 5) {
 9876: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9877: 	        return false;
 9878: 	    } else {
 9879: 	        formname.submit();
 9880: 	    }
 9881: 	}
 9882:     }
 9883: 
 9884:     function checkReceiptNo(formname,nospace) {
 9885: 	var receiptNo = formname.receipt.value;
 9886: 	var checkOpt = false;
 9887: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9888: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9889: 	if (checkOpt) {
 9890: 	    alert("$receiptalert");
 9891: 	    formname.receipt.value = "";
 9892: 	    formname.receipt.focus();
 9893: 	    return false;
 9894: 	}
 9895: 	return true;
 9896:     }
 9897: </script>
 9898: GRADINGMENUJS
 9899:     &commonJSfunctions($request);
 9900:     return $Str;    
 9901: }
 9902: 
 9903: 
 9904: #--- Displays the submissions first page -------
 9905: sub submit_options {
 9906:     my ($request) = @_;
 9907:     my ($symb)=&get_symb($request);
 9908:     if (!$symb) {return '';}
 9909:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9910: 
 9911:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9912:     $request->print(<<GRADINGMENUJS);
 9913: <script type="text/javascript" language="javascript">
 9914:     function checkChoice(formname,val,cmdx) {
 9915: 	if (val <= 2) {
 9916: 	    var cmd = radioSelection(formname.radioChoice);
 9917: 	    var cmdsave = cmd;
 9918: 	} else {
 9919: 	    cmd = cmdx;
 9920: 	    cmdsave = 'submission';
 9921: 	}
 9922: 	formname.command.value = cmd;
 9923: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9924: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9925: 	if (val < 5) formname.submit();
 9926: 	if (val == 5) {
 9927: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9928: 	    formname.submit();
 9929: 	}
 9930: 	if (val < 7) formname.submit();
 9931:     }
 9932: 
 9933:     function checkReceiptNo(formname,nospace) {
 9934: 	var receiptNo = formname.receipt.value;
 9935: 	var checkOpt = false;
 9936: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9937: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9938: 	if (checkOpt) {
 9939: 	    alert("$receiptalert");
 9940: 	    formname.receipt.value = "";
 9941: 	    formname.receipt.focus();
 9942: 	    return false;
 9943: 	}
 9944: 	return true;
 9945:     }
 9946: </script>
 9947: GRADINGMENUJS
 9948:     &commonJSfunctions($request);
 9949:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9950:     my $result;
 9951:     my (undef,$sections) = &getclasslist('all','0');
 9952:     my $savedState = &savedState();
 9953:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9954:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9955:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9956:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9957: 
 9958:     # Preselect sections
 9959:     my $selsec="";
 9960:     if (ref($sections)) {
 9961:         foreach my $section (sort(@$sections)) {
 9962:             $selsec.='<option value="'.$section.'" '.
 9963:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9964:         }
 9965:     }
 9966: 
 9967:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9968: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9969: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9970: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9971: 	'<input type="hidden" name="command"     value="" />'."\n".
 9972: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9973: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9974: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9975: 
 9976:     $result.='
 9977: <h2>
 9978:   '.&mt('Grade Current Resource').'
 9979: </h2>
 9980: <div>
 9981:   '.$table.'
 9982: </div>
 9983: 
 9984: <div class="LC_columnSection">
 9985:   
 9986:     <fieldset>
 9987:       <legend>
 9988:        '.&mt('Sections').'
 9989:       </legend>
 9990:       <select name="section" multiple="multiple" size="5">'."\n";
 9991:     $result.= $selsec;
 9992:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9993:     $result.='
 9994:     </fieldset>
 9995:   
 9996:     <fieldset>
 9997:       <legend>
 9998:         '.&mt('Groups').'
 9999:       </legend>
10000:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10001:     </fieldset>
10002:   
10003:     <fieldset>
10004:       <legend>
10005:         '.&mt('Access Status').'
10006:       </legend>
10007:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
10008:     </fieldset>
10009:   
10010:     <fieldset>
10011:       <legend>
10012:         '.&mt('Submission Status').'
10013:       </legend>
10014:       <select name="submitonly" size="5">
10015: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
10016: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
10017: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
10018: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
10019:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
10020:       </select>
10021:     </fieldset>
10022:   
10023: </div>
10024: 
10025: <br />
10026:           <div>
10027:             <div>
10028:               <label>
10029:                 <input type="radio" name="radioChoice" value="submission" '.
10030:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
10031:              &mt('Select individual students to grade and view submissions.').'
10032: 	      </label> 
10033:             </div>
10034:             <div>
10035: 	      <label>
10036:                 <input type="radio" name="radioChoice" value="viewgrades" '.
10037:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
10038:                     &mt('Grade all selected students in a grading table.').'
10039:               </label>
10040:             </div>
10041:             <div>
10042: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
10043:             </div>
10044:           </div>
10045: 
10046: 
10047:         <h2>
10048:          '.&mt('Grade Complete Folder for One Student').'
10049:         </h2>
10050:         <div>
10051:             <div>
10052:               <label>
10053:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
10054: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
10055:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
10056:               </label>
10057:             </div>
10058:             <div>
10059: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
10060:             </div>
10061:         </div>
10062:   </form>';
10063:     $result .= &show_grading_menu_form($symb);
10064:     return $result;
10065: }
10066: 
10067: sub substatus_options {
10068:     return &Apache::lonlocal::texthash(
10069:                                       'yes'       => 'with submissions',
10070:                                       'queued'    => 'in grading queue',
10071:                                       'graded'    => 'with ungraded submissions',
10072:                                       'incorrect' => 'with incorrect submissions',
10073:                                       'all'       => 'with any status',
10074:                                       );
10075: }
10076: 
10077: sub reset_perm {
10078:     undef(%perm);
10079: }
10080: 
10081: sub init_perm {
10082:     &reset_perm();
10083:     foreach my $test_perm ('vgr','mgr','opa') {
10084: 
10085: 	my $scope = $env{'request.course.id'};
10086: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10087: 
10088: 	    $scope .= '/'.$env{'request.course.sec'};
10089: 	    if ( $perm{$test_perm}=
10090: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10091: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10092: 	    } else {
10093: 		delete($perm{$test_perm});
10094: 	    }
10095: 	}
10096:     }
10097: }
10098: 
10099: sub init_old_essays {
10100:     my ($symb,$apath,$adom,$aname) = @_;
10101:     if ($symb ne '') {
10102:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10103:         if (keys(%essays) > 0) {
10104:             $old_essays{$symb} = \%essays;
10105:         }
10106:     }
10107:     return;
10108: }
10109: 
10110: sub reset_old_essays {
10111:     undef(%old_essays);
10112: }
10113: 
10114: sub gather_clicker_ids {
10115:     my %clicker_ids;
10116: 
10117:     my $classlist = &Apache::loncoursedata::get_classlist();
10118: 
10119:     # Set up a couple variables.
10120:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10121:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10122:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10123: 
10124:     foreach my $student (keys(%$classlist)) {
10125:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10126:         my $username = $classlist->{$student}->[$username_idx];
10127:         my $domain   = $classlist->{$student}->[$domain_idx];
10128:         my $clickers =
10129: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10130:         foreach my $id (split(/\,/,$clickers)) {
10131:             $id=~s/^[\#0]+//;
10132:             $id=~s/[\-\:]//g;
10133:             if (exists($clicker_ids{$id})) {
10134: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10135:             } else {
10136: 		$clicker_ids{$id}=$username.':'.$domain;
10137:             }
10138:         }
10139:     }
10140:     return %clicker_ids;
10141: }
10142: 
10143: sub gather_adv_clicker_ids {
10144:     my %clicker_ids;
10145:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10146:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10147:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10148:     foreach my $element (sort(keys(%coursepersonnel))) {
10149:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10150:             my ($puname,$pudom)=split(/\:/,$person);
10151:             my $clickers =
10152: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10153:             foreach my $id (split(/\,/,$clickers)) {
10154: 		$id=~s/^[\#0]+//;
10155:                 $id=~s/[\-\:]//g;
10156: 		if (exists($clicker_ids{$id})) {
10157: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10158: 		} else {
10159: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10160: 		}
10161:             }
10162:         }
10163:     }
10164:     return %clicker_ids;
10165: }
10166: 
10167: sub clicker_grading_parameters {
10168:     return ('gradingmechanism' => 'scalar',
10169:             'upfiletype' => 'scalar',
10170:             'specificid' => 'scalar',
10171:             'pcorrect' => 'scalar',
10172:             'pincorrect' => 'scalar');
10173: }
10174: 
10175: sub process_clicker {
10176:     my ($r)=@_;
10177:     my ($symb)=&get_symb($r);
10178:     if (!$symb) {return '';}
10179:     my $result=&checkforfile_js();
10180:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
10181:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
10182:     $result.=$table;
10183:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
10184:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
10185:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
10186:         '</b></td></tr>'."\n";
10187:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
10188: # Attempt to restore parameters from last session, set defaults if not present
10189:     my %Saveable_Parameters=&clicker_grading_parameters();
10190:     &Apache::loncommon::restore_course_settings('grades_clicker',
10191:                                                  \%Saveable_Parameters);
10192:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10193:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10194:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10195:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10196: 
10197:     my %checked;
10198:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10199:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10200:           $checked{$gradingmechanism}=' checked="checked"';
10201:        }
10202:     }
10203: 
10204:     my $upload=&mt("Upload File");
10205:     my $type=&mt("Type");
10206:     my $attendance=&mt("Award points just for participation");
10207:     my $personnel=&mt("Correctness determined from response by course personnel");
10208:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10209:     my $given=&mt("Correctness determined from given list of answers").' '.
10210:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10211:     my $pcorrect=&mt("Percentage points for correct solution");
10212:     my $pincorrect=&mt("Percentage points for incorrect solution");
10213:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10214:                                                    {'iclicker' => 'i>clicker',
10215:                                                     'interwrite' => 'interwrite PRS',
10216:                                                     'turning' => 'Turning Technologies'});
10217:     $symb = &Apache::lonenc::check_encrypt($symb);
10218:     $result.=<<ENDUPFORM;
10219: <script type="text/javascript">
10220: function sanitycheck() {
10221: // Accept only integer percentages
10222:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10223:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10224: // Find out grading choice
10225:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10226:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10227:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10228:       }
10229:    }
10230: // By default, new choice equals user selection
10231:    newgradingchoice=gradingchoice;
10232: // Not good to give more points for false answers than correct ones
10233:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10234:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10235:    }
10236: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10237:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10238:       document.forms.gradesupload.pcorrect.value=100;
10239:       document.forms.gradesupload.pincorrect.value=100;
10240:    }
10241: // If the values are different, cannot be attendance only
10242:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10243:        (gradingchoice=='attendance')) {
10244:        newgradingchoice='personnel';
10245:    }
10246: // Change grading choice to new one
10247:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10248:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10249:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10250:       } else {
10251:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10252:       }
10253:    }
10254: // Remember the old state
10255:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10256: }
10257: </script>
10258: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10259: <input type="hidden" name="symb" value="$symb" />
10260: <input type="hidden" name="command" value="processclickerfile" />
10261: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10262: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10263: <input type="file" name="upfile" size="50" />
10264: <br /><label>$type: $selectform</label>
10265: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10266: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10267: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10268: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10269: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10270: <br />&nbsp;&nbsp;&nbsp;
10271: <input type="text" name="givenanswer" size="50" />
10272: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10273: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10274: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10275: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10276: </form>
10277: ENDUPFORM
10278:     $result.='</td></tr></table>'."\n".
10279:              '</td></tr></table><br /><br />'."\n";
10280:     $result.=&show_grading_menu_form($symb);
10281:     return $result;
10282: }
10283: 
10284: sub process_clicker_file {
10285:     my ($r)=@_;
10286:     my ($symb)=&get_symb($r);
10287:     if (!$symb) {return '';}
10288: 
10289:     my %Saveable_Parameters=&clicker_grading_parameters();
10290:     &Apache::loncommon::store_course_settings('grades_clicker',
10291:                                               \%Saveable_Parameters);
10292: 
10293:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10294:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10295: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10296: 	return $result.&show_grading_menu_form($symb);
10297:     }
10298:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10299:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10300:         return $result.&show_grading_menu_form($symb);
10301:     }
10302:     my $foundgiven=0;
10303:     if ($env{'form.gradingmechanism'} eq 'given') {
10304:         $env{'form.givenanswer'}=~s/^\s*//gs;
10305:         $env{'form.givenanswer'}=~s/\s*$//gs;
10306:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10307:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10308:         my @answers=split(/\,/,$env{'form.givenanswer'});
10309:         $foundgiven=$#answers+1;
10310:     }
10311:     my %clicker_ids=&gather_clicker_ids();
10312:     my %correct_ids;
10313:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10314: 	%correct_ids=&gather_adv_clicker_ids();
10315:     }
10316:     if ($env{'form.gradingmechanism'} eq 'specific') {
10317: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10318: 	   $correct_id=~tr/a-z/A-Z/;
10319: 	   $correct_id=~s/\s//gs;
10320: 	   $correct_id=~s/^[\#0]+//;
10321:            $correct_id=~s/[\-\:]//g;
10322:            if ($correct_id) {
10323: 	      $correct_ids{$correct_id}='specified';
10324:            }
10325:         }
10326:     }
10327:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10328: 	$result.=&mt('Score based on attendance only');
10329:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10330:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10331:     } else {
10332: 	my $number=0;
10333: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10334: 	foreach my $id (sort(keys(%correct_ids))) {
10335: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10336: 	    if ($correct_ids{$id} eq 'specified') {
10337: 		$result.=&mt('specified');
10338: 	    } else {
10339: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10340: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10341: 	    }
10342: 	    $number++;
10343: 	}
10344:         $result.="</p>\n";
10345:         if ($number==0) {
10346:             $result .=
10347:                  &Apache::lonhtmlcommon::confirm_success(
10348:                      &mt('No IDs found to determine correct answer'),1);
10349:             return $result,.&show_grading_menu_form($symb);
10350:         }
10351:     }
10352:     if (length($env{'form.upfile'}) < 2) {
10353:         $result .=
10354:             &Apache::lonhtmlcommon::confirm_success(
10355:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10356:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10357:         return $result.&show_grading_menu_form($symb);
10358:     }
10359: 
10360: # Were able to get all the info needed, now analyze the file
10361: 
10362:     $result.=&Apache::loncommon::studentbrowser_javascript();
10363:     $symb = &Apache::lonenc::check_encrypt($symb);
10364:     my $heading=&mt('Scanning clicker file');
10365:     $result.=(<<ENDHEADER);
10366: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
10367: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
10368: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
10369: <form method="post" action="/adm/grades" name="clickeranalysis">
10370: <input type="hidden" name="symb" value="$symb" />
10371: <input type="hidden" name="command" value="assignclickergrades" />
10372: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10373: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10374: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10375: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10376: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10377: ENDHEADER
10378:     if ($env{'form.gradingmechanism'} eq 'given') {
10379:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10380:     } 
10381:     my %responses;
10382:     my @questiontitles;
10383:     my $errormsg='';
10384:     my $number=0;
10385:     if ($env{'form.upfiletype'} eq 'iclicker') {
10386: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10387:     }
10388:     if ($env{'form.upfiletype'} eq 'interwrite') {
10389:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10390:     }
10391:     if ($env{'form.upfiletype'} eq 'turning') {
10392:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10393:     }
10394:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10395:              '<input type="hidden" name="number" value="'.$number.'" />'.
10396:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10397:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10398:              '<br />';
10399:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10400:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10401:        return $result.&show_grading_menu_form($symb);
10402:     } 
10403: # Remember Question Titles
10404: # FIXME: Possibly need delimiter other than ":"
10405:     for (my $i=0;$i<$number;$i++) {
10406:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10407:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10408:     }
10409:     my $correct_count=0;
10410:     my $student_count=0;
10411:     my $unknown_count=0;
10412: # Match answers with usernames
10413: # FIXME: Possibly need delimiter other than ":"
10414:     foreach my $id (keys(%responses)) {
10415:        if ($correct_ids{$id}) {
10416:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10417:           $correct_count++;
10418:        } elsif ($clicker_ids{$id}) {
10419:           if ($clicker_ids{$id}=~/\,/) {
10420: # More than one user with the same clicker!
10421:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10422:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10423:                            "<select name='multi".$id."'>";
10424:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10425:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10426:              }
10427:              $result.='</select>';
10428:              $unknown_count++;
10429:           } else {
10430: # Good: found one and only one user with the right clicker
10431:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10432:              $student_count++;
10433:           }
10434:        } else {
10435:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10436:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10437:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10438:                    "\n".&mt("Domain").": ".
10439:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10440:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10441:           $unknown_count++;
10442:        }
10443:     }
10444:     $result.='<hr />'.
10445:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10446:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10447:        if ($correct_count==0) {
10448:           $errormsg.="Found no correct answers for grading!";
10449:        } elsif ($correct_count>1) {
10450:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10451:        }
10452:     }
10453:     if ($number<1) {
10454:        $errormsg.="Found no questions.";
10455:     }
10456:     if ($errormsg) {
10457:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10458:     } else {
10459:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10460:     }
10461:     $result.='</form></td></tr></table>'."\n".
10462:              '</td></tr></table><br /><br />'."\n";
10463:     return $result.&show_grading_menu_form($symb);
10464: }
10465: 
10466: sub iclicker_eval {
10467:     my ($questiontitles,$responses)=@_;
10468:     my $number=0;
10469:     my $errormsg='';
10470:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10471:         my %components=&Apache::loncommon::record_sep($line);
10472:         my @entries=map {$components{$_}} (sort(keys(%components)));
10473: 	if ($entries[0] eq 'Question') {
10474: 	    for (my $i=3;$i<$#entries;$i+=6) {
10475: 		$$questiontitles[$number]=$entries[$i];
10476: 		$number++;
10477: 	    }
10478: 	}
10479: 	if ($entries[0]=~/^\#/) {
10480: 	    my $id=$entries[0];
10481: 	    my @idresponses;
10482: 	    $id=~s/^[\#0]+//;
10483: 	    for (my $i=0;$i<$number;$i++) {
10484: 		my $idx=3+$i*6;
10485:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10486: 		push(@idresponses,$entries[$idx]);
10487: 	    }
10488: 	    $$responses{$id}=join(',',@idresponses);
10489: 	}
10490:     }
10491:     return ($errormsg,$number);
10492: }
10493: 
10494: sub interwrite_eval {
10495:     my ($questiontitles,$responses)=@_;
10496:     my $number=0;
10497:     my $errormsg='';
10498:     my $skipline=1;
10499:     my $questionnumber=0;
10500:     my %idresponses=();
10501:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10502:         my %components=&Apache::loncommon::record_sep($line);
10503:         my @entries=map {$components{$_}} (sort(keys(%components)));
10504:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10505:         if ($entries[1] eq 'Response') { $skipline=1; }
10506:         next if $skipline;
10507:         if ($entries[0]!=$questionnumber) {
10508:            $questionnumber=$entries[0];
10509:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10510:            $number++;
10511:         }
10512:         my $id=$entries[4];
10513:         $id=~s/^[\#0]+//;
10514:         $id=~s/^v\d*\://i;
10515:         $id=~s/[\-\:]//g;
10516:         $idresponses{$id}[$number]=$entries[6];
10517:     }
10518:     foreach my $id (keys(%idresponses)) {
10519:        $$responses{$id}=join(',',@{$idresponses{$id}});
10520:        $$responses{$id}=~s/^\s*\,//;
10521:     }
10522:     return ($errormsg,$number);
10523: }
10524: 
10525: sub turning_eval {
10526:     my ($questiontitles,$responses)=@_;
10527:     my $number=0;
10528:     my $errormsg='';
10529:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10530:         my %components=&Apache::loncommon::record_sep($line);
10531:         my @entries=map {$components{$_}} (sort(keys(%components)));
10532:         if ($#entries>$number) { $number=$#entries; }
10533:         my $id=$entries[0];
10534:         my @idresponses;
10535:         $id=~s/^[\#0]+//;
10536:         unless ($id) { next; }
10537:         for (my $idx=1;$idx<=$#entries;$idx++) {
10538:             $entries[$idx]=~s/\,/\;/g;
10539:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10540:             push(@idresponses,$entries[$idx]);
10541:         }
10542:         $$responses{$id}=join(',',@idresponses);
10543:     }
10544:     for (my $i=1; $i<=$number; $i++) {
10545:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10546:     }
10547:     return ($errormsg,$number);
10548: }
10549: 
10550: sub assign_clicker_grades {
10551:     my ($r)=@_;
10552:     my ($symb)=&get_symb($r);
10553:     if (!$symb) {return '';}
10554: # See which part we are saving to
10555:     my $res_error;
10556:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10557:     if ($res_error) {
10558:         return &navmap_errormsg();
10559:     }
10560: # FIXME: This should probably look for the first handgradeable part
10561:     my $part=$$partlist[0];
10562: # Start screen output
10563:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10564: 
10565:     $result .= '<br />'.
10566:                &Apache::loncommon::start_data_table().
10567:                &Apache::loncommon::start_data_table_header_row().
10568:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10569:                &Apache::loncommon::end_data_table_header_row().
10570:                &Apache::loncommon::start_data_table_row().'<td>';
10571: 
10572: # Get correct result
10573: # FIXME: Possibly need delimiter other than ":"
10574:     my @correct=();
10575:     my $gradingmechanism=$env{'form.gradingmechanism'};
10576:     my $number=$env{'form.number'};
10577:     if ($gradingmechanism ne 'attendance') {
10578:        foreach my $key (keys(%env)) {
10579:           if ($key=~/^form\.correct\:/) {
10580:              my @input=split(/\,/,$env{$key});
10581:              for (my $i=0;$i<=$#input;$i++) {
10582:                  if (($correct[$i]) && ($input[$i]) &&
10583:                      ($correct[$i] ne $input[$i])) {
10584:                     $result.='<br /><span class="LC_warning">'.
10585:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10586:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10587:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10588:                     $correct[$i]=$input[$i];
10589:                  }
10590:              }
10591:           }
10592:        }
10593:        for (my $i=0;$i<$number;$i++) {
10594:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10595:              $result.='<br /><span class="LC_error">'.
10596:                       &mt('No correct result given for question "[_1]"!',
10597:                           $env{'form.question:'.$i}).'</span>';
10598:           }
10599:        }
10600:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10601:     }
10602: # Start grading
10603:     my $pcorrect=$env{'form.pcorrect'};
10604:     my $pincorrect=$env{'form.pincorrect'};
10605:     my $storecount=0;
10606:     my %users=();
10607:     foreach my $key (keys(%env)) {
10608:        my $user='';
10609:        if ($key=~/^form\.student\:(.*)$/) {
10610:           $user=$1;
10611:        }
10612:        if ($key=~/^form\.unknown\:(.*)$/) {
10613:           my $id=$1;
10614:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10615:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10616:           } elsif ($env{'form.multi'.$id}) {
10617:              $user=$env{'form.multi'.$id};
10618:           }
10619:        }
10620:        if ($user) {
10621:           if ($users{$user}) {
10622:              $result.='<br /><span class="LC_warning">'.
10623:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10624:                       '</span><br />';
10625:           }
10626:           $users{$user}=1;
10627:           my @answer=split(/\,/,$env{$key});
10628:           my $sum=0;
10629:           my $realnumber=$number;
10630:           for (my $i=0;$i<$number;$i++) {
10631:              if  ($correct[$i] eq '-') {
10632:                 $realnumber--;
10633:              } elsif ($answer[$i]) {
10634:                 if ($gradingmechanism eq 'attendance') {
10635:                    $sum+=$pcorrect;
10636:                 } elsif ($correct[$i] eq '*') {
10637:                    $sum+=$pcorrect;
10638:                 } else {
10639: # We actually grade if correct or not
10640:                    my $increment=$pincorrect;
10641: # Special case: numerical answer "0"
10642:                    if ($correct[$i] eq '0') {
10643:                       if ($answer[$i]=~/^[0\.]+$/) {
10644:                          $increment=$pcorrect;
10645:                       }
10646: # General numerical answer, both evaluate to something non-zero
10647:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10648:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10649:                          $increment=$pcorrect;
10650:                       }
10651: # Must be just alphanumeric
10652:                    } elsif ($answer[$i] eq $correct[$i]) {
10653:                       $increment=$pcorrect;
10654:                    }
10655:                    $sum+=$increment;
10656:                 }
10657:              }
10658:           }
10659:           my $ave=$sum/(100*$realnumber);
10660: # Store
10661:           my ($username,$domain)=split(/\:/,$user);
10662:           my %grades=();
10663:           $grades{"resource.$part.solved"}='correct_by_override';
10664:           $grades{"resource.$part.awarded"}=$ave;
10665:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10666:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10667:                                                  $env{'request.course.id'},
10668:                                                  $domain,$username);
10669:           if ($returncode ne 'ok') {
10670:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10671:           } else {
10672:              $storecount++;
10673:           }
10674:        }
10675:     }
10676: # We are done
10677:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10678:              '</td>'.
10679:              &Apache::loncommon::end_data_table_row().
10680:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10681:     return $result.&show_grading_menu_form($symb);
10682: }
10683: 
10684: sub navmap_errormsg {
10685:     return '<div class="LC_error">'.
10686:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10687:            &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>').
10688:            '</div>';
10689: }
10690: 
10691: sub startpage {
10692:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10693:     if ($nomenu) {
10694:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10695:     } else {
10696:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10697:                                                  {'bread_crumbs' => $crumbs}));
10698:     }
10699:     unless ($nodisplayflag) {
10700:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10701:     }
10702: }
10703: 
10704: sub handler {
10705:     my $request=$_[0];
10706:     &reset_caches();
10707:     if ($request->header_only) {
10708:         &Apache::loncommon::content_type($request,'text/html');
10709:         $request->send_http_header;
10710:         return OK;
10711:     }
10712:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10713: 
10714:     my $symb=&get_symb($request,1);
10715:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10716:     my $command=$commands[0];
10717: 
10718:     if ($#commands > 0) {
10719: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10720:     }
10721: 
10722:     $ssi_error = 0;
10723:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10724:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10725:                                                     {'bread_crumbs' => $brcrum});
10726:     if ($symb eq '' && $command eq '') {
10727: 	if ($env{'user.adv'}) {
10728:             &Apache::loncommon::content_type($request,'text/html');
10729:             $request->send_http_header;
10730:             $request->print($start_page);
10731: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10732: 		($env{'form.codethree'})) {
10733: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10734: 		    $env{'form.codethree'};
10735: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10736: 		    &Apache::lonnet::checkin($token);
10737: 		if ($tsymb) {
10738: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10739: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10740: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10741: 					  ('grade_username' => $tuname,
10742: 					   'grade_domain' => $tudom,
10743: 					   'grade_courseid' => $tcrsid,
10744: 					   'grade_symb' => $tsymb)));
10745: 		    } else {
10746: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10747: 		    }
10748: 		} else {
10749: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10750: 		}
10751: 	    } else {
10752: 		$request->print(&Apache::lonxml::tokeninputfield());
10753: 	    }
10754:         } elsif ($env{'request.course.id'}) {
10755:             &init_perm(); 
10756:             if (!%perm) {
10757:                 $request->internal_redirect('/adm/quickgrades');
10758:                 return OK;
10759:             } else {
10760:                 &Apache::loncommon::content_type($request,'text/html');
10761:                 $request->send_http_header;
10762:                 $request->print($start_page);
10763:             }
10764:         }
10765:     } else {
10766:         &init_perm();
10767:         if (!$env{'request.course.id'}) {
10768:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10769:                     ($command =~ /^scantronupload/)) {
10770:                 # Not in a course.
10771:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10772:                 return HTTP_NOT_ACCEPTABLE;
10773:             }
10774:         } elsif (!%perm) {
10775:             $request->internal_redirect('/adm/quickgrades');
10776:         }
10777:         &Apache::loncommon::content_type($request,'text/html');
10778:         $request->send_http_header;
10779:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10780:             $request->print($start_page); 
10781:         }
10782: 	if ($command eq 'submission' && $perm{'vgr'}) {
10783:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10784:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10785:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10786:                     &choose_task_version_form($symb,$env{'form.student'},
10787:                                               $env{'form.userdom'});
10788:             }
10789:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10790:             if ($versionform) {
10791:                 $request->print($versionform);
10792:             }
10793:             $request->print('<br clear="all" />');
10794: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10795:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10796:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10797:                 &choose_task_version_form($symb,$env{'form.student'},
10798:                                           $env{'form.userdom'},
10799:                                           $env{'form.inhibitmenu'});
10800:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10801:             if ($versionform) {
10802:                 $request->print($versionform);
10803:             }
10804:             $request->print('<br clear="all" />');
10805:             $request->print(&show_previous_task_version($request,$symb));
10806: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10807: 	    &pickStudentPage($request);
10808: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10809: 	    &displayPage($request);
10810: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10811: 	    &updateGradeByPage($request);
10812: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10813: 	    &processGroup($request);
10814: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10815: 	    $request->print(&grading_menu($request));
10816: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10817: 	    $request->print(&submit_options($request));
10818: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10819: 	    $request->print(&viewgrades($request));
10820: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10821: 	    $request->print(&processHandGrade($request));
10822: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10823: 	    $request->print(&editgrades($request));
10824: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10825: 	    $request->print(&verifyreceipt($request));
10826:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10827:             $request->print(&process_clicker($request));
10828:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10829:             $request->print(&process_clicker_file($request));
10830:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10831:             $request->print(&assign_clicker_grades($request));
10832: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10833: 	    $request->print(&upcsvScores_form($request));
10834: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10835: 	    $request->print(&csvupload($request));
10836: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10837: 	    $request->print(&csvuploadmap($request));
10838: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10839: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10840: 		$request->print(&csvuploadoptions($request));
10841: 	    } else {
10842: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10843: 		    $env{'form.upfile_associate'} = 'reverse';
10844: 		} else {
10845: 		    $env{'form.upfile_associate'} = 'forward';
10846: 		}
10847: 		$request->print(&csvuploadmap($request));
10848: 	    }
10849: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10850: 	    $request->print(&csvuploadassign($request));
10851: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10852: 	    $request->print(&scantron_selectphase($request));
10853:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10854:  	    $request->print(&scantron_do_warning($request));
10855: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10856: 	    $request->print(&scantron_validate_file($request));
10857: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10858: 	    $request->print(&scantron_process_students($request));
10859:  	} elsif ($command eq 'scantronupload' && 
10860:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10861: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10862:  	    $request->print(&scantron_upload_scantron_data($request)); 
10863:  	} elsif ($command eq 'scantronupload_save' &&
10864:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10865: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10866:  	    $request->print(&scantron_upload_scantron_data_save($request));
10867:  	} elsif ($command eq 'scantron_download' &&
10868: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10869:  	    $request->print(&scantron_download_scantron_data($request));
10870:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10871:             $request->print(&checkscantron_results($request));     
10872: 	} elsif ($command) {
10873: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10874: 	}
10875:     }
10876:     if ($ssi_error) {
10877: 	&ssi_print_error($request);
10878:     }
10879:     $request->print(&Apache::loncommon::end_page());
10880:     &reset_caches();
10881:     return OK;
10882: }
10883: 
10884: 1;
10885: 
10886: __END__;
10887: 
10888: 
10889: =head1 NAME
10890: 
10891: Apache::grades
10892: 
10893: =head1 SYNOPSIS
10894: 
10895: Handles the viewing of grades.
10896: 
10897: This is part of the LearningOnline Network with CAPA project
10898: described at http://www.lon-capa.org.
10899: 
10900: =head1 OVERVIEW
10901: 
10902: Do an ssi with retries:
10903: While I'd love to factor out this with the vesrion in lonprintout,
10904: 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
10905: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10906: 
10907: At least the logic that drives this has been pulled out into loncommon.
10908: 
10909: 
10910: 
10911: ssi_with_retries - Does the server side include of a resource.
10912:                      if the ssi call returns an error we'll retry it up to
10913:                      the number of times requested by the caller.
10914:                      If we still have a problem, no text is appended to the
10915:                      output and we set some global variables.
10916:                      to indicate to the caller an SSI error occurred.  
10917:                      All of this is supposed to deal with the issues described
10918:                      in LON-CAPA BZ 5631 see:
10919:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10920:                      by informing the user that this happened.
10921: 
10922: Parameters:
10923:   resource   - The resource to include.  This is passed directly, without
10924:                interpretation to lonnet::ssi.
10925:   form       - The form hash parameters that guide the interpretation of the resource
10926:                
10927:   retries    - Number of retries allowed before giving up completely.
10928: Returns:
10929:   On success, returns the rendered resource identified by the resource parameter.
10930: Side Effects:
10931:   The following global variables can be set:
10932:    ssi_error                - If an unrecoverable error occurred this becomes true.
10933:                               It is up to the caller to initialize this to false
10934:                               if desired.
10935:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10936:                               of the resource that could not be rendered by the ssi
10937:                               call.
10938:    ssi_error_message   - The error string fetched from the ssi response
10939:                               in the event of an error.
10940: 
10941: 
10942: =head1 HANDLER SUBROUTINE
10943: 
10944: ssi_with_retries()
10945: 
10946: =head1 SUBROUTINES
10947: 
10948: =over
10949: 
10950: =item scantron_get_correction() : 
10951: 
10952:    Builds the interface screen to interact with the operator to fix a
10953:    specific error condition in a specific scanline
10954: 
10955:  Arguments:
10956:     $r           - Apache request object
10957:     $i           - number of the current scanline
10958:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10959:     $scan_config - hash ref as returned from &get_scantron_config()
10960:     $line        - full contents of the current scanline
10961:     $error       - error condition, valid values are
10962:                    'incorrectCODE', 'duplicateCODE',
10963:                    'doublebubble', 'missingbubble',
10964:                    'duplicateID', 'incorrectID'
10965:     $arg         - extra information needed
10966:        For errors:
10967:          - duplicateID   - paper number that this studentID was seen before on
10968:          - duplicateCODE - array ref of the paper numbers this CODE was
10969:                            seen on before
10970:          - incorrectCODE - current incorrect CODE 
10971:          - doublebubble  - array ref of the bubble lines that have double
10972:                            bubble errors
10973:          - missingbubble - array ref of the bubble lines that have missing
10974:                            bubble errors
10975: 
10976:    $randomorder - True if exam folder has randomorder set
10977:    $randompick  - True if exam folder has randompick set
10978:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10979:                      for current line to question number used for same question
10980:                      in "Master Seqence" (as seen by Course Coordinator).
10981:    $startline   - Reference to hash where key is question number (0 is first)
10982:                   and value is number of first bubble line for current student
10983:                   or code-based randompick and/or randomorder.
10984: 
10985: 
10986: =item  scantron_get_maxbubble() : 
10987: 
10988:    Arguments:
10989:        $nav_error  - Reference to scalar which is a flag to indicate a
10990:                       failure to retrieve a navmap object.
10991:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10992:        calling routine should trap the error condition and display the warning
10993:        found in &navmap_errormsg().
10994: 
10995:        $scantron_config - Reference to bubblesheet format configuration hash.
10996: 
10997:    Returns the maximum number of bubble lines that are expected to
10998:    occur. Does this by walking the selected sequence rendering the
10999:    resource and then checking &Apache::lonxml::get_problem_counter()
11000:    for what the current value of the problem counter is.
11001: 
11002:    Caches the results to $env{'form.scantron_maxbubble'},
11003:    $env{'form.scantron.bubble_lines.n'}, 
11004:    $env{'form.scantron.first_bubble_line.n'} and
11005:    $env{"form.scantron.sub_bubblelines.n"}
11006:    which are the total number of bubble lines, the number of bubble
11007:    lines for response n and number of the first bubble line for response n,
11008:    and a comma separated list of numbers of bubble lines for sub-questions
11009:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11010: 
11011: 
11012: =item  scantron_validate_missingbubbles() : 
11013: 
11014:    Validates all scanlines in the selected file to not have any
11015:     answers that don't have bubbles that have not been verified
11016:     to be bubble free.
11017: 
11018: =item  scantron_process_students() : 
11019: 
11020:    Routine that does the actual grading of the bubblesheet information.
11021: 
11022:    The parsed scanline hash is added to %env 
11023: 
11024:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11025:    foreach resource , with the form data of
11026: 
11027: 	'submitted'     =>'scantron' 
11028: 	'grade_target'  =>'grade',
11029: 	'grade_username'=> username of student
11030: 	'grade_domain'  => domain of student
11031: 	'grade_courseid'=> of course
11032: 	'grade_symb'    => symb of resource to grade
11033: 
11034:     This triggers a grading pass. The problem grading code takes care
11035:     of converting the bubbled letter information (now in %env) into a
11036:     valid submission.
11037: 
11038: =item  scantron_upload_scantron_data() :
11039: 
11040:     Creates the screen for adding a new bubblesheet data file to a course.
11041: 
11042: =item  scantron_upload_scantron_data_save() : 
11043: 
11044:    Adds a provided bubble information data file to the course if user
11045:    has the correct privileges to do so. 
11046: 
11047: =item  valid_file() :
11048: 
11049:    Validates that the requested bubble data file exists in the course.
11050: 
11051: =item  scantron_download_scantron_data() : 
11052: 
11053:    Shows a list of the three internal files (original, corrected,
11054:    skipped) for a specific bubblesheet data file that exists in the
11055:    course.
11056: 
11057: =item  scantron_validate_ID() : 
11058: 
11059:    Validates all scanlines in the selected file to not have any
11060:    invalid or underspecified student/employee IDs
11061: 
11062: =item navmap_errormsg() :
11063: 
11064:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11065:    Should be called whenever the request to instantiate a navmap object fails.  
11066: 
11067: =back
11068: 
11069: =cut

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