File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.46: download - view: text, annotated - select for diffs
Tue Feb 19 21:27:46 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 (part). Missed in earlier rev. 1.596.2.12.2.45.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.46 2019/02/19 21:27:46 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:                                     my %old_course_desc;
 2365:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2366:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2367:                                     } else {
 2368:                                         my $args;
 2369:                                         if ($ocrsid ne $env{'request.course.id'}) {
 2370:                                             $args = {'one_time' => 1};
 2371:                                         }
 2372:                                         %old_course_desc =
 2373:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
 2374:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2375:                                     }
 2376:                                     $similar .=
 2377: 				        &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2378: 				            $osim,
 2379: 				            &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2380: 				            $old_course_desc{'description'},
 2381: 				            $old_course_desc{'num'},
 2382: 				            $old_course_desc{'domain'}).
 2383: 				            '</span></h3>';
 2384:                                 } else {
 2385:                                     $similar .=
 2386:                                         '<h3><span class="LC_warning">'.
 2387:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2388:                                             $osim,
 2389:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2390:                                         '</span></h3>';
 2391:                                 }
 2392:                                 $similar .= '<blockquote><i>'.
 2393:                                             &keywords_highlight($oessay).
 2394:                                             '</i></blockquote><hr />';
 2395: 		            }
 2396:                         }
 2397:                     }
 2398: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2399:                                          undef,$type,$trial,$rndseed);
 2400:                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
 2401:                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2402: 			my $display_part=&get_display_part($partid,$symb);
 2403:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2404:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2405:                             ' <span class="LC_internal_info">'.
 2406:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2407:                             '</span>&nbsp; &nbsp;';
 2408: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2409: 			if (@$files) {
 2410:                             if ($hide eq 'anon') {
 2411:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2412:                             } else {
 2413:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2414:                                             .'<br /><span class="LC_warning">';
 2415:                                 if(@$files == 1) {
 2416:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2417:                                 } else {
 2418:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2419:                                 }
 2420:                                 $lastsubonly .= '</span>';
 2421: 
 2422:                                 foreach my $file (@$files) {
 2423:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2424:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2425:                                 }
 2426:                             }
 2427: 			    $lastsubonly.='<br />';
 2428: 			}
 2429:                         if ($hide eq 'anon') {
 2430:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2431:                         } else {
 2432: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2433:                             if ($draft) {
 2434:                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2435:                             }
 2436:                             $subval =
 2437: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2438: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2439:                             if ($responsetype eq 'essay') {
 2440:                                 $subval =~ s{\n}{<br />}g;
 2441:                             }
 2442:                             $lastsubonly.=$subval."\n";
 2443:                         }
 2444: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2445: 			$lastsubonly.='</div>';
 2446: 		    }
 2447: 		}
 2448: 	    }
 2449: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2450: 	}
 2451: 	$request->print($lastsubonly);
 2452:    if ($env{'form.lastSub'} eq 'datesub') {
 2453: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2454: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2455:     }
 2456:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2457:         my $identifier = (&canmodify($usec)? $counter : '');
 2458: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2459: 								 $env{'request.course.id'},
 2460: 								 $last,'.submission',
 2461: 								 'Apache::grades::keywords_highlight',
 2462:                                                                  $usec,$identifier));
 2463:     }
 2464: 
 2465:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2466: 	.$udom.'" />'."\n");
 2467:     # return if view submission with no grading option
 2468:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2469: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2470: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2471: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2472: 	$toGrade.='</div>'."\n";
 2473: 	if (($env{'form.command'} eq 'submission') || 
 2474: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2475: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2476: 	}
 2477: 	$request->print($toGrade);
 2478: 	return;
 2479:     } else {
 2480: 	$request->print('</div>'."\n");
 2481:     }
 2482: 
 2483:     # essay grading message center
 2484:     if ($env{'form.handgrade'} eq 'yes') {
 2485: 	my $result='<div class="LC_grade_message_center">';
 2486:     
 2487: 	$result.='<div class="LC_grade_message_center_header">'.
 2488: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2489: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2490: 	my $msgfor = $givenn.' '.$lastname;
 2491: 	if (scalar(@$col_fullnames) > 0) {
 2492: 	    my $lastone = pop(@$col_fullnames);
 2493: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2494: 	}
 2495: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2496: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2497: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2498: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2499: 	    ',\''.$msgfor.'\');" target="_self">'.
 2500: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2501: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2502: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2503: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2504: 	    '<br />&nbsp;('.
 2505: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2506: 	$result.='</div></div>';
 2507: 	$request->print($result);
 2508:     }
 2509: 
 2510:     my %seen = ();
 2511:     my @partlist;
 2512:     my @gradePartRespid;
 2513:     my @part_response_id = &flatten_responseType($responseType);
 2514:     $request->print(
 2515:         '<div class="LC_Box">'
 2516:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2517:     );
 2518:     $request->print(&gradeBox_start());
 2519:     foreach my $part_response_id (@part_response_id) {
 2520:     	my ($partid,$respid) = @{ $part_response_id };
 2521: 	my $part_resp = join('_',@{ $part_response_id });
 2522: 	next if ($seen{$partid} > 0);
 2523: 	$seen{$partid}++;
 2524: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2525: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2526: 	push(@partlist,$partid);
 2527: 	push(@gradePartRespid,$partid.'.'.$respid);
 2528: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2529:     }
 2530:     $request->print(&gradeBox_end()); # </div>
 2531:     $request->print('</div>');
 2532: 
 2533:     $request->print('<div class="LC_grade_info_links">');
 2534:     $request->print('</div>');
 2535: 
 2536:     $result='<input type="hidden" name="partlist'.$counter.
 2537: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2538:     $result.='<input type="hidden" name="gradePartRespid'.
 2539: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2540:     my $ctr = 0;
 2541:     while ($ctr < scalar(@partlist)) {
 2542: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2543: 	    $partlist[$ctr].'" />'."\n";
 2544: 	$ctr++;
 2545:     }
 2546:     $request->print($result.''."\n");
 2547: 
 2548: # Done with printing info for one student
 2549: 
 2550:     $request->print('</div>');#LC_grade_show_user
 2551: 
 2552: 
 2553:     # print end of form
 2554:     if ($counter == $total) {
 2555:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2556: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2557: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2558: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2559: 	my $ntstu ='<select name="NTSTU">'.
 2560: 	    '<option>1</option><option>2</option>'.
 2561: 	    '<option>3</option><option>5</option>'.
 2562: 	    '<option>7</option><option>10</option></select>'."\n";
 2563: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2564: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2565:         $endform.=&mt('[_1]student(s)',$ntstu);
 2566: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2567: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2568: 	    '<input type="button" value="'.&mt('Next').'" '.
 2569: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2570:         $endform.='<span class="LC_warning">'.
 2571:                   &mt('(Next and Previous (student) do not save the scores.)').
 2572:                   '</span>'."\n" ;
 2573:         $endform.="<input type='hidden' value='".&get_increment().
 2574:             "' name='increment' />";
 2575: 	$endform.='</td></tr></table></form>';
 2576: 	$endform.=&show_grading_menu_form($symb);
 2577: 	$request->print($endform);
 2578:     }
 2579:     return '';
 2580: }
 2581: 
 2582: sub check_collaborators {
 2583:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2584:     my ($result,@col_fullnames);
 2585:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2586:     foreach my $part (keys(%$handgrade)) {
 2587: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2588: 					'.maxcollaborators',
 2589: 					$symb,$udom,$uname);
 2590: 	next if ($ncol <= 0);
 2591: 	$part =~ s/\_/\./g;
 2592: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2593: 	my (@good_collaborators, @bad_collaborators);
 2594: 	foreach my $possible_collaborator
 2595: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2596: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2597: 	    next if ($possible_collaborator eq '');
 2598: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2599: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2600: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2601: 	    # Doing this grep allows 'fuzzy' specification
 2602: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2603: 			       keys(%$classlist));
 2604: 	    if (! scalar(@matches)) {
 2605: 		push(@bad_collaborators, $possible_collaborator);
 2606: 	    } else {
 2607: 		push(@good_collaborators, @matches);
 2608: 	    }
 2609: 	}
 2610: 	if (scalar(@good_collaborators) != 0) {
 2611: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2612: 	    foreach my $name (@good_collaborators) {
 2613: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2614: 		push(@col_fullnames, $givenn.' '.$lastname);
 2615: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2616: 	    }
 2617: 	    $result.='</ol><br />'."\n";
 2618: 	    my ($part)=split(/\./,$part);
 2619: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2620: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2621: 		"\n";
 2622: 	}
 2623: 	if (scalar(@bad_collaborators) > 0) {
 2624: 	    $result.='<div class="LC_warning">';
 2625: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2626: 	    $result .= '</div>';
 2627: 	}         
 2628: 	if (scalar(@bad_collaborators > $ncol)) {
 2629: 	    $result .= '<div class="LC_warning">';
 2630: 	    $result .= &mt('This student has submitted too many '.
 2631: 		'collaborators.  Maximum is [_1].',$ncol);
 2632: 	    $result .= '</div>';
 2633: 	}
 2634:     }
 2635:     return ($result,$fullname,\@col_fullnames);
 2636: }
 2637: 
 2638: #--- Retrieve the last submission for all the parts
 2639: sub get_last_submission {
 2640:     my ($returnhash)=@_;
 2641:     my (@string,$timestamp,%lasthidden);
 2642:     if ($$returnhash{'version'}) {
 2643: 	my %lasthash=();
 2644: 	my ($version);
 2645: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2646: 	    foreach my $key (sort(split(/\:/,
 2647: 					$$returnhash{$version.':keys'}))) {
 2648: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2649: 		$timestamp = 
 2650: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2651: 	    }
 2652: 	}
 2653:         my (%typeparts,%randombytry);
 2654:         my $showsurv = 
 2655:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2656:         foreach my $key (sort(keys(%lasthash))) {
 2657:             if ($key =~ /\.type$/) {
 2658:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2659:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2660:                     ($lasthash{$key} eq 'randomizetry')) {
 2661:                     my ($ign,@parts) = split(/\./,$key);
 2662:                     pop(@parts);
 2663:                     my $id = join('.',@parts);
 2664:                     if ($lasthash{$key} eq 'randomizetry') {
 2665:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2666:                     } else {
 2667:                         unless ($showsurv) {
 2668:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2669:                         }
 2670:                     }
 2671:                     delete($lasthash{$key});
 2672:                 }
 2673:             }
 2674:         }
 2675:         my @hidden = keys(%typeparts);
 2676:         my @randomize = keys(%randombytry);
 2677: 	foreach my $key (keys(%lasthash)) {
 2678: 	    next if ($key !~ /\.submission$/);
 2679:             my $hide;
 2680:             if (@hidden) {
 2681:                 foreach my $id (@hidden) {
 2682:                     if ($key =~ /^\Q$id\E/) {
 2683:                         $hide = 'anon';
 2684:                         last;
 2685:                     }
 2686:                 }
 2687:             }
 2688:             unless ($hide) {
 2689:                 if (@randomize) {
 2690:                     foreach my $id (@randomize) {
 2691:                         if ($key =~ /^\Q$id\E/) {
 2692:                             $hide = 'rand';
 2693:                             last;
 2694:                         }
 2695:                     }
 2696:                 }
 2697:             }
 2698: 	    my ($partid,$foo) = split(/submission$/,$key);
 2699: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
 2700:             push(@string, join(':', $key, $hide, $draft, (
 2701:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2702:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2703: 	}
 2704:     }
 2705:     if (!@string) {
 2706: 	$string[0] =
 2707: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2708:     }
 2709:     return (\@string,\$timestamp);
 2710: }
 2711: 
 2712: #--- High light keywords, with style choosen by user.
 2713: sub keywords_highlight {
 2714:     my $string    = shift;
 2715:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2716:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2717:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2718:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2719:     foreach my $keyword (@keylist) {
 2720: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2721:     }
 2722:     return $string;
 2723: }
 2724: 
 2725: # For Tasks provide a mechanism to display previous version for one specific student
 2726: 
 2727: sub show_previous_task_version {
 2728:     my ($request,$symb) = @_;
 2729:     if ($symb eq '') {
 2730:         $request->print(
 2731:             '<span class="LC_error">'.
 2732:             &mt('Unable to handle ambiguous references.').
 2733:             '</span>');
 2734:         return '';
 2735:     }
 2736:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2737:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2738:     if (!&canview($usec)) {
 2739:         $request->print('<span class="LC_warning">'.
 2740:                         &mt('Unable to view previous version for requested student.').
 2741:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2742:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2743:                         '</span>');
 2744:         return;
 2745:     }
 2746:     my $mode = 'both';
 2747:     my $isTask = ($symb =~/\.task$/);
 2748:     if ($isTask) {
 2749:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2750:             if ($env{'form.fullname'} eq '') {
 2751:                 $env{'form.fullname'} =
 2752:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2753:             }
 2754:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2755:             $request->print("\n\n".
 2756:                             '<div class="LC_grade_show_user">'.
 2757:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2758:                             '</h2>'."\n");
 2759:             &Apache::lonxml::clear_problem_counter();
 2760:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2761:                             {'previousversion' => $env{'form.previousversion'} }));
 2762:             $request->print("\n</div>");
 2763:         }
 2764:     }
 2765:     return;
 2766: }
 2767: 
 2768: sub choose_task_version_form {
 2769:     my ($symb,$uname,$udom,$nomenu) = @_;
 2770:     my $isTask = ($symb =~/\.task$/);
 2771:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2772:     if ($isTask) {
 2773:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2774:                                               $udom,$uname);
 2775:         if (($record{'resource.0.version'} eq '') ||
 2776:             ($record{'resource.0.version'} < 2)) {
 2777:             return ($record{'resource.0.version'},
 2778:                     $record{'resource.0.version'},$result,$js);
 2779:         } else {
 2780:             $current = $record{'resource.0.version'};
 2781:         }
 2782:         if ($env{'form.previousversion'}) {
 2783:             $displayed = $env{'form.previousversion'};
 2784:             $rowtitle = &mt('Choose another version:')
 2785:         } else {
 2786:             $displayed = $current;
 2787:             $rowtitle = &mt('Show earlier version:');
 2788:         }
 2789:         $result = '<div class="LC_left_float">';
 2790:         my $list;
 2791:         my $numversions = 0;
 2792:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2793:             if ($i == $current) {
 2794:                 if (!$env{'form.previousversion'} || $nomenu) {
 2795:                     next;
 2796:                 } else {
 2797:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2798:                     $numversions ++;
 2799:                 }
 2800:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2801:                 unless ($i == $env{'form.previousversion'}) {
 2802:                     $numversions ++;
 2803:                 }
 2804:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2805:             }
 2806:         }
 2807:         if ($numversions) {
 2808:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2809:             $result .=
 2810:                 '<form name="getprev" method="post" action=""'.
 2811:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2812:                 &Apache::loncommon::start_data_table().
 2813:                 &Apache::loncommon::start_data_table_row().
 2814:                 '<th align="left">'.$rowtitle.'</th>'.
 2815:                 '<td><select name="version">'.
 2816:                 '<option>'.&mt('Select').'</option>'.
 2817:                 $list.
 2818:                 '</select></td>'.
 2819:                 &Apache::loncommon::end_data_table_row();
 2820:             unless ($nomenu) {
 2821:                 $result .= &Apache::loncommon::start_data_table_row().
 2822:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2823:                 '<td><span class="LC_nobreak">'.
 2824:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2825:                 &mt('Yes').'</label>'.
 2826:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2827:                 '</span></td>'.
 2828:                 &Apache::loncommon::end_data_table_row();
 2829:             }
 2830:             $result .=
 2831:                 &Apache::loncommon::start_data_table_row().
 2832:                 '<th align="left">&nbsp;</th>'.
 2833:                 '<td>'.
 2834:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2835:                 '</td>'.
 2836:                 &Apache::loncommon::end_data_table_row().
 2837:                 &Apache::loncommon::end_data_table().
 2838:                 '</form>';
 2839:             $js = &previous_display_javascript($nomenu,$current);
 2840:         } elsif ($displayed && $nomenu) {
 2841:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2842:         } else {
 2843:             $result .= &mt('No previous versions to show for this student');
 2844:         }
 2845:         $result .= '</div>';
 2846:     }
 2847:     return ($current,$displayed,$result,$js);
 2848: }
 2849: 
 2850: sub previous_display_javascript {
 2851:     my ($nomenu,$current) = @_;
 2852:     my $js = <<"JSONE";
 2853: <script type="text/javascript">
 2854: // <![CDATA[
 2855: function previousVersion(uname,udom,symb) {
 2856:     var current = '$current';
 2857:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2858:     var prevstr = new RegExp("^\\\\d+\$");
 2859:     if (!prevstr.test(version)) {
 2860:         return false;
 2861:     }
 2862:     var url = '';
 2863:     if (version == current) {
 2864:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2865:     } else {
 2866:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2867:     }
 2868: JSONE
 2869:     if ($nomenu) {
 2870:         $js .= <<"JSTWO";
 2871:     document.location.href = url;
 2872: JSTWO
 2873:     } else {
 2874:         $js .= <<"JSTHREE";
 2875:     var newwin = 0;
 2876:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2877:         if (document.getprev.prevwin[i].checked == true) {
 2878:             newwin = document.getprev.prevwin[i].value;
 2879:         }
 2880:     }
 2881:     if (newwin == 1) {
 2882:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2883:         url = url+'&inhibitmenu=yes';
 2884:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2885:             previousWin = window.open(url,'',options,1);
 2886:         } else {
 2887:             previousWin.location.href = url;
 2888:         }
 2889:         previousWin.focus();
 2890:         return false;
 2891:     } else {
 2892:         document.location.href = url;
 2893:         return false;
 2894:     }
 2895: JSTHREE
 2896:     }
 2897:     $js .= <<"ENDJS";
 2898:     return false;
 2899: }
 2900: // ]]>
 2901: </script>
 2902: ENDJS
 2903: 
 2904: }
 2905: 
 2906: #--- Called from submission routine
 2907: sub processHandGrade {
 2908:     my ($request) = shift;
 2909:     my ($symb)   = &get_symb($request);
 2910:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2911:     my $button = $env{'form.gradeOpt'};
 2912:     my $ngrade = $env{'form.NCT'};
 2913:     my $ntstu  = $env{'form.NTSTU'};
 2914:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2915:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2916: 
 2917:     if ($button eq 'Save & Next') {
 2918: 	my $ctr = 0;
 2919: 	while ($ctr < $ngrade) {
 2920: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2921: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2922:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2923: 	    if ($errorflag eq 'no_score') {
 2924: 		$ctr++;
 2925: 		next;
 2926: 	    }
 2927: 	    if ($errorflag eq 'not_allowed') {
 2928:                 $request->print(
 2929:                     '<span class="LC_error">'
 2930:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2931:                    .'</span>');
 2932: 		$ctr++;
 2933: 		next;
 2934: 	    }
 2935:             if ($numhidden) {
 2936:                 $request->print(
 2937:                     '<span class="LC_info">'
 2938:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2939:                    .'</span><br />');
 2940:             }
 2941: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2942: 	    my ($subject,$message,$msgstatus) = ('','','');
 2943: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2944:             my ($feedurl,$showsymb) =
 2945: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2946: 	    my $messagetail;
 2947: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2948: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2949: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2950: 		$subject.=' ['.$restitle.']';
 2951: 		my (@msgnum) = split(/,/,$includemsg);
 2952: 		foreach (@msgnum) {
 2953: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2954: 		}
 2955: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2956: 		if ($env{'form.withgrades'.$ctr}) {
 2957: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2958: 		    $messagetail = " for <a href=\"".
 2959: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2960: 		}
 2961: 		$msgstatus = 
 2962:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2963: 						     $message.$messagetail,
 2964:                                                      undef,$feedurl,undef,
 2965:                                                      undef,undef,$showsymb,
 2966:                                                      $restitle);
 2967: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2968: 				$msgstatus.'<br />');
 2969: 	    }
 2970: 	    if ($env{'form.collaborator'.$ctr}) {
 2971: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2972: 		foreach my $collabstr (@collabstrs) {
 2973: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2974: 		    foreach my $collaborator (@collaborators) {
 2975: 			my ($errorflag,$pts,$wgt) = 
 2976: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2977: 					   $env{'form.unamedom'.$ctr},$part);
 2978: 			if ($errorflag eq 'not_allowed') {
 2979: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2980: 			    next;
 2981: 			} elsif ($message ne '') {
 2982: 			    my ($baseurl,$showsymb) = 
 2983: 				&get_feedurl_and_symb($symb,$collaborator,
 2984: 						      $udom);
 2985: 			    if ($env{'form.withgrades'.$ctr}) {
 2986: 				$messagetail = " for <a href=\"".
 2987:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2988: 			    }
 2989: 			    $msgstatus = 
 2990: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2991: 			}
 2992: 		    }
 2993: 		}
 2994: 	    }
 2995: 	    $ctr++;
 2996: 	}
 2997:     }
 2998: 
 2999:     if ($env{'form.handgrade'} eq 'yes') {
 3000: 	# Keywords sorted in alphabatical order
 3001: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3002: 	my %keyhash = ();
 3003: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3004: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 3005: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3006: 	$env{'form.keywords'} = join(' ',@keywords);
 3007: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3008: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3009: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3010: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3011: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3012: 
 3013: 	# message center - Order of message gets changed. Blank line is eliminated.
 3014: 	# New messages are saved in env for the next student.
 3015: 	# All messages are saved in nohist_handgrade.db
 3016: 	my ($ctr,$idx) = (1,1);
 3017: 	while ($ctr <= $env{'form.savemsgN'}) {
 3018: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3019: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3020: 		$idx++;
 3021: 	    }
 3022: 	    $ctr++;
 3023: 	}
 3024: 	$ctr = 0;
 3025: 	while ($ctr < $ngrade) {
 3026: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3027: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3028: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3029: 		$idx++;
 3030: 	    }
 3031: 	    $ctr++;
 3032: 	}
 3033: 	$env{'form.savemsgN'} = --$idx;
 3034: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3035: 	my $putresult = &Apache::lonnet::put
 3036: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3037:     }
 3038:     # Called by Save & Refresh from Highlight Attribute Window
 3039:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3040:     if ($env{'form.refresh'} eq 'on') {
 3041: 	my ($ctr,$total) = (0,0);
 3042: 	while ($ctr < $ngrade) {
 3043: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3044: 	    $ctr++;
 3045: 	}
 3046: 	$env{'form.NTSTU'}=$ngrade;
 3047: 	$ctr = 0;
 3048: 	while ($ctr < $total) {
 3049: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3050: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3051: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3052: 	    &submission($request,$ctr,$total-1);
 3053: 	    $ctr++;
 3054: 	}
 3055: 	return '';
 3056:     }
 3057: 
 3058: # Go directly to grade student - from submission or link from chart page
 3059:     if ($button eq 'Grade Student') {
 3060: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 3061: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 3062: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3063: 	$env{'form.fullname'} = $$fullname{$processUser};
 3064: 	&submission($request,0,0);
 3065: 	return '';
 3066:     }
 3067: 
 3068:     # Get the next/previous one or group of students
 3069:     my $firststu = $env{'form.unamedom0'};
 3070:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3071:     my $ctr = 2;
 3072:     while ($laststu eq '') {
 3073: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3074: 	$ctr++;
 3075: 	$laststu = $firststu if ($ctr > $ngrade);
 3076:     }
 3077: 
 3078:     my (@parsedlist,@nextlist);
 3079:     my ($nextflg) = 0;
 3080:     foreach my $item (sort 
 3081: 	     {
 3082: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3083: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3084: 		 }
 3085: 		 return $a cmp $b;
 3086: 	     } (keys(%$fullname))) {
 3087: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3088: 	    push(@parsedlist,$item);
 3089: 	}
 3090: 	$nextflg = 1 if ($item eq $laststu);
 3091: 	if ($button eq 'Previous') {
 3092: 	    last if ($item eq $firststu);
 3093: 	    push(@parsedlist,$item);
 3094: 	}
 3095:     }
 3096:     $ctr = 0;
 3097:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3098:     my $res_error;
 3099:     my ($partlist) = &response_type($symb,\$res_error);
 3100:     if ($res_error) {
 3101:         $request->print(&navmap_errormsg());
 3102:         return;
 3103:     }
 3104:     foreach my $student (@parsedlist) {
 3105: 	my $submitonly=$env{'form.submitonly'};
 3106: 	my ($uname,$udom) = split(/:/,$student);
 3107: 	
 3108: 	if ($submitonly eq 'queued') {
 3109: 	    my %queue_status = 
 3110: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3111: 							$udom,$uname);
 3112: 	    next if (!defined($queue_status{'gradingqueue'}));
 3113: 	}
 3114: 
 3115: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3116: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3117: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3118: 	    my $submitted = 0;
 3119: 	    my $ungraded = 0;
 3120: 	    my $incorrect = 0;
 3121: 	    foreach my $item (keys(%status)) {
 3122: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3123: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3124: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3125: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3126: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3127: 		    $submitted = 0;
 3128: 		}
 3129: 	    }
 3130: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3131: 				     $submitonly eq 'incorrect' ||
 3132: 				     $submitonly eq 'graded'));
 3133: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3134: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3135: 	}
 3136: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3137: 	last if ($ctr == $ntstu);
 3138: 	$ctr++;
 3139:     }
 3140: 
 3141:     $ctr = 0;
 3142:     my $total = scalar(@nextlist)-1;
 3143: 
 3144:     foreach (sort(@nextlist)) {
 3145: 	my ($uname,$udom,$submitter) = split(/:/);
 3146: 	$env{'form.student'}  = $uname;
 3147: 	$env{'form.userdom'}  = $udom;
 3148: 	$env{'form.fullname'} = $$fullname{$_};
 3149: 	&submission($request,$ctr,$total);
 3150: 	$ctr++;
 3151:     }
 3152:     if ($total < 0) {
 3153: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3154: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3155: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3156: 	$the_end.=&show_grading_menu_form($symb);
 3157: 	$request->print($the_end);
 3158:     }
 3159:     return '';
 3160: }
 3161: 
 3162: #---- Save the score and award for each student, if changed
 3163: sub saveHandGrade {
 3164:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3165:     my @version_parts;
 3166:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3167: 					   $env{'request.course.id'});
 3168:     if (!&canmodify($usec)) { return('not_allowed'); }
 3169:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3170:     my @parts_graded;
 3171:     my %newrecord  = ();
 3172:     my ($pts,$wgt,$totchg) = ('','',0);
 3173:     my %aggregate = ();
 3174:     my $aggregateflag = 0;
 3175:     if ($env{'form.HIDE'.$newflg}) {
 3176:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3177:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3178:         $totchg += $numchgs;
 3179:     }
 3180:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3181:     foreach my $new_part (@parts) {
 3182: 	#collaborator ($submi may vary for different parts
 3183: 	if ($submitter && $new_part ne $part) { next; }
 3184: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3185: 	if ($dropMenu eq 'excused') {
 3186: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3187: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3188: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3189: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3190: 		}
 3191: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3192: 	    }
 3193: 	} elsif ($dropMenu eq 'reset status'
 3194: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3195: 	    foreach my $key (keys(%record)) {
 3196: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3197: 	    }
 3198: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3199: 		"$env{'user.name'}:$env{'user.domain'}";
 3200:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3201: 
 3202:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3203: 					       [$new_part]);
 3204:             my $aggtries =$totaltries;
 3205:             if ($last_resets{$new_part}) {
 3206:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3207: 					   $new_part);
 3208:             }
 3209: 
 3210:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3211:             if ($aggtries > 0) {
 3212:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3213:                 $aggregateflag = 1;
 3214:             }
 3215: 	} elsif ($dropMenu eq '') {
 3216: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3217: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3218: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3219: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3220: 		next;
 3221: 	    }
 3222: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3223: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3224: 	    my $partial= $pts/$wgt;
 3225: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3226: 		#do not update score for part if not changed.
 3227:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3228: 		next;
 3229: 	    } else {
 3230: 	        push(@parts_graded,$new_part);
 3231: 	    }
 3232: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3233: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3234: 	    }
 3235: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3236: 	    if ($partial == 0) {
 3237: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3238: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3239: 		}
 3240: 	    } else {
 3241: 		if ($record{$reckey} ne 'correct_by_override') {
 3242: 		    $newrecord{$reckey} = 'correct_by_override';
 3243: 		}
 3244: 	    }	    
 3245: 	    if ($submitter && 
 3246: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3247: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3248: 	    }
 3249: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3250: 		"$env{'user.name'}:$env{'user.domain'}";
 3251: 	}
 3252: 	# unless problem has been graded, set flag to version the submitted files
 3253: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3254: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3255: 	        $dropMenu eq 'reset status')
 3256: 	   {
 3257: 	    push(@version_parts,$new_part);
 3258: 	}
 3259:     }
 3260:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3261:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3262: 
 3263:     if (%newrecord) {
 3264:         if (@version_parts) {
 3265:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3266:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3267: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3268: 	    foreach my $new_part (@version_parts) {
 3269: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3270: 				$new_part,\%newrecord);
 3271: 	    }
 3272:         }
 3273: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3274: 				$env{'request.course.id'},$domain,$stuname);
 3275: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3276: 				     $cdom,$cnum,$domain,$stuname);
 3277:     }
 3278:     if ($aggregateflag) {
 3279:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3280: 			      $cdom,$cnum);
 3281:     }
 3282:     return ('',$pts,$wgt,$totchg);
 3283: }
 3284: 
 3285: sub makehidden {
 3286:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3287:     return unless (ref($record) eq 'HASH');
 3288:     my %modified;
 3289:     my $numchanged = 0;
 3290:     if (exists($record->{$version.':keys'})) {
 3291:         my $partsregexp = $parts;
 3292:         $partsregexp =~ s/,/|/g;
 3293:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3294:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3295:                  my $item = $1;
 3296:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3297:                      $modified{$key} = $record->{$version.':'.$key};
 3298:                  }
 3299:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3300:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3301:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3302:                 $modified{$key} = $record->{$version.':'.$key};
 3303:             }
 3304:         }
 3305:         if (keys(%modified)) {
 3306:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3307:                                           $domain,$stuname,$tolog) eq 'ok') {
 3308:                 $numchanged ++;
 3309:             }
 3310:         }
 3311:     }
 3312:     return $numchanged;
 3313: }
 3314: 
 3315: sub check_and_remove_from_queue {
 3316:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3317:     my @ungraded_parts;
 3318:     foreach my $part (@{$parts}) {
 3319: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3320: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3321: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3322: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3323: 		) {
 3324: 	    push(@ungraded_parts, $part);
 3325: 	}
 3326:     }
 3327:     if ( !@ungraded_parts ) {
 3328: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3329: 					       $cnum,$domain,$stuname);
 3330:     }
 3331: }
 3332: 
 3333: sub handback_files {
 3334:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3335:     my $portfolio_root = '/userfiles/portfolio';
 3336:     my $res_error;
 3337:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3338:     if ($res_error) {
 3339:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3340:         return;
 3341:     }
 3342:     my @handedback;
 3343:     my $file_msg;
 3344:     my @part_response_id = &flatten_responseType($responseType);
 3345:     foreach my $part_response_id (@part_response_id) {
 3346:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3347: 	my $part_resp = join('_',@{ $part_response_id });
 3348:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3349:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3350:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3351: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3352:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3353:                     my ($directory,$answer_file) = 
 3354:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3355:                     my ($answer_name,$answer_ver,$answer_ext) =
 3356: 		        &file_name_version_ext($answer_file);
 3357: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3358:                     my $getpropath = 1;
 3359:                     my ($dir_list,$listerror) =
 3360:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3361:                                                  $domain,$stuname,$getpropath);
 3362: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3363:                     # fix filename
 3364:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3365:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3366:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3367:             	                                $save_file_name);
 3368:                     if ($result !~ m|^/uploaded/|) {
 3369:                         $request->print('<br /><span class="LC_error">'.
 3370:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3371:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3372:                                         '</span>');
 3373:                     } else {
 3374:                         # mark the file as read only
 3375:                         push(@handedback,$save_file_name);
 3376: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3377: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3378: 			}
 3379:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3380: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3381: 
 3382:                     }
 3383:                     $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>'));
 3384:                 }
 3385:             }
 3386:         }
 3387:     }
 3388:     if (@handedback > 0) {
 3389:         $request->print('<br />');
 3390:         my @what = ($symb,$env{'request.course.id'},'handback');
 3391:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3392:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3393:         my ($subject,$message);
 3394:         if (scalar(@handedback) == 1) {
 3395:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3396:         } else {
 3397:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3398:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3399:         }
 3400:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3401:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3402:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3403:         my ($feedurl,$showsymb) =
 3404:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3405:         my $restitle = &Apache::lonnet::gettitle($symb);
 3406:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3407:         my $msgstatus =
 3408:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3409:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3410:                  $restitle);
 3411:         if ($msgstatus) {
 3412:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3413:         }
 3414:     }
 3415:     return;
 3416: }
 3417: 
 3418: sub get_feedurl_and_symb {
 3419:     my ($symb,$uname,$udom) = @_;
 3420:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3421:     $url = &Apache::lonnet::clutter($url);
 3422:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3423: 					$symb,$udom,$uname);
 3424:     if ($encrypturl =~ /^yes$/i) {
 3425: 	&Apache::lonenc::encrypted(\$url,1);
 3426: 	&Apache::lonenc::encrypted(\$symb,1);
 3427:     }
 3428:     return ($url,$symb);
 3429: }
 3430: 
 3431: sub get_submitted_files {
 3432:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3433:     my @files;
 3434:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3435:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3436:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3437:     	    push(@files,$file_url.$file);
 3438:         }
 3439:     }
 3440:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3441:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3442:     }
 3443:     return (\@files);
 3444: }
 3445: 
 3446: # ----------- Provides number of tries since last reset.
 3447: sub get_num_tries {
 3448:     my ($record,$last_reset,$part) = @_;
 3449:     my $timestamp = '';
 3450:     my $num_tries = 0;
 3451:     if ($$record{'version'}) {
 3452:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3453:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3454:                 $timestamp = $$record{$version.':timestamp'};
 3455:                 if ($timestamp > $last_reset) {
 3456:                     $num_tries ++;
 3457:                 } else {
 3458:                     last;
 3459:                 }
 3460:             }
 3461:         }
 3462:     }
 3463:     return $num_tries;
 3464: }
 3465: 
 3466: # ----------- Determine decrements required in aggregate totals 
 3467: sub decrement_aggs {
 3468:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3469:     my %decrement = (
 3470:                         attempts => 0,
 3471:                         users => 0,
 3472:                         correct => 0
 3473:                     );
 3474:     $decrement{'attempts'} = $aggtries;
 3475:     if ($solvedstatus =~ /^correct/) {
 3476:         $decrement{'correct'} = 1;
 3477:     }
 3478:     if ($aggtries == $totaltries) {
 3479:         $decrement{'users'} = 1;
 3480:     }
 3481:     foreach my $type (keys(%decrement)) {
 3482:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3483:     }
 3484:     return;
 3485: }
 3486: 
 3487: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3488: sub get_last_resets {
 3489:     my ($symb,$courseid,$partids) =@_;
 3490:     my %last_resets;
 3491:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3492:     my $cname = $env{'course.'.$courseid.'.num'};
 3493:     my @keys;
 3494:     foreach my $part (@{$partids}) {
 3495: 	push(@keys,"$symb\0$part\0resettime");
 3496:     }
 3497:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3498: 				     $cdom,$cname);
 3499:     foreach my $part (@{$partids}) {
 3500: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3501:     }
 3502:     return %last_resets;
 3503: }
 3504: 
 3505: # ----------- Handles creating versions for portfolio files as answers
 3506: sub version_portfiles {
 3507:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3508:     my $version_parts = join('|',@$v_flag);
 3509:     my @returned_keys;
 3510:     my $parts = join('|', @$parts_graded);
 3511:     my $portfolio_root = '/userfiles/portfolio';
 3512:     foreach my $key (keys(%$record)) {
 3513:         my $new_portfiles;
 3514:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3515:             my @versioned_portfiles;
 3516:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3517:             foreach my $file (@portfiles) {
 3518:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3519:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3520: 		my ($answer_name,$answer_ver,$answer_ext) =
 3521: 		    &file_name_version_ext($answer_file);
 3522:                 my $getpropath = 1;
 3523:                 my ($dir_list,$listerror) =
 3524:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3525:                                              $stu_name,$getpropath);
 3526:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3527:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3528:                 if ($new_answer ne 'problem getting file') {
 3529:                     push(@versioned_portfiles, $directory.$new_answer);
 3530:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3531:                         [$directory.$new_answer],
 3532:                         [$symb,$env{'request.course.id'},'graded']);
 3533:                 }
 3534:             }
 3535:             $$record{$key} = join(',',@versioned_portfiles);
 3536:             push(@returned_keys,$key);
 3537:         }
 3538:     } 
 3539:     return (@returned_keys);   
 3540: }
 3541: 
 3542: sub get_next_version {
 3543:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3544:     my $version;
 3545:     if (ref($dir_list) eq 'ARRAY') {
 3546:         foreach my $row (@{$dir_list}) {
 3547:             my ($file) = split(/\&/,$row,2);
 3548:             my ($file_name,$file_version,$file_ext) =
 3549: 	        &file_name_version_ext($file);
 3550:             if (($file_name eq $answer_name) && 
 3551: 	        ($file_ext eq $answer_ext)) {
 3552:                 # gets here if filename and extension match, 
 3553:                 # regardless of version
 3554:                 if ($file_version ne '') {
 3555:                     # a versioned file is found  so save it for later
 3556:                     if ($file_version > $version) {
 3557: 		        $version = $file_version;
 3558:                     }
 3559: 	        }
 3560:             }
 3561:         }
 3562:     }
 3563:     $version ++;
 3564:     return($version);
 3565: }
 3566: 
 3567: sub version_selected_portfile {
 3568:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3569:     my ($answer_name,$answer_ver,$answer_ext) =
 3570:         &file_name_version_ext($file_name);
 3571:     my $new_answer;
 3572:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3573:     if($env{'form.copy'} eq '-1') {
 3574:         $new_answer = 'problem getting file';
 3575:     } else {
 3576:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3577:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3578:                             $stu_name,$domain,'copy',
 3579: 		        '/portfolio'.$directory.$new_answer);
 3580:     }    
 3581:     return ($new_answer);
 3582: }
 3583: 
 3584: sub file_name_version_ext {
 3585:     my ($file)=@_;
 3586:     my @file_parts = split(/\./, $file);
 3587:     my ($name,$version,$ext);
 3588:     if (@file_parts > 1) {
 3589: 	$ext=pop(@file_parts);
 3590: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3591: 	    $version=pop(@file_parts);
 3592: 	}
 3593: 	$name=join('.',@file_parts);
 3594:     } else {
 3595: 	$name=join('.',@file_parts);
 3596:     }
 3597:     return($name,$version,$ext);
 3598: }
 3599: 
 3600: #--------------------------------------------------------------------------------------
 3601: #
 3602: #-------------------------- Next few routines handles grading by section or whole class
 3603: #
 3604: #--- Javascript to handle grading by section or whole class
 3605: sub viewgrades_js {
 3606:     my ($request) = shift;
 3607: 
 3608:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3609:     &js_escape(\$alertmsg);
 3610:     $request->print(<<VIEWJAVASCRIPT);
 3611: <script type="text/javascript" language="javascript">
 3612:    function writePoint(partid,weight,point) {
 3613: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3614: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3615: 	if (point == "textval") {
 3616: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3617: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3618: 		alert("$alertmsg"+parseFloat(point));
 3619: 		var resetbox = false;
 3620: 		for (var i=0; i<radioButton.length; i++) {
 3621: 		    if (radioButton[i].checked) {
 3622: 			textbox.value = i;
 3623: 			resetbox = true;
 3624: 		    }
 3625: 		}
 3626: 		if (!resetbox) {
 3627: 		    textbox.value = "";
 3628: 		}
 3629: 		return;
 3630: 	    }
 3631: 	    if (parseFloat(point) > parseFloat(weight)) {
 3632: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3633: 				   ") greater than the weight for the part. Accept?");
 3634: 		if (resp == false) {
 3635: 		    textbox.value = "";
 3636: 		    return;
 3637: 		}
 3638: 	    }
 3639: 	    for (var i=0; i<radioButton.length; i++) {
 3640: 		radioButton[i].checked=false;
 3641: 		if (parseFloat(point) == i) {
 3642: 		    radioButton[i].checked=true;
 3643: 		}
 3644: 	    }
 3645: 
 3646: 	} else {
 3647: 	    textbox.value = parseFloat(point);
 3648: 	}
 3649: 	for (i=0;i<document.classgrade.total.value;i++) {
 3650: 	    var user = document.classgrade["ctr"+i].value;
 3651: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3652: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3653: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3654: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3655: 	    if (saveval != "correct") {
 3656: 		scorename.value = point;
 3657: 		if (selname[0].selected != true) {
 3658: 		    selname[0].selected = true;
 3659: 		}
 3660: 	    }
 3661: 	}
 3662: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3663:     }
 3664: 
 3665:     function writeRadText(partid,weight) {
 3666: 	var selval   = document.classgrade["SELVAL_"+partid];
 3667: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3668:         var override = document.classgrade["FORCE_"+partid].checked;
 3669: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3670: 	if (selval[1].selected || selval[2].selected) {
 3671: 	    for (var i=0; i<radioButton.length; i++) {
 3672: 		radioButton[i].checked=false;
 3673: 
 3674: 	    }
 3675: 	    textbox.value = "";
 3676: 
 3677: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3678: 		var user = document.classgrade["ctr"+i].value;
 3679: 		user = user.replace(new RegExp(':', 'g'),"_");
 3680: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3681: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3682: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3683: 		if ((saveval != "correct") || override) {
 3684: 		    scorename.value = "";
 3685: 		    if (selval[1].selected) {
 3686: 			selname[1].selected = true;
 3687: 		    } else {
 3688: 			selname[2].selected = true;
 3689: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3690: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3691: 		    }
 3692: 		}
 3693: 	    }
 3694: 	} else {
 3695: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3696: 		var user = document.classgrade["ctr"+i].value;
 3697: 		user = user.replace(new RegExp(':', 'g'),"_");
 3698: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3699: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3700: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3701: 		if ((saveval != "correct") || override) {
 3702: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3703: 		    selname[0].selected = true;
 3704: 		}
 3705: 	    }
 3706: 	}	    
 3707:     }
 3708: 
 3709:     function changeSelect(partid,user) {
 3710: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3711: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3712: 	var point  = textbox.value;
 3713: 	var weight = document.classgrade["weight_"+partid].value;
 3714: 
 3715: 	if (isNaN(point) || parseFloat(point) < 0) {
 3716: 	    alert("$alertmsg"+parseFloat(point));
 3717: 	    textbox.value = "";
 3718: 	    return;
 3719: 	}
 3720: 	if (parseFloat(point) > parseFloat(weight)) {
 3721: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3722: 			       ") greater than the weight of the part. Accept?");
 3723: 	    if (resp == false) {
 3724: 		textbox.value = "";
 3725: 		return;
 3726: 	    }
 3727: 	}
 3728: 	selval[0].selected = true;
 3729:     }
 3730: 
 3731:     function changeOneScore(partid,user) {
 3732: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3733: 	if (selval[1].selected || selval[2].selected) {
 3734: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3735: 	    if (selval[2].selected) {
 3736: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3737: 	    }
 3738:         }
 3739:     }
 3740: 
 3741:     function resetEntry(numpart) {
 3742: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3743: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3744: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3745: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3746: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3747: 	    for (var i=0; i<radioButton.length; i++) {
 3748: 		radioButton[i].checked=false;
 3749: 
 3750: 	    }
 3751: 	    textbox.value = "";
 3752: 	    selval[0].selected = true;
 3753: 
 3754: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3755: 		var user = document.classgrade["ctr"+i].value;
 3756: 		user = user.replace(new RegExp(':', 'g'),"_");
 3757: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3758: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3759: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3760: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3761: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3762: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3763: 		if (saveselval == "excused") {
 3764: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3765: 		} else {
 3766: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3767: 		}
 3768: 	    }
 3769: 	}
 3770:     }
 3771: 
 3772: </script>
 3773: VIEWJAVASCRIPT
 3774: }
 3775: 
 3776: #--- show scores for a section or whole class w/ option to change/update a score
 3777: sub viewgrades {
 3778:     my ($request) = shift;
 3779:     &viewgrades_js($request);
 3780: 
 3781:     my ($symb) = &get_symb($request);
 3782:     #need to make sure we have the correct data for later EXT calls, 
 3783:     #thus invalidate the cache
 3784:     &Apache::lonnet::devalidatecourseresdata(
 3785:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3786:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3787:     &Apache::lonnet::clear_EXT_cache_status();
 3788: 
 3789:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3790:     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3791: 
 3792:     #view individual student submission form - called using Javascript viewOneStudent
 3793:     $result.=&jscriptNform($symb);
 3794: 
 3795:     #beginning of class grading form
 3796:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3797:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3798: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3799: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3800: 	&build_section_inputs().
 3801: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3802: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3803: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3804: 
 3805:     #retrieve selected groups
 3806:     my (@groups,$group_display);
 3807:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3808:     if (grep(/^all$/,@groups)) {
 3809:         @groups = ('all');
 3810:     } elsif (grep(/^none$/,@groups)) {
 3811:         @groups = ('none');
 3812:     } elsif (@groups > 0) {
 3813:         $group_display = join(', ',@groups);
 3814:     }
 3815: 
 3816:     my ($common_header,$specific_header,@sections,$section_display);
 3817:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3818:     if (grep(/^all$/,@sections)) {
 3819:         @sections = ('all');
 3820:         if ($group_display) {
 3821:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3822:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3823:         } elsif (grep(/^none$/,@groups)) {
 3824:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3825:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3826:         } else {
 3827:             $common_header = &mt('Assign Common Grade to Class');
 3828:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3829:         }
 3830:     } elsif (grep(/^none$/,@sections)) {
 3831:         @sections = ('none');
 3832:         if ($group_display) {
 3833:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3834:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3835:         } elsif (grep(/^none$/,@groups)) {
 3836:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3837:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3838:         } else {
 3839:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3840:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3841:         }
 3842:     } else {
 3843:         $section_display = join (", ",@sections);
 3844:         if ($group_display) {
 3845:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3846:                                  $section_display,$group_display);
 3847:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3848:                                    $section_display,$group_display);
 3849:         } elsif (grep(/^none$/,@groups)) {
 3850:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3851:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3852:         } else {
 3853:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3854:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3855:         }
 3856:     }
 3857:     my %submit_types = &substatus_options();
 3858:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3859: 
 3860:     if ($env{'form.submitonly'} eq 'all') {
 3861:         $result.= '<h3>'.$common_header.'</h3>';
 3862:     } else {
 3863:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 3864:     }
 3865:     $result .= &Apache::loncommon::start_data_table();
 3866:     #radio buttons/text box for assigning points for a section or class.
 3867:     #handles different parts of a problem
 3868:     my $res_error;
 3869:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3870:     if ($res_error) {
 3871:         return &navmap_errormsg();
 3872:     }
 3873:     my %weight = ();
 3874:     my $ctsparts = 0;
 3875:     my %seen = ();
 3876:     my @part_response_id = &flatten_responseType($responseType);
 3877:     foreach my $part_response_id (@part_response_id) {
 3878:     	my ($partid,$respid) = @{ $part_response_id };
 3879: 	my $part_resp = join('_',@{ $part_response_id });
 3880: 	next if $seen{$partid};
 3881: 	$seen{$partid}++;
 3882: 	my $handgrade=$$handgrade{$part_resp};
 3883: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3884: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3885: 
 3886: 	my $display_part=&get_display_part($partid,$symb);
 3887: 	my $radio.='<table border="0"><tr>';  
 3888: 	my $ctr = 0;
 3889: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3890: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3891: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3892: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3893: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3894: 	    $ctr++;
 3895: 	}
 3896: 	$radio.='</tr></table>';
 3897: 	my $line = '<input type="text" name="TEXTVAL_'.
 3898: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3899: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3900: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3901: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3902:                 '<select name="SELVAL_'.$partid.'" '.
 3903: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 3904: 		$weight{$partid}.')"> '.
 3905: 	    '<option selected="selected"> </option>'.
 3906: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3907: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3908: 	    '</select></td>'.
 3909:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3910: 	$line.='<input type="hidden" name="partid_'.
 3911: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3912: 	$line.='<input type="hidden" name="weight_'.
 3913: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3914: 
 3915: 	$result.=
 3916: 	    &Apache::loncommon::start_data_table_row()."\n".
 3917: 	    '<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>'.
 3918: 	    &Apache::loncommon::end_data_table_row()."\n";
 3919: 	$ctsparts++;
 3920:     }
 3921:     $result.=&Apache::loncommon::end_data_table()."\n".
 3922: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3923:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3924: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3925: 
 3926:     #table listing all the students in a section/class
 3927:     #header of table
 3928:     if ($env{'form.submitonly'} eq 'all') { 
 3929:         $result.= '<h3>'.$specific_header.'</h3>';
 3930:     } else {
 3931:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 3932:     }
 3933:     $result.= &Apache::loncommon::start_data_table().
 3934: 	      &Apache::loncommon::start_data_table_header_row().
 3935: 	      '<th>'.&mt('No.').'</th>'.
 3936: 	      '<th>'.&nameUserString('header')."</th>\n";
 3937:     my $partserror;
 3938:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3939:     if ($partserror) {
 3940:         return &navmap_errormsg();
 3941:     }
 3942:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3943:     my @partids = ();
 3944:     foreach my $part (@parts) {
 3945: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3946:         my $narrowtext = &mt('Tries');
 3947: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3948: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3949: 	my ($partid) = &split_part_type($part);
 3950:         push(@partids,$partid);
 3951: 	my $display_part=&get_display_part($partid,$symb);
 3952: 	if ($display =~ /^Partial Credit Factor/) {
 3953: 	    $result.='<th>'.
 3954:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3955:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3956: 	    next;
 3957: 	    
 3958: 	} else {
 3959: 	    if ($display =~ /Problem Status/) {
 3960: 		my $grade_status_mt = &mt('Grade Status');
 3961: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3962: 	    }
 3963: 	    my $part_mt = &mt('Part:');
 3964: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3965: 	}
 3966: 
 3967: 	$result.='<th>'.$display.'</th>'."\n";
 3968:     }
 3969:     $result.=&Apache::loncommon::end_data_table_header_row();
 3970: 
 3971:     my %last_resets = 
 3972: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3973: 
 3974:     #get info for each student
 3975:     #list all the students - with points and grade status
 3976:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3977:     my $ctr = 0;
 3978:     foreach (sort 
 3979: 	     {
 3980: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3981: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3982: 		 }
 3983: 		 return $a cmp $b;
 3984: 	     } (keys(%$fullname))) {
 3985: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3986: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 3987:     }
 3988:     $result.=&Apache::loncommon::end_data_table();
 3989:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3990:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3991: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3992:     if ($ctr == 0) {
 3993:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3994:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 3995:                 '<span class="LC_warning">';
 3996:         if ($env{'form.submitonly'} eq 'all') {
 3997:             if (grep(/^all$/,@sections)) {
 3998:                 if (grep(/^all$/,@groups)) {
 3999:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4000:                                    $stu_status);
 4001:                 } elsif (grep(/^none$/,@groups)) {
 4002:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4003:                                    $stu_status);
 4004:                 } else {
 4005:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4006:                                    $group_display,$stu_status);
 4007:                 }
 4008:             } elsif (grep(/^none$/,@sections)) {
 4009:                 if (grep(/^all$/,@groups)) {
 4010:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4011:                                    $stu_status);
 4012:                 } elsif (grep(/^none$/,@groups)) {
 4013:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4014:                                    $stu_status);
 4015:                 } else {
 4016:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4017:                                    $group_display,$stu_status);
 4018:                 }
 4019:             } else {
 4020:                 if (grep(/^all$/,@groups)) {
 4021:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4022:                                    $section_display,$stu_status);
 4023:                 } elsif (grep(/^none$/,@groups)) {
 4024:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4025:                                    $section_display,$stu_status);
 4026:                 } else {
 4027:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4028:                                    $section_display,$group_display,$stu_status);
 4029:                 }
 4030:             }
 4031:         } else {
 4032:             if (grep(/^all$/,@sections)) {
 4033:                 if (grep(/^all$/,@groups)) {
 4034:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4035:                                    $stu_status,$submission_status);
 4036:                 } elsif (grep(/^none$/,@groups)) {
 4037:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4038:                                    $stu_status,$submission_status);
 4039:                 } else {
 4040:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4041:                                    $group_display,$stu_status,$submission_status);
 4042:                 }
 4043:             } elsif (grep(/^none$/,@sections)) {
 4044:                 if (grep(/^all$/,@groups)) {
 4045:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4046:                                    $stu_status,$submission_status);
 4047:                 } elsif (grep(/^none$/,@groups)) {
 4048:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4049:                                    $stu_status,$submission_status);
 4050:                 } else {
 4051:                     $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.',
 4052:                                    $group_display,$stu_status,$submission_status);
 4053:                 }
 4054:             } else {
 4055:                 if (grep(/^all$/,@groups)) {
 4056:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4057:                                    $section_display,$stu_status,$submission_status);
 4058:                 } elsif (grep(/^none$/,@groups)) {
 4059:                     $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.',
 4060:                                    $section_display,$stu_status,$submission_status);
 4061:                 } else {
 4062:                     $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.',
 4063:                                    $section_display,$group_display,$stu_status,$submission_status);
 4064:                 }
 4065:             }
 4066: 	}
 4067: 	$result .= '</span><br />';
 4068:     }
 4069:     $result.=&show_grading_menu_form($symb);
 4070:     return $result;
 4071: }
 4072: 
 4073: #--- call by previous routine to display each student who satisfies submission filter.
 4074: sub viewstudentgrade {
 4075:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4076:     my ($uname,$udom) = split(/:/,$student);
 4077:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4078:     my $submitonly = $env{'form.submitonly'};
 4079:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4080:         my %partstatus = ();
 4081:         if (ref($parts) eq 'ARRAY') {
 4082:             foreach my $apart (@{$parts}) {
 4083:                 my ($part,$type) = &split_part_type($apart);
 4084:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4085:                 $status = 'nothing' if ($status eq '');
 4086:                 $partstatus{$part}      = $status;
 4087:                 my $subkey = "resource.$part.submitted_by";
 4088:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4089:             }
 4090:             my $submitted = 0;
 4091:             my $graded = 0;
 4092:             my $incorrect = 0;
 4093:             foreach my $key (keys(%partstatus)) {
 4094:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4095:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4096:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4097: 
 4098:                 my $partid = (split(/\./,$key))[1];
 4099:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4100:                     $submitted = 0;
 4101:                 }
 4102:             }
 4103:             return if (!$submitted && ($submitonly eq 'yes' ||
 4104:                                        $submitonly eq 'incorrect' ||
 4105:                                        $submitonly eq 'graded'));
 4106:             return if (!$graded && ($submitonly eq 'graded'));
 4107:             return if (!$incorrect && $submitonly eq 'incorrect');
 4108:         }
 4109:     }
 4110:     if ($submitonly eq 'queued') {
 4111:         my ($cdom,$cnum) = split(/_/,$courseid);
 4112:         my %queue_status =
 4113:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4114:                                                     $udom,$uname);
 4115:         return if (!defined($queue_status{'gradingqueue'}));
 4116:     }
 4117:     $$ctr++;
 4118:     my %aggregates = ();
 4119:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4120: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4121: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4122: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4123: 	'\');" target="_self">'.$fullname.'</a> '.
 4124: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4125:     $student=~s/:/_/; # colon doen't work in javascript for names
 4126:     foreach my $apart (@$parts) {
 4127: 	my ($part,$type) = &split_part_type($apart);
 4128: 	my $score=$record{"resource.$part.$type"};
 4129:         $result.='<td align="center">';
 4130:         my ($aggtries,$totaltries);
 4131:         unless (exists($aggregates{$part})) {
 4132: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4133: 
 4134: 	    $aggtries = $totaltries;
 4135:             if ($$last_resets{$part}) {  
 4136:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4137: 					   $part);
 4138:             }
 4139:             $result.='<input type="hidden" name="'.
 4140:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4141:             $result.='<input type="hidden" name="'.
 4142:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4143:             $aggregates{$part} = 1;
 4144:         }
 4145: 	if ($type eq 'awarded') {
 4146: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4147: 	    $result.='<input type="hidden" name="'.
 4148: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4149: 	    $result.='<input type="text" name="'.
 4150: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4151:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4152: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4153: 	} elsif ($type eq 'solved') {
 4154: 	    my ($status,$foo)=split(/_/,$score,2);
 4155: 	    $status = 'nothing' if ($status eq '');
 4156: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4157: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4158: 	    $result.='&nbsp;<select name="'.
 4159: 		'GD_'.$student.'_'.$part.'_solved" '.
 4160:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4161: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4162: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4163: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4164: 	    $result.="</select>&nbsp;</td>\n";
 4165: 	} else {
 4166: 	    $result.='<input type="hidden" name="'.
 4167: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4168: 		    "\n";
 4169: 	    $result.='<input type="text" name="'.
 4170: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4171: 		'value="'.$score.'" size="4" /></td>'."\n";
 4172: 	}
 4173:     }
 4174:     $result.=&Apache::loncommon::end_data_table_row();
 4175:     return $result;
 4176: }
 4177: 
 4178: #--- change scores for all the students in a section/class
 4179: #    record does not get update if unchanged
 4180: sub editgrades {
 4181:     my ($request) = @_;
 4182: 
 4183:     my ($symb)=&get_symb($request);
 4184:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4185:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4186:     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 4187:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4188: 
 4189:     my $result= &Apache::loncommon::start_data_table().
 4190: 	&Apache::loncommon::start_data_table_header_row().
 4191: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4192: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4193:     my %scoreptr = (
 4194: 		    'correct'  =>'correct_by_override',
 4195: 		    'incorrect'=>'incorrect_by_override',
 4196: 		    'excused'  =>'excused',
 4197: 		    'ungraded' =>'ungraded_attempted',
 4198:                     'credited' =>'credit_attempted',
 4199: 		    'nothing'  => '',
 4200: 		    );
 4201:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4202: 
 4203:     my (@partid);
 4204:     my %weight = ();
 4205:     my %columns = ();
 4206:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4207: 
 4208:     my $partserror;
 4209:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4210:     if ($partserror) {
 4211:         return &navmap_errormsg();
 4212:     }
 4213:     my $header;
 4214:     while ($ctr < $env{'form.totalparts'}) {
 4215: 	my $partid = $env{'form.partid_'.$ctr};
 4216: 	push(@partid,$partid);
 4217: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4218: 	$ctr++;
 4219:     }
 4220:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4221:     my $totcolspan = 0;
 4222:     foreach my $partid (@partid) {
 4223: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4224: 	    '<th align="center">'.&mt('New Score').'</th>';
 4225: 	$columns{$partid}=2;
 4226: 	foreach my $stores (@parts) {
 4227: 	    my ($part,$type) = &split_part_type($stores);
 4228: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4229: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4230: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4231: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4232:             my $narrowtext = &mt('Tries');
 4233: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4234: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4235: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4236: 	    $columns{$partid}+=2;
 4237: 	}
 4238:         $totcolspan += $columns{$partid};
 4239:     }
 4240:     foreach my $partid (@partid) {
 4241: 	my $display_part=&get_display_part($partid,$symb);
 4242: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4243: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4244: 	    '</th>';
 4245: 
 4246:     }
 4247:     $result .= &Apache::loncommon::end_data_table_header_row().
 4248: 	&Apache::loncommon::start_data_table_header_row().
 4249: 	$header.
 4250: 	&Apache::loncommon::end_data_table_header_row();
 4251:     my @noupdate;
 4252:     my ($updateCtr,$noupdateCtr) = (1,1);
 4253:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4254: 	my $user = $env{'form.ctr'.$i};
 4255: 	my ($uname,$udom)=split(/:/,$user);
 4256: 	my %newrecord;
 4257: 	my $updateflag = 0;
 4258:         my $usec=$classlist->{"$uname:$udom"}[5];
 4259:         my $canmodify = &canmodify($usec);
 4260:         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4261:                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4262:         if (!$canmodify) {
 4263:             push(@noupdate,
 4264:                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4265:                  &mt('Not allowed to modify student')."</span></td>");
 4266:             next;
 4267:         }
 4268:         my %aggregate = ();
 4269:         my $aggregateflag = 0;
 4270: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4271: 	foreach (@partid) {
 4272: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4273: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4274: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4275: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4276: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4277: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4278: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4279: 	    my $score;
 4280: 	    if ($partial eq '') {
 4281: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4282: 	    } elsif ($partial > 0) {
 4283: 		$score = 'correct_by_override';
 4284: 	    } elsif ($partial == 0) {
 4285: 		$score = 'incorrect_by_override';
 4286: 	    }
 4287: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4288: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4289: 
 4290: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4291: 		"$env{'user.name'}:$env{'user.domain'}";
 4292: 	    if ($dropMenu eq 'reset status' &&
 4293: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4294: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4295: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4296: 		$newrecord{'resource.'.$_.'.award'} = '';
 4297: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4298: 		$updateflag = 1;
 4299:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4300:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4301:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4302:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4303:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4304:                     $aggregateflag = 1;
 4305:                 }
 4306: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4307: 		$updateflag = 1;
 4308: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4309: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4310: 		$rec_update++;
 4311: 	    }
 4312: 
 4313: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4314: 		'<td align="center">'.$awarded.
 4315: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4316: 
 4317: 
 4318: 	    my $partid=$_;
 4319: 	    foreach my $stores (@parts) {
 4320: 		my ($part,$type) = &split_part_type($stores);
 4321: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4322: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4323: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4324: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4325: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4326: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4327: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4328: 		    $updateflag=1;
 4329: 		}
 4330: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4331: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4332: 	    }
 4333: 	}
 4334: 	$line.="\n";
 4335: 
 4336: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4337: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4338: 
 4339: 	if ($updateflag) {
 4340: 	    $count++;
 4341: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4342: 				    $udom,$uname);
 4343: 
 4344: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4345: 					      $cnum,$udom,$uname)) {
 4346: 		# need to figure out if should be in queue.
 4347: 		my %record =  
 4348: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4349: 					     $udom,$uname);
 4350: 		my $all_graded = 1;
 4351: 		my $none_graded = 1;
 4352: 		foreach my $part (@parts) {
 4353: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4354: 			$all_graded = 0;
 4355: 		    } else {
 4356: 			$none_graded = 0;
 4357: 		    }
 4358: 		}
 4359: 
 4360: 		if ($all_graded || $none_graded) {
 4361: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4362: 							   $symb,$cdom,$cnum,
 4363: 							   $udom,$uname);
 4364: 		}
 4365: 	    }
 4366: 
 4367: 	    $result.=&Apache::loncommon::start_data_table_row().
 4368: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4369: 		&Apache::loncommon::end_data_table_row();
 4370: 	    $updateCtr++;
 4371: 	} else {
 4372: 	    push(@noupdate,
 4373: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4374: 	    $noupdateCtr++;
 4375: 	}
 4376:         if ($aggregateflag) {
 4377:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4378: 				  $cdom,$cnum);
 4379:         }
 4380:     }
 4381:     if (@noupdate) {
 4382:         my $numcols=$totcolspan+2;
 4383: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4384: 	    '<td align="center" colspan="'.$numcols.'">'.
 4385: 	    &mt('No Changes Occurred For the Students Below').
 4386: 	    '</td>'.
 4387: 	    &Apache::loncommon::end_data_table_row();
 4388: 	foreach my $line (@noupdate) {
 4389: 	    $result.=
 4390: 		&Apache::loncommon::start_data_table_row().
 4391: 		$line.
 4392: 		&Apache::loncommon::end_data_table_row();
 4393: 	}
 4394:     }
 4395:     $result .= &Apache::loncommon::end_data_table().
 4396: 	&show_grading_menu_form($symb);
 4397:     my $msg = '<p><b>'.
 4398: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4399: 	    $rec_update,$count).'</b><br />'.
 4400: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4401: 	'</b></p>';
 4402:     return $title.$msg.$result;
 4403: }
 4404: 
 4405: sub split_part_type {
 4406:     my ($partstr) = @_;
 4407:     my ($temp,@allparts)=split(/_/,$partstr);
 4408:     my $type=pop(@allparts);
 4409:     my $part=join('_',@allparts);
 4410:     return ($part,$type);
 4411: }
 4412: 
 4413: #------------- end of section for handling grading by section/class ---------
 4414: #
 4415: #----------------------------------------------------------------------------
 4416: 
 4417: 
 4418: #----------------------------------------------------------------------------
 4419: #
 4420: #-------------------------- Next few routines handles grading by csv upload
 4421: #
 4422: #--- Javascript to handle csv upload
 4423: sub csvupload_javascript_reverse_associate {
 4424:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4425:     my $error2=&mt('You need to specify at least one grading field');
 4426:   &js_escape(\$error1);
 4427:   &js_escape(\$error2);
 4428:   return(<<ENDPICK);
 4429:   function verify(vf) {
 4430:     var foundsomething=0;
 4431:     var founduname=0;
 4432:     var foundID=0;
 4433:     for (i=0;i<=vf.nfields.value;i++) {
 4434:       tw=eval('vf.f'+i+'.selectedIndex');
 4435:       if (i==0 && tw!=0) { foundID=1; }
 4436:       if (i==1 && tw!=0) { founduname=1; }
 4437:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4438:     }
 4439:     if (founduname==0 && foundID==0) {
 4440: 	alert('$error1');
 4441: 	return;
 4442:     }
 4443:     if (foundsomething==0) {
 4444: 	alert('$error2');
 4445: 	return;
 4446:     }
 4447:     vf.submit();
 4448:   }
 4449:   function flip(vf,tf) {
 4450:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4451:     var i;
 4452:     for (i=0;i<=vf.nfields.value;i++) {
 4453:       //can not pick the same destination field for both name and domain
 4454:       if (((i ==0)||(i ==1)) && 
 4455:           ((tf==0)||(tf==1)) && 
 4456:           (i!=tf) &&
 4457:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4458:         eval('vf.f'+i+'.selectedIndex=0;')
 4459:       }
 4460:     }
 4461:   }
 4462: ENDPICK
 4463: }
 4464: 
 4465: sub csvupload_javascript_forward_associate {
 4466:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4467:     my $error2=&mt('You need to specify at least one grading field');
 4468:   &js_escape(\$error1);
 4469:   &js_escape(\$error2);
 4470:   return(<<ENDPICK);
 4471:   function verify(vf) {
 4472:     var foundsomething=0;
 4473:     var founduname=0;
 4474:     var foundID=0;
 4475:     for (i=0;i<=vf.nfields.value;i++) {
 4476:       tw=eval('vf.f'+i+'.selectedIndex');
 4477:       if (tw==1) { foundID=1; }
 4478:       if (tw==2) { founduname=1; }
 4479:       if (tw>3) { foundsomething=1; }
 4480:     }
 4481:     if (founduname==0 && foundID==0) {
 4482: 	alert('$error1');
 4483: 	return;
 4484:     }
 4485:     if (foundsomething==0) {
 4486: 	alert('$error2');
 4487: 	return;
 4488:     }
 4489:     vf.submit();
 4490:   }
 4491:   function flip(vf,tf) {
 4492:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4493:     var i;
 4494:     //can not pick the same destination field twice
 4495:     for (i=0;i<=vf.nfields.value;i++) {
 4496:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4497:         eval('vf.f'+i+'.selectedIndex=0;')
 4498:       }
 4499:     }
 4500:   }
 4501: ENDPICK
 4502: }
 4503: 
 4504: sub csvuploadmap_header {
 4505:     my ($request,$symb,$datatoken,$distotal)= @_;
 4506:     my $javascript;
 4507:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4508: 	$javascript=&csvupload_javascript_reverse_associate();
 4509:     } else {
 4510: 	$javascript=&csvupload_javascript_forward_associate();
 4511:     }
 4512: 
 4513:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4514:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4515:     my $ignore=&mt('Ignore First Line');
 4516:     $symb = &Apache::lonenc::check_encrypt($symb);
 4517:     $request->print(<<ENDPICK);
 4518: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4519: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4520: $result
 4521: <hr />
 4522: <h3>Identify fields</h3>
 4523: Total number of records found in file: $distotal <hr />
 4524: Enter as many fields as you can. The system will inform you and bring you back
 4525: to this page if the data selected is insufficient to run your class.<hr />
 4526: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4527: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4528: <input type="hidden" name="associate"  value="" />
 4529: <input type="hidden" name="phase"      value="three" />
 4530: <input type="hidden" name="datatoken"  value="$datatoken" />
 4531: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4532: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4533: <input type="hidden" name="upfile_associate" 
 4534:                                        value="$env{'form.upfile_associate'}" />
 4535: <input type="hidden" name="symb"       value="$symb" />
 4536: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4537: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4538: <input type="hidden" name="command"    value="csvuploadoptions" />
 4539: <hr />
 4540: <script type="text/javascript" language="Javascript">
 4541: $javascript
 4542: </script>
 4543: ENDPICK
 4544:     return '';
 4545: 
 4546: }
 4547: 
 4548: sub csvupload_fields {
 4549:     my ($symb,$errorref) = @_;
 4550:     my (@parts) = &getpartlist($symb,$errorref);
 4551:     if (ref($errorref)) {
 4552:         if ($$errorref) {
 4553:             return;
 4554:         }
 4555:     }
 4556: 
 4557:     my @fields=(['ID','Student/Employee ID'],
 4558: 		['username','Student Username'],
 4559: 		['domain','Student Domain']);
 4560:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4561:     foreach my $part (sort(@parts)) {
 4562: 	my @datum;
 4563: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4564: 	my $name=$part;
 4565: 	if  (!$display) { $display = $name; }
 4566: 	@datum=($name,$display);
 4567: 	if ($name=~/^stores_(.*)_awarded/) {
 4568: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4569: 	}
 4570: 	push(@fields,\@datum);
 4571:     }
 4572:     return (@fields);
 4573: }
 4574: 
 4575: sub csvuploadmap_footer {
 4576:     my ($request,$i,$keyfields) =@_;
 4577:     my $buttontext = &mt('Assign Grades');
 4578:     $request->print(<<ENDPICK);
 4579: </table>
 4580: <input type="hidden" name="nfields" value="$i" />
 4581: <input type="hidden" name="keyfields" value="$keyfields" />
 4582: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4583: </form>
 4584: ENDPICK
 4585: }
 4586: 
 4587: sub checkforfile_js {
 4588:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4589:     &js_escape(\$alertmsg);
 4590:     my $result =<<CSVFORMJS;
 4591: <script type="text/javascript" language="javascript">
 4592:     function checkUpload(formname) {
 4593: 	if (formname.upfile.value == "") {
 4594: 	    alert("$alertmsg");
 4595: 	    return false;
 4596: 	}
 4597: 	formname.submit();
 4598:     }
 4599:     </script>
 4600: CSVFORMJS
 4601:     return $result;
 4602: }
 4603: 
 4604: sub upcsvScores_form {
 4605:     my ($request) = shift;
 4606:     my ($symb)=&get_symb($request);
 4607:     if (!$symb) {return '';}
 4608:     my $result=&checkforfile_js();
 4609:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4610:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4611:     $result.=$table;
 4612:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4613:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4614:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4615: 	'</b></td></tr>'."\n";
 4616:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4617:     my $upload=&mt("Upload Scores");
 4618:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4619:     my $ignore=&mt('Ignore First Line');
 4620:     $symb = &Apache::lonenc::check_encrypt($symb);
 4621:     $result.=<<ENDUPFORM;
 4622: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4623: <input type="hidden" name="symb" value="$symb" />
 4624: <input type="hidden" name="command" value="csvuploadmap" />
 4625: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4626: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4627: $upfile_select
 4628: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4629: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4630: </form>
 4631: ENDUPFORM
 4632:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4633:                            &mt("How do I create a CSV file from a spreadsheet"))
 4634:     .'</td></tr></table>'."\n";
 4635:     $result.='</td></tr></table><br /><br />'."\n";
 4636:     $result.=&show_grading_menu_form($symb);
 4637:     return $result;
 4638: }
 4639: 
 4640: 
 4641: sub csvuploadmap {
 4642:     my ($request)= @_;
 4643:     my ($symb)=&get_symb($request);
 4644:     if (!$symb) {return '';}
 4645: 
 4646:     my $datatoken;
 4647:     if (!$env{'form.datatoken'}) {
 4648: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4649:     } else {
 4650:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4651:         if ($datatoken ne '') { 
 4652: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4653:         }
 4654:     }
 4655:     my @records=&Apache::loncommon::upfile_record_sep();
 4656:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4657:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4658:     my ($i,$keyfields);
 4659:     if (@records) {
 4660:         my $fieldserror;
 4661: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4662:         if ($fieldserror) {
 4663:             $request->print(&navmap_errormsg());
 4664:             return;
 4665:         }
 4666: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4667: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4668: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4669: 							  \@fields);
 4670: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4671: 	    chop($keyfields);
 4672: 	} else {
 4673: 	    unshift(@fields,['none','']);
 4674: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4675: 							    \@fields);
 4676:             foreach my $rec (@records) {
 4677:                 my %temp = &Apache::loncommon::record_sep($rec);
 4678:                 if (%temp) {
 4679:                     $keyfields=join(',',sort(keys(%temp)));
 4680:                     last;
 4681:                 }
 4682:             }
 4683: 	}
 4684:     }
 4685:     &csvuploadmap_footer($request,$i,$keyfields);
 4686:     $request->print(&show_grading_menu_form($symb));
 4687: 
 4688:     return '';
 4689: }
 4690: 
 4691: sub csvuploadoptions {
 4692:     my ($request)= @_;
 4693:     my ($symb)=&get_symb($request);
 4694:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4695:     my $ignore=&mt('Ignore First Line');
 4696:     $request->print(<<ENDPICK);
 4697: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4698: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4699: <input type="hidden" name="command"    value="csvuploadassign" />
 4700: <!--
 4701: <p>
 4702: <label>
 4703:    <input type="checkbox" name="show_full_results" />
 4704:    Show a table of all changes
 4705: </label>
 4706: </p>
 4707: -->
 4708: <p>
 4709: <label>
 4710:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4711:    Overwrite any existing score
 4712: </label>
 4713: </p>
 4714: ENDPICK
 4715:     my %fields=&get_fields();
 4716:     if (!defined($fields{'domain'})) {
 4717: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4718: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4719:     }
 4720:     foreach my $key (sort(keys(%env))) {
 4721: 	if ($key !~ /^form\.(.*)$/) { next; }
 4722: 	my $cleankey=$1;
 4723: 	if ($cleankey eq 'command') { next; }
 4724: 	$request->print('<input type="hidden" name="'.$cleankey.
 4725: 			'"  value="'.$env{$key}.'" />'."\n");
 4726:     }
 4727:     # FIXME do a check for any duplicated user ids...
 4728:     # FIXME do a check for any invalid user ids?...
 4729:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4730: <hr /></form>'."\n");
 4731:     $request->print(&show_grading_menu_form($symb));
 4732:     return '';
 4733: }
 4734: 
 4735: sub get_fields {
 4736:     my %fields;
 4737:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4738:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4739: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4740: 	    if ($env{'form.f'.$i} ne 'none') {
 4741: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4742: 	    }
 4743: 	} else {
 4744: 	    if ($env{'form.f'.$i} ne 'none') {
 4745: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4746: 	    }
 4747: 	}
 4748:     }
 4749:     return %fields;
 4750: }
 4751: 
 4752: sub csvuploadassign {
 4753:     my ($request)= @_;
 4754:     my ($symb)=&get_symb($request);
 4755:     if (!$symb) {return '';}
 4756:     my $error_msg = '';
 4757:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4758:     if ($datatoken ne '') {
 4759:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4760:     }
 4761:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4762:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4763:     my %fields=&get_fields();
 4764:     $request->print('<h3>Assigning Grades</h3>');
 4765:     my $courseid=$env{'request.course.id'};
 4766:     my ($classlist) = &getclasslist('all',0);
 4767:     my @notallowed;
 4768:     my @skipped;
 4769:     my @warnings;
 4770:     my $countdone=0;
 4771:     foreach my $grade (@gradedata) {
 4772: 	my %entries=&Apache::loncommon::record_sep($grade);
 4773: 	my $domain;
 4774: 	if ($entries{$fields{'domain'}}) {
 4775: 	    $domain=$entries{$fields{'domain'}};
 4776: 	} else {
 4777: 	    $domain=$env{'form.default_domain'};
 4778: 	}
 4779: 	$domain=~s/\s//g;
 4780: 	my $username=$entries{$fields{'username'}};
 4781: 	$username=~s/\s//g;
 4782: 	if (!$username) {
 4783: 	    my $id=$entries{$fields{'ID'}};
 4784: 	    $id=~s/\s//g;
 4785: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4786: 	    $username=$ids{$id};
 4787: 	}
 4788: 	if (!exists($$classlist{"$username:$domain"})) {
 4789: 	    my $id=$entries{$fields{'ID'}};
 4790: 	    $id=~s/\s//g;
 4791: 	    if ($id) {
 4792: 		push(@skipped,"$id:$domain");
 4793: 	    } else {
 4794: 		push(@skipped,"$username:$domain");
 4795: 	    }
 4796: 	    next;
 4797: 	}
 4798: 	my $usec=$classlist->{"$username:$domain"}[5];
 4799: 	if (!&canmodify($usec)) {
 4800: 	    push(@notallowed,"$username:$domain");
 4801: 	    next;
 4802: 	}
 4803: 	my %points;
 4804: 	my %grades;
 4805: 	foreach my $dest (keys(%fields)) {
 4806: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4807: 		$dest eq 'domain') { next; }
 4808: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4809: 	    if ($dest=~/stores_(.*)_points/) {
 4810: 		my $part=$1;
 4811: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4812: 					      $symb,$domain,$username);
 4813:                 if ($wgt) {
 4814:                     $entries{$fields{$dest}}=~s/\s//g;
 4815:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4816:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4817:                                           : 'correct_by_override';
 4818:                     if ($pcr>1) {
 4819:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4820:                     }
 4821:                     $grades{"resource.$part.awarded"}=$pcr;
 4822:                     $grades{"resource.$part.solved"}=$award;
 4823:                     $points{$part}=1;
 4824:                 } else {
 4825:                     $error_msg = "<br />" .
 4826:                         &mt("Some point values were assigned"
 4827:                             ." for problems with a weight "
 4828:                             ."of zero. These values were "
 4829:                             ."ignored.");
 4830:                 }
 4831: 	    } else {
 4832: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4833: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4834: 		my $store_key=$dest;
 4835: 		$store_key=~s/^stores/resource/;
 4836: 		$store_key=~s/_/\./g;
 4837: 		$grades{$store_key}=$entries{$fields{$dest}};
 4838: 	    }
 4839: 	}
 4840: 	if (! %grades) { 
 4841:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4842:         } else {
 4843: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4844: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4845: 					   $env{'request.course.id'},
 4846: 					   $domain,$username);
 4847: 	   if ($result eq 'ok') {
 4848: 	      $request->print('.');
 4849: # Remove from grading queue
 4850:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4851:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4852:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4853:                                              $domain,$username);
 4854: 	   } else {
 4855: 	      $request->print("<p><span class=\"LC_error\">".
 4856:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4857:                                   "$username:$domain",$result)."</span></p>");
 4858: 	   }
 4859: 	   $request->rflush();
 4860: 	   $countdone++;
 4861:         }
 4862:     }
 4863:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4864:     if (@warnings) {
 4865:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4866:         $request->print(join(', ',@warnings));
 4867:     }
 4868:     if (@skipped) {
 4869: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4870:         $request->print(join(', ',@skipped));
 4871:     }
 4872:     if (@notallowed) {
 4873: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4874: 	$request->print(join(', ',@notallowed));
 4875:     }
 4876:     $request->print("<br />\n");
 4877:     $request->print(&show_grading_menu_form($symb));
 4878:     return $error_msg;
 4879: }
 4880: #------------- end of section for handling csv file upload ---------
 4881: #
 4882: #-------------------------------------------------------------------
 4883: #
 4884: #-------------- Next few routines handle grading by page/sequence
 4885: #
 4886: #--- Select a page/sequence and a student to grade
 4887: sub pickStudentPage {
 4888:     my ($request) = shift;
 4889: 
 4890:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4891:     &js_escape(\$alertmsg);
 4892:     $request->print(<<LISTJAVASCRIPT);
 4893: <script type="text/javascript" language="javascript">
 4894: 
 4895: function checkPickOne(formname) {
 4896:     if (radioSelection(formname.student) == null) {
 4897: 	alert("$alertmsg");
 4898: 	return;
 4899:     }
 4900:     ptr = pullDownSelection(formname.selectpage);
 4901:     formname.page.value = formname["page"+ptr].value;
 4902:     formname.title.value = formname["title"+ptr].value;
 4903:     formname.submit();
 4904: }
 4905: 
 4906: </script>
 4907: LISTJAVASCRIPT
 4908:     &commonJSfunctions($request);
 4909:     my ($symb) = &get_symb($request);
 4910:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4911:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4912:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4913: 
 4914:     my $result='<h3><span class="LC_info">&nbsp;'.
 4915: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4916: 
 4917:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4918:     my $map_error;
 4919:     my ($titles,$symbx) = &getSymbMap($map_error);
 4920:     if ($map_error) {
 4921:         $request->print(&navmap_errormsg());
 4922:         return; 
 4923:     }
 4924:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4925: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4926: #    my $type=($curpage =~ /\.(page|sequence)/);
 4927:     my $select = '<select name="selectpage">'."\n";
 4928:     my $ctr=0;
 4929:     foreach (@$titles) {
 4930: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4931: 	$select.='<option value="'.$ctr.'" '.
 4932: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4933: 	    '>'.$showtitle.'</option>'."\n";
 4934: 	$ctr++;
 4935:     }
 4936:     $select.= '</select>';
 4937:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4938: 
 4939:     $ctr=0;
 4940:     foreach (@$titles) {
 4941: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4942: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4943: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4944: 	$ctr++;
 4945:     }
 4946:     $result.='<input type="hidden" name="page" />'."\n".
 4947: 	'<input type="hidden" name="title" />'."\n";
 4948: 
 4949:     my $options =
 4950: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4951: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4952:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4953: 
 4954:     $options =
 4955: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4956: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4957: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4958:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4959:     
 4960:     $result.=&build_section_inputs();
 4961:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4962:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4963: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4964: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4965: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4966: 
 4967:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4968: 
 4969:     $result.='&nbsp;<input type="button" '.
 4970:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4971: 
 4972:     $request->print($result);
 4973: 
 4974:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4975: 	&Apache::loncommon::start_data_table().
 4976: 	&Apache::loncommon::start_data_table_header_row().
 4977: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4978: 	'<th>'.&nameUserString('header').'</th>'.
 4979: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4980: 	'<th>'.&nameUserString('header').'</th>'.
 4981: 	&Apache::loncommon::end_data_table_header_row();
 4982:  
 4983:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4984:     my $ptr = 1;
 4985:     foreach my $student (sort 
 4986: 			 {
 4987: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4988: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4989: 			     }
 4990: 			     return $a cmp $b;
 4991: 			 } (keys(%$fullname))) {
 4992: 	my ($uname,$udom) = split(/:/,$student);
 4993: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4994:                                   : '</td>');
 4995: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4996: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4997: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4998: 	$studentTable.=
 4999: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5000:                          : '');
 5001: 	$ptr++;
 5002:     }
 5003:     if ($ptr%2 == 0) {
 5004: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5005: 	    &Apache::loncommon::end_data_table_row();
 5006:     }
 5007:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5008:     $studentTable.='<input type="button" '.
 5009:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5010: 
 5011:     $studentTable.=&show_grading_menu_form($symb);
 5012:     $request->print($studentTable);
 5013: 
 5014:     return '';
 5015: }
 5016: 
 5017: sub getSymbMap {
 5018:     my ($map_error) = @_;
 5019:     my $navmap = Apache::lonnavmaps::navmap->new();
 5020:     unless (ref($navmap)) {
 5021:         if (ref($map_error)) {
 5022:             $$map_error = 'navmap';
 5023:         }
 5024:         return;
 5025:     }
 5026:     my %symbx = ();
 5027:     my @titles = ();
 5028:     my $minder = 0;
 5029: 
 5030:     # Gather every sequence that has problems.
 5031:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5032: 					       1,0,1);
 5033:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5034: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 5035: 	    my $title = $minder.'.'.
 5036: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5037: 	    push(@titles, $title); # minder in case two titles are identical
 5038: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5039: 	    $minder++;
 5040: 	}
 5041:     }
 5042:     return \@titles,\%symbx;
 5043: }
 5044: 
 5045: #
 5046: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5047: sub displayPage {
 5048:     my ($request) = shift;
 5049: 
 5050:     my ($symb) = &get_symb($request);
 5051:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5052:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5053:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5054:     my $pageTitle = $env{'form.page'};
 5055:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5056:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5057:     my $usec=$classlist->{$env{'form.student'}}[5];
 5058: 
 5059:     #need to make sure we have the correct data for later EXT calls, 
 5060:     #thus invalidate the cache
 5061:     &Apache::lonnet::devalidatecourseresdata(
 5062:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5063:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5064:     &Apache::lonnet::clear_EXT_cache_status();
 5065: 
 5066:     if (!&canview($usec)) {
 5067: 	$request->print('<span class="LC_warning">'.
 5068:                         &mt('Unable to view requested student. ([_1])',
 5069:                             $env{'form.student'}).
 5070:                         '</span>');
 5071:         $request->print(&show_grading_menu_form($symb));
 5072:         return;
 5073:     }
 5074:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5075:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5076: 	'</h3>'."\n";
 5077:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5078:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5079: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5080:     } else {
 5081: 	delete($env{'form.CODE'});
 5082:     }
 5083:     &sub_page_js($request);
 5084:     $request->print($result);
 5085: 
 5086:     my $navmap = Apache::lonnavmaps::navmap->new();
 5087:     unless (ref($navmap)) {
 5088:         $request->print(&navmap_errormsg());
 5089:         $request->print(&show_grading_menu_form($symb));
 5090:         return;
 5091:     }
 5092:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5093:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5094:     if (!$map) {
 5095: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5096: 	$request->print(&show_grading_menu_form($symb));
 5097: 	return; 
 5098:     }
 5099:     my $iterator = $navmap->getIterator($map->map_start(),
 5100: 					$map->map_finish());
 5101: 
 5102:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5103: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5104: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5105: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5106: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5107: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5108: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5109: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 5110: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 5111: 
 5112:     if (defined($env{'form.CODE'})) {
 5113: 	$studentTable.=
 5114: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5115:     }
 5116:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5117: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5118: 
 5119:     $studentTable.='&nbsp;<span class="LC_info">'.
 5120:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5121:         '</span>'."\n".
 5122: 	&Apache::loncommon::start_data_table().
 5123: 	&Apache::loncommon::start_data_table_header_row().
 5124: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 5125: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5126: 	&Apache::loncommon::end_data_table_header_row();
 5127: 
 5128:     &Apache::lonxml::clear_problem_counter();
 5129:     my ($depth,$question,$prob) = (1,1,1);
 5130:     $iterator->next(); # skip the first BEGIN_MAP
 5131:     my $curRes = $iterator->next(); # for "current resource"
 5132:     while ($depth > 0) {
 5133:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5134:         if($curRes == $iterator->END_MAP) { $depth--; }
 5135: 
 5136:         if (ref($curRes) && $curRes->is_problem()) {
 5137: 	    my $parts = $curRes->parts();
 5138:             my $title = $curRes->compTitle();
 5139: 	    my $symbx = $curRes->symb();
 5140: 	    $studentTable.=
 5141: 		&Apache::loncommon::start_data_table_row().
 5142: 		'<td align="center" valign="top" >'.$prob.
 5143: 		(scalar(@{$parts}) == 1 ? '' 
 5144: 		                        : '<br />('.&mt('[_1]parts',
 5145: 							scalar(@{$parts}).'&nbsp;').')'
 5146: 		 ).
 5147: 		 '</td>';
 5148: 	    $studentTable.='<td valign="top">';
 5149: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5150: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5151: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5152: 					     undef,'both',\%form);
 5153: 	    } else {
 5154: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5155: 		$companswer =~ s|<form(.*?)>||g;
 5156: 		$companswer =~ s|</form>||g;
 5157: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5158: #		    $companswer =~ s/$1/ /ms;
 5159: #		    $request->print('match='.$1."<br />\n");
 5160: #		}
 5161: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5162: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5163: 	    }
 5164: 
 5165: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5166: 
 5167: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5168: 		if ($record{'version'} eq '') {
 5169: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5170: 		} else {
 5171: 		    my %responseType = ();
 5172: 		    foreach my $partid (@{$parts}) {
 5173: 			my @responseIds =$curRes->responseIds($partid);
 5174: 			my @responseType =$curRes->responseType($partid);
 5175: 			my %responseIds;
 5176: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5177: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5178: 			}
 5179: 			$responseType{$partid} = \%responseIds;
 5180: 		    }
 5181: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5182: 
 5183: 		}
 5184: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5185: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5186:                 my $identifier = (&canmodify($usec)? $prob : '');
 5187: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5188: 									$env{'request.course.id'},
 5189: 									'','.submission',undef,
 5190:                                                                         $usec,$identifier);
 5191:  
 5192: 	    }
 5193: 	    if (&canmodify($usec)) {
 5194:             $studentTable.=&gradeBox_start();
 5195: 		foreach my $partid (@{$parts}) {
 5196: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5197: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5198: 		    $question++;
 5199: 		}
 5200:             $studentTable.=&gradeBox_end();
 5201: 		$prob++;
 5202: 	    }
 5203: 	    $studentTable.='</td></tr>';
 5204: 
 5205: 	}
 5206:         $curRes = $iterator->next();
 5207:     }
 5208: 
 5209:     $studentTable.=
 5210:         '</table>'."\n".
 5211:         '<input type="button" value="'.&mt('Save').'" '.
 5212:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5213:         '</form>'."\n";
 5214:     $studentTable.=&show_grading_menu_form($symb);
 5215:     $request->print($studentTable);
 5216: 
 5217:     return '';
 5218: }
 5219: 
 5220: sub displaySubByDates {
 5221:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5222:     my $isCODE=0;
 5223:     my $isTask = ($symb =~/\.task$/);
 5224:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5225:     my $studentTable=&Apache::loncommon::start_data_table().
 5226: 	&Apache::loncommon::start_data_table_header_row().
 5227: 	'<th>'.&mt('Date/Time').'</th>'.
 5228: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5229:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5230: 	'<th>'.&mt('Submission').'</th>'.
 5231: 	'<th>'.&mt('Status').'</th>'.
 5232: 	&Apache::loncommon::end_data_table_header_row();
 5233:     my ($version);
 5234:     my %mark;
 5235:     my %orders;
 5236:     $mark{'correct_by_student'} = $checkIcon;
 5237:     if (!exists($$record{'1:timestamp'})) {
 5238: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5239:     }
 5240: 
 5241:     my $interaction;
 5242:     my $no_increment = 1;
 5243:     my (%lastrndseed,%lasttype);
 5244:     for ($version=1;$version<=$$record{'version'};$version++) {
 5245: 	my $timestamp = 
 5246: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5247: 	if (exists($$record{$version.':resource.0.version'})) {
 5248: 	    $interaction = $$record{$version.':resource.0.version'};
 5249: 	}
 5250:         if ($isTask && $env{'form.previousversion'}) {
 5251:             next unless ($interaction == $env{'form.previousversion'});
 5252:         }
 5253: 	my $where = ($isTask ? "$version:resource.$interaction"
 5254: 		             : "$version:resource");
 5255: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5256: 	    '<td>'.$timestamp.'</td>';
 5257: 	if ($isCODE) {
 5258: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5259: 	}
 5260:         if ($isTask) {
 5261:             $studentTable.='<td>'.$interaction.'</td>';
 5262:         }
 5263: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5264: 	my @displaySub = ();
 5265: 	foreach my $partid (@{$parts}) {
 5266:             my ($hidden,$type);
 5267:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5268:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5269:                 $hidden = 1;
 5270:             }
 5271: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 5272: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5273: 	    
 5274: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5275: 	    my $display_part=&get_display_part($partid,$symb);
 5276: 	    foreach my $matchKey (@matchKey) {
 5277: 		if (exists($$record{$version.':'.$matchKey}) &&
 5278: 		    $$record{$version.':'.$matchKey} ne '') {
 5279:                     
 5280: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5281: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5282:                     $displaySub[0].='<span class="LC_nobreak">';
 5283:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5284:                                    .' <span class="LC_internal_info">'
 5285:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5286:                                    .'</span>'
 5287:                                    .' <b>';
 5288:                     if ($hidden) {
 5289:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5290:                     } else {
 5291:                         my ($trial,$rndseed,$newvariation);
 5292:                         if ($type eq 'randomizetry') {
 5293:                             $trial = $$record{"$where.$partid.tries"};
 5294:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5295:                         }
 5296: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5297: 			    $displaySub[0].=&mt('Trial not counted');
 5298: 		        } else {
 5299: 			    $displaySub[0].=&mt('Trial: [_1]',
 5300: 					    $$record{"$where.$partid.tries"});
 5301:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5302:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5303:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5304:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5305:                                 }
 5306:                             }
 5307:                             $lastrndseed{$partid} = $rndseed;
 5308:                             $lasttype{$partid} = $type;
 5309: 		        }
 5310: 		        my $responseType=($isTask ? 'Task'
 5311:                                               : $responseType->{$partid}->{$responseId});
 5312: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5313: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5314: 			    $orders{$partid}->{$responseId}=
 5315: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5316:                                            $no_increment,$type,$trial,$rndseed);
 5317: 		        }
 5318: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5319: 		        $displaySub[0].='&nbsp; '.
 5320: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5321:                     }
 5322: 		}
 5323: 	    }
 5324: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5325: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5326: 				    $$record{"$where.$partid.checkedin"},
 5327: 				    $$record{"$where.$partid.checkedin.slot"}).
 5328: 					'<br />';
 5329: 	    }
 5330: 	    if (exists $$record{"$where.$partid.award"}) {
 5331: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5332: 		    lc($$record{"$where.$partid.award"}).' '.
 5333: 		    $mark{$$record{"$where.$partid.solved"}}.
 5334: 		    '<br />';
 5335: 	    }
 5336: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5337: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5338: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5339: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5340: 		$displaySub[2].=
 5341: 		    $$record{"$version:resource.$partid.regrader"}.
 5342: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5343: 	    }
 5344: 	}
 5345: 	# needed because old essay regrader has not parts info
 5346: 	if (exists $$record{"$version:resource.regrader"}) {
 5347: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5348: 	}
 5349: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5350: 	if ($displaySub[2]) {
 5351: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5352: 	}
 5353: 	$studentTable.='&nbsp;</td>'.
 5354: 	    &Apache::loncommon::end_data_table_row();
 5355:     }
 5356:     $studentTable.=&Apache::loncommon::end_data_table();
 5357:     return $studentTable;
 5358: }
 5359: 
 5360: sub updateGradeByPage {
 5361:     my ($request) = shift;
 5362: 
 5363:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5364:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5365:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5366:     my $pageTitle = $env{'form.page'};
 5367:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5368:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5369:     my $usec=$classlist->{$env{'form.student'}}[5];
 5370:     if (!&canmodify($usec)) {
 5371: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5372: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5373: 	return;
 5374:     }
 5375:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5376:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5377: 	'</h3>'."\n";
 5378: 
 5379:     $request->print($result);
 5380: 
 5381: 
 5382:     my $navmap = Apache::lonnavmaps::navmap->new();
 5383:     unless (ref($navmap)) {
 5384:         $request->print(&navmap_errormsg());
 5385:         return;
 5386:     }
 5387:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5388:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5389:     if (!$map) {
 5390: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5391: 	my ($symb)=&get_symb($request);
 5392: 	$request->print(&show_grading_menu_form($symb));
 5393: 	return; 
 5394:     }
 5395:     my $iterator = $navmap->getIterator($map->map_start(),
 5396: 					$map->map_finish());
 5397: 
 5398:     my $studentTable=
 5399: 	&Apache::loncommon::start_data_table().
 5400: 	&Apache::loncommon::start_data_table_header_row().
 5401: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5402: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5403: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5404: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5405: 	&Apache::loncommon::end_data_table_header_row();
 5406: 
 5407:     $iterator->next(); # skip the first BEGIN_MAP
 5408:     my $curRes = $iterator->next(); # for "current resource"
 5409:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5410:     while ($depth > 0) {
 5411:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5412:         if($curRes == $iterator->END_MAP) { $depth--; }
 5413: 
 5414:         if (ref($curRes) && $curRes->is_problem()) {
 5415: 	    my $parts = $curRes->parts();
 5416:             my $title = $curRes->compTitle();
 5417: 	    my $symbx = $curRes->symb();
 5418: 	    $studentTable.=
 5419: 		&Apache::loncommon::start_data_table_row().
 5420: 		'<td align="center" valign="top" >'.$prob.
 5421: 		(scalar(@{$parts}) == 1 ? '' 
 5422:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5423: 		.')').'</td>';
 5424: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5425: 
 5426: 	    my %newrecord=();
 5427: 	    my @displayPts=();
 5428:             my %aggregate = ();
 5429:             my $aggregateflag = 0;
 5430:             if ($env{'form.HIDE'.$prob}) {
 5431:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5432:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5433:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5434:                 $hideflag += $numchgs;
 5435:             }
 5436: 	    foreach my $partid (@{$parts}) {
 5437: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5438: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5439: 
 5440: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5441: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5442: 		my $partial = $newpts/$wgt;
 5443: 		my $score;
 5444: 		if ($partial > 0) {
 5445: 		    $score = 'correct_by_override';
 5446: 		} elsif ($newpts ne '') { #empty is taken as 0
 5447: 		    $score = 'incorrect_by_override';
 5448: 		}
 5449: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5450: 		if ($dropMenu eq 'excused') {
 5451: 		    $partial = '';
 5452: 		    $score = 'excused';
 5453: 		} elsif ($dropMenu eq 'reset status'
 5454: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5455: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5456: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5457: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5458: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5459: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5460: 		    $changeflag++;
 5461: 		    $newpts = '';
 5462:                     
 5463:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5464:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5465:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5466:                     if ($aggtries > 0) {
 5467:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5468:                         $aggregateflag = 1;
 5469:                     }
 5470: 		}
 5471: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5472: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5473: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5474: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5475: 		    '&nbsp;<br />';
 5476: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5477: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5478: 		    '&nbsp;<br />';
 5479: 		$question++;
 5480: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5481: 
 5482: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5483: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5484: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5485: 		    if (scalar(keys(%newrecord)) > 0);
 5486: 
 5487: 		$changeflag++;
 5488: 	    }
 5489: 	    if (scalar(keys(%newrecord)) > 0) {
 5490: 		my %record = 
 5491: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5492: 					     $udom,$uname);
 5493: 
 5494: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5495: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5496: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5497: 		    $newrecord{'resource.CODE'} = '';
 5498: 		}
 5499: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5500: 					$udom,$uname);
 5501: 		%record = &Apache::lonnet::restore($symbx,
 5502: 						   $env{'request.course.id'},
 5503: 						   $udom,$uname);
 5504: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5505: 					     $cdom,$cnum,$udom,$uname);
 5506: 	    }
 5507: 	    
 5508:             if ($aggregateflag) {
 5509:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5510:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5511:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5512:             }
 5513: 
 5514: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5515: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5516: 		&Apache::loncommon::end_data_table_row();
 5517: 
 5518: 	    $prob++;
 5519: 	}
 5520:         $curRes = $iterator->next();
 5521:     }
 5522: 
 5523:     $studentTable.=&Apache::loncommon::end_data_table();
 5524:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5525:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5526: 		  &mt('The scores were changed for [quant,_1,problem].',
 5527: 		  $changeflag).'<br />');
 5528:     my $hidemsg=($hideflag == 0 ? '' :
 5529:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5530:                      $hideflag).'<br />');
 5531:     $request->print($hidemsg.$grademsg.$studentTable);
 5532: 
 5533:     return '';
 5534: }
 5535: 
 5536: #-------- end of section for handling grading by page/sequence ---------
 5537: #
 5538: #-------------------------------------------------------------------
 5539: 
 5540: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5541: #
 5542: #------ start of section for handling grading by page/sequence ---------
 5543: 
 5544: =pod
 5545: 
 5546: =head1 Bubble sheet grading routines
 5547: 
 5548:   For this documentation:
 5549: 
 5550:    'scanline' refers to the full line of characters
 5551:    from the file that we are parsing that represents one entire sheet
 5552: 
 5553:    'bubble line' refers to the data
 5554:    representing the line of bubbles that are on the physical bubblesheet
 5555: 
 5556: 
 5557: The overall process is that a scanned in bubblesheet data is uploaded
 5558: into a course. When a user wants to grade, they select a
 5559: sequence/folder of resources, a file of bubblesheet info, and pick
 5560: one of the predefined configurations for what each scanline looks
 5561: like.
 5562: 
 5563: Next each scanline is checked for any errors of either 'missing
 5564: bubbles' (it's an error because it may have been mis-scanned
 5565: because too light bubbling), 'double bubble' (each bubble line should
 5566: have no more than one letter picked), invalid or duplicated CODE,
 5567: invalid student/employee ID
 5568: 
 5569: If the CODE option is used that determines the randomization of the
 5570: homework problems, either way the student/employee ID is looked up into a
 5571: username:domain.
 5572: 
 5573: During the validation phase the instructor can choose to skip scanlines. 
 5574: 
 5575: After the validation phase, there are now 3 bubblesheet files
 5576: 
 5577:   scantron_original_filename (unmodified original file)
 5578:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5579:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5580: 
 5581: Also there is a separate hash nohist_scantrondata that contains extra
 5582: correction information that isn't representable in the bubblesheet
 5583: file (see &scantron_getfile() for more information)
 5584: 
 5585: After all scanlines are either valid, marked as valid or skipped, then
 5586: foreach line foreach problem in the picked sequence, an ssi request is
 5587: made that simulates a user submitting their selected letter(s) against
 5588: the homework problem.
 5589: 
 5590: =over 4
 5591: 
 5592: 
 5593: 
 5594: =item defaultFormData
 5595: 
 5596:   Returns html hidden inputs used to hold context/default values.
 5597: 
 5598:  Arguments:
 5599:   $symb - $symb of the current resource 
 5600: 
 5601: =cut
 5602: 
 5603: sub defaultFormData {
 5604:     my ($symb)=@_;
 5605:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5606:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5607:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5608: }
 5609: 
 5610: 
 5611: =pod 
 5612: 
 5613: =item getSequenceDropDown
 5614: 
 5615:    Return html dropdown of possible sequences to grade
 5616:  
 5617:  Arguments:
 5618:    $symb - $symb of the current resource
 5619:    $map_error - ref to scalar which will container error if
 5620:                 $navmap object is unavailable in &getSymbMap().
 5621: 
 5622: =cut
 5623: 
 5624: sub getSequenceDropDown {
 5625:     my ($symb,$map_error)=@_;
 5626:     my $result='<select name="selectpage">'."\n";
 5627:     my ($titles,$symbx) = &getSymbMap($map_error);
 5628:     if (ref($map_error)) {
 5629:         return if ($$map_error);
 5630:     }
 5631:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5632:     my $ctr=0;
 5633:     foreach (@$titles) {
 5634: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5635: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5636: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5637: 	    '>'.$showtitle.'</option>'."\n";
 5638: 	$ctr++;
 5639:     }
 5640:     $result.= '</select>';
 5641:     return $result;
 5642: }
 5643: 
 5644: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5645:                                    # key is zero-based index - 0, 1, 2 ...
 5646: 
 5647: my %first_bubble_line;             # First bubble line no. for each bubble.
 5648: 
 5649: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5650:                                    # matchresponse or rankresponse, where 
 5651:                                    # an individual response can have multiple 
 5652:                                    # lines
 5653: 
 5654: my %responsetype_per_response;     # responsetype for each response
 5655: 
 5656: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5657:                                    # numbered response. Needed when randomorder
 5658:                                    # or randompick are in use. Key is ID, value 
 5659:                                    # is response number.
 5660: 
 5661: # Save and restore the bubble lines array to the form env.
 5662: 
 5663: 
 5664: sub save_bubble_lines {
 5665:     foreach my $line (keys(%bubble_lines_per_response)) {
 5666: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5667: 	$env{"form.scantron.first_bubble_line.$line"} =
 5668: 	    $first_bubble_line{$line};
 5669:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5670:             $subdivided_bubble_lines{$line};
 5671:         $env{"form.scantron.responsetype.$line"} =
 5672:             $responsetype_per_response{$line};
 5673:     }
 5674:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5675:         my $line = $masterseq_id_responsenum{$resid};
 5676:         $env{"form.scantron.residpart.$line"} = $resid;
 5677:     }
 5678: }
 5679: 
 5680: 
 5681: sub restore_bubble_lines {
 5682:     my $line = 0;
 5683:     %bubble_lines_per_response = ();
 5684:     %masterseq_id_responsenum = ();
 5685:     while ($env{"form.scantron.bubblelines.$line"}) {
 5686: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5687: 	$bubble_lines_per_response{$line} = $value;
 5688: 	$first_bubble_line{$line}  =
 5689: 	    $env{"form.scantron.first_bubble_line.$line"};
 5690:         $subdivided_bubble_lines{$line} =
 5691:             $env{"form.scantron.sub_bubblelines.$line"};
 5692:         $responsetype_per_response{$line} =
 5693:             $env{"form.scantron.responsetype.$line"};
 5694:         my $id = $env{"form.scantron.residpart.$line"};
 5695:         $masterseq_id_responsenum{$id} = $line;
 5696: 	$line++;
 5697:     }
 5698: }
 5699: 
 5700: =pod 
 5701: 
 5702: =item scantron_filenames
 5703: 
 5704:    Returns a list of the scantron files in the current course 
 5705: 
 5706: =cut
 5707: 
 5708: sub scantron_filenames {
 5709:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5710:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5711:     my $getpropath = 1;
 5712:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5713:                                                         $cname,$getpropath);
 5714:     my @possiblenames;
 5715:     if (ref($dirlist) eq 'ARRAY') {
 5716:         foreach my $filename (sort(@{$dirlist})) {
 5717: 	    ($filename)=split(/&/,$filename);
 5718: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5719: 	    $filename=~s/^scantron_orig_//;
 5720: 	    push(@possiblenames,$filename);
 5721:         }
 5722:     }
 5723:     return @possiblenames;
 5724: }
 5725: 
 5726: =pod 
 5727: 
 5728: =item scantron_uploads
 5729: 
 5730:    Returns  html drop-down list of scantron files in current course.
 5731: 
 5732:  Arguments:
 5733:    $file2grade - filename to set as selected in the dropdown
 5734: 
 5735: =cut
 5736: 
 5737: sub scantron_uploads {
 5738:     my ($file2grade) = @_;
 5739:     my $result=	'<select name="scantron_selectfile">';
 5740:     $result.="<option></option>";
 5741:     foreach my $filename (sort(&scantron_filenames())) {
 5742: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5743:     }
 5744:     $result.="</select>";
 5745:     return $result;
 5746: }
 5747: 
 5748: =pod 
 5749: 
 5750: =item scantron_scantab
 5751: 
 5752:   Returns html drop down of the scantron formats in the scantronformat.tab
 5753:   file.
 5754: 
 5755: =cut
 5756: 
 5757: sub scantron_scantab {
 5758:     my $result='<select name="scantron_format">'."\n";
 5759:     $result.='<option></option>'."\n";
 5760:     my @lines = &get_scantronformat_file();
 5761:     if (@lines > 0) {
 5762:         foreach my $line (@lines) {
 5763:             next if (($line =~ /^\#/) || ($line eq ''));
 5764: 	    my ($name,$descrip)=split(/:/,$line);
 5765: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5766:         }
 5767:     }
 5768:     $result.='</select>'."\n";
 5769:     return $result;
 5770: }
 5771: 
 5772: =pod
 5773: 
 5774: =item get_scantronformat_file
 5775: 
 5776:   Returns an array containing lines from the scantron format file for
 5777:   the domain of the course.
 5778: 
 5779:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5780:   lines are from this file.
 5781: 
 5782:   Otherwise, if a default.tab has been published in RES space by the 
 5783:   domainconfig user, lines are from this file.
 5784: 
 5785:   Otherwise, fall back to getting lines from the legacy file on the
 5786:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5787: 
 5788: =cut
 5789: 
 5790: sub get_scantronformat_file {
 5791:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5792:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5793:     my $gottab = 0;
 5794:     my @lines;
 5795:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5796:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5797:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5798:             if ($formatfile ne '-1') {
 5799:                 @lines = split("\n",$formatfile,-1);
 5800:                 $gottab = 1;
 5801:             }
 5802:         }
 5803:     }
 5804:     if (!$gottab) {
 5805:         my $confname = $cdom.'-domainconfig';
 5806:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5807:         my $formatfile =  &Apache::lonnet::getfile($default);
 5808:         if ($formatfile ne '-1') {
 5809:             @lines = split("\n",$formatfile,-1);
 5810:             $gottab = 1;
 5811:         }
 5812:     }
 5813:     if (!$gottab) {
 5814:         my @domains = &Apache::lonnet::current_machine_domains();
 5815:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5816:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5817:             @lines = <$fh>;
 5818:             close($fh);
 5819:         } else {
 5820:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5821:             @lines = <$fh>;
 5822:             close($fh);
 5823:         }
 5824:     }
 5825:     return @lines;
 5826: }
 5827: 
 5828: =pod 
 5829: 
 5830: =item scantron_CODElist
 5831: 
 5832:   Returns html drop down of the saved CODE lists from current course,
 5833:   generated from earlier printings.
 5834: 
 5835: =cut
 5836: 
 5837: sub scantron_CODElist {
 5838:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5839:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5840:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5841:     my $namechoice='<option></option>';
 5842:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5843: 	if ($name =~ /^error: 2 /) { next; }
 5844: 	if ($name =~ /^type\0/) { next; }
 5845: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5846:     }
 5847:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5848:     return $namechoice;
 5849: }
 5850: 
 5851: =pod 
 5852: 
 5853: =item scantron_CODEunique
 5854: 
 5855:   Returns the html for "Each CODE to be used once" radio.
 5856: 
 5857: =cut
 5858: 
 5859: sub scantron_CODEunique {
 5860:     my $result='<span class="LC_nobreak">
 5861:                  <label><input type="radio" name="scantron_CODEunique"
 5862:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5863:                 </span>
 5864:                 <span class="LC_nobreak">
 5865:                  <label><input type="radio" name="scantron_CODEunique"
 5866:                         value="no" />'.&mt('No').' </label>
 5867:                 </span>';
 5868:     return $result;
 5869: }
 5870: 
 5871: =pod 
 5872: 
 5873: =item scantron_selectphase
 5874: 
 5875:   Generates the initial screen to start the bubblesheet process.
 5876:   Allows for - starting a grading run.
 5877:              - downloading existing scan data (original, corrected
 5878:                                                 or skipped info)
 5879: 
 5880:              - uploading new scan data
 5881: 
 5882:  Arguments:
 5883:   $r          - The Apache request object
 5884:   $file2grade - name of the file that contain the scanned data to score
 5885: 
 5886: =cut
 5887: 
 5888: sub scantron_selectphase {
 5889:     my ($r,$file2grade) = @_;
 5890:     my ($symb)=&get_symb($r);
 5891:     if (!$symb) {return '';}
 5892:     my $map_error;
 5893:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5894:     if ($map_error) {
 5895:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5896:         return;
 5897:     }
 5898:     my $default_form_data=&defaultFormData($symb);
 5899:     my $grading_menu_button=&show_grading_menu_form($symb);
 5900:     my $file_selector=&scantron_uploads($file2grade);
 5901:     my $format_selector=&scantron_scantab();
 5902:     my $CODE_selector=&scantron_CODElist();
 5903:     my $CODE_unique=&scantron_CODEunique();
 5904:     my $result;
 5905: 
 5906:     $ssi_error = 0;
 5907: 
 5908:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5909:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5910: 
 5911:         # Chunk of form to prompt for a scantron file upload.
 5912: 
 5913:         $r->print('
 5914:     <br />
 5915:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5916:        '.&Apache::loncommon::start_data_table_header_row().'
 5917:             <th>
 5918:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5919:             </th>
 5920:        '.&Apache::loncommon::end_data_table_header_row().'
 5921:        '.&Apache::loncommon::start_data_table_row().'
 5922:             <td>
 5923: ');
 5924:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5925:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5926:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5927:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5928:     &js_escape(\$alertmsg);
 5929:     $r->print('
 5930:               <script type="text/javascript" language="javascript">
 5931:     function checkUpload(formname) {
 5932:         if (formname.upfile.value == "") {
 5933:             alert("'.$alertmsg.'");
 5934:             return false;
 5935:         }
 5936:         formname.submit();
 5937:     }
 5938:               </script>
 5939: 
 5940:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5941:                 '.$default_form_data.'
 5942:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5943:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5944:                 <input name="command" value="scantronupload_save" type="hidden" />
 5945:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5946:                 <br />
 5947:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5948:               </form>
 5949: ');
 5950: 
 5951:         $r->print('
 5952:             </td>
 5953:        '.&Apache::loncommon::end_data_table_row().'
 5954:        '.&Apache::loncommon::end_data_table().'
 5955: ');
 5956:     }
 5957: 
 5958:     # Chunk of form to prompt for a file to grade and how:
 5959: 
 5960:     $result.= '
 5961:     <br />
 5962:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5963:     <input type="hidden" name="command" value="scantron_warning" />
 5964:     '.$default_form_data.'
 5965:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5966:        '.&Apache::loncommon::start_data_table_header_row().'
 5967:             <th colspan="2">
 5968:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5969:             </th>
 5970:        '.&Apache::loncommon::end_data_table_header_row().'
 5971:        '.&Apache::loncommon::start_data_table_row().'
 5972:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5973:        '.&Apache::loncommon::end_data_table_row().'
 5974:        '.&Apache::loncommon::start_data_table_row().'
 5975:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5976:        '.&Apache::loncommon::end_data_table_row().'
 5977:        '.&Apache::loncommon::start_data_table_row().'
 5978:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5979:        '.&Apache::loncommon::end_data_table_row().'
 5980:        '.&Apache::loncommon::start_data_table_row().'
 5981:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5982:        '.&Apache::loncommon::end_data_table_row().'
 5983:        '.&Apache::loncommon::start_data_table_row().'
 5984:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5985:        '.&Apache::loncommon::end_data_table_row().'
 5986:        '.&Apache::loncommon::start_data_table_row().'
 5987: 	    <td> '.&mt('Options:').' </td>
 5988:             <td>
 5989: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5990:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5991:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5992: 	    </td>
 5993:        '.&Apache::loncommon::end_data_table_row().'
 5994:        '.&Apache::loncommon::start_data_table_row().'
 5995:             <td colspan="2">
 5996:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5997:             </td>
 5998:        '.&Apache::loncommon::end_data_table_row().'
 5999:     '.&Apache::loncommon::end_data_table().'
 6000:     </form>
 6001: ';
 6002:    
 6003:     $r->print($result);
 6004: 
 6005:     # Chunk of the form that prompts to view a scoring office file,
 6006:     # corrected file, skipped records in a file.
 6007: 
 6008:     $r->print('
 6009:    <br />
 6010:    <form action="/adm/grades" name="scantron_download">
 6011:      '.$default_form_data.'
 6012:      <input type="hidden" name="command" value="scantron_download" />
 6013:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6014:        '.&Apache::loncommon::start_data_table_header_row().'
 6015:               <th>
 6016:                 &nbsp;'.&mt('Download a scoring office file').'
 6017:               </th>
 6018:        '.&Apache::loncommon::end_data_table_header_row().'
 6019:        '.&Apache::loncommon::start_data_table_row().'
 6020:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6021:                 <br />
 6022:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6023:        '.&Apache::loncommon::end_data_table_row().'
 6024:      '.&Apache::loncommon::end_data_table().'
 6025:    </form>
 6026:    <br />
 6027: ');
 6028: 
 6029:     &Apache::lonpickcode::code_list($r,2);
 6030: 
 6031:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6032:              $default_form_data."\n".
 6033:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6034:              &Apache::loncommon::start_data_table_header_row()."\n".
 6035:              '<th colspan="2">
 6036:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6037:              '</th>'."\n".
 6038:               &Apache::loncommon::end_data_table_header_row()."\n".
 6039:               &Apache::loncommon::start_data_table_row()."\n".
 6040:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6041:               '<td> '.$sequence_selector.' </td>'.
 6042:               &Apache::loncommon::end_data_table_row()."\n".
 6043:               &Apache::loncommon::start_data_table_row()."\n".
 6044:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6045:               '<td> '.$file_selector.' </td>'."\n".
 6046:               &Apache::loncommon::end_data_table_row()."\n".
 6047:               &Apache::loncommon::start_data_table_row()."\n".
 6048:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6049:               '<td> '.$format_selector.' </td>'."\n".
 6050:               &Apache::loncommon::end_data_table_row()."\n".
 6051:               &Apache::loncommon::start_data_table_row()."\n".
 6052:               '<td> '.&mt('Options').' </td>'."\n".
 6053:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6054:               &Apache::loncommon::end_data_table_row()."\n".
 6055:               &Apache::loncommon::start_data_table_row()."\n".
 6056:               '<td colspan="2">'."\n".
 6057:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6058:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6059:               '</td>'."\n".
 6060:               &Apache::loncommon::end_data_table_row()."\n".
 6061:               &Apache::loncommon::end_data_table()."\n".
 6062:               '</form><br />');
 6063:     $r->print($grading_menu_button);
 6064:     return;
 6065: }
 6066: 
 6067: =pod
 6068: 
 6069: =item get_scantron_config
 6070: 
 6071:    Parse and return the scantron configuration line selected as a
 6072:    hash of configuration file fields.
 6073: 
 6074:  Arguments:
 6075:     which - the name of the configuration to parse from the file.
 6076: 
 6077: 
 6078:  Returns:
 6079:             If the named configuration is not in the file, an empty
 6080:             hash is returned.
 6081:     a hash with the fields
 6082:       name         - internal name for the this configuration setup
 6083:       description  - text to display to operator that describes this config
 6084:       CODElocation - if 0 or the string 'none'
 6085:                           - no CODE exists for this config
 6086:                      if -1 || the string 'letter'
 6087:                           - a CODE exists for this config and is
 6088:                             a string of letters
 6089:                      Unsupported value (but planned for future support)
 6090:                           if a positive integer
 6091:                                - The CODE exists as the first n items from
 6092:                                  the question section of the form
 6093:                           if the string 'number'
 6094:                                - The CODE exists for this config and is
 6095:                                  a string of numbers
 6096:       CODEstart   - (only matter if a CODE exists) column in the line where
 6097:                      the CODE starts
 6098:       CODElength  - length of the CODE
 6099:       IDstart     - column where the student/employee ID starts
 6100:       IDlength    - length of the student/employee ID info
 6101:       Qstart      - column where the information from the bubbled
 6102:                     'questions' start
 6103:       Qlength     - number of columns comprising a single bubble line from
 6104:                     the sheet. (usually either 1 or 10)
 6105:       Qon         - either a single character representing the character used
 6106:                     to signal a bubble was chosen in the positional setup, or
 6107:                     the string 'letter' if the letter of the chosen bubble is
 6108:                     in the final, or 'number' if a number representing the
 6109:                     chosen bubble is in the file (1->A 0->J)
 6110:       Qoff        - the character used to represent that a bubble was
 6111:                     left blank
 6112:       PaperID     - if the scanning process generates a unique number for each
 6113:                     sheet scanned the column that this ID number starts in
 6114:       PaperIDlength - number of columns that comprise the unique ID number
 6115:                       for the sheet of paper
 6116:       FirstName   - column that the first name starts in
 6117:       FirstNameLength - number of columns that the first name spans
 6118:  
 6119:       LastName    - column that the last name starts in
 6120:       LastNameLength - number of columns that the last name spans
 6121:       BubblesPerRow - number of bubbles available in each row used to
 6122:                       bubble an answer. (If not specified, 10 assumed).
 6123: 
 6124: =cut
 6125: 
 6126: sub get_scantron_config {
 6127:     my ($which) = @_;
 6128:     my @lines = &get_scantronformat_file();
 6129:     my %config;
 6130:     #FIXME probably should move to XML it has already gotten a bit much now
 6131:     foreach my $line (@lines) {
 6132: 	my ($name,$descrip)=split(/:/,$line);
 6133: 	if ($name ne $which ) { next; }
 6134: 	chomp($line);
 6135: 	my @config=split(/:/,$line);
 6136: 	$config{'name'}=$config[0];
 6137: 	$config{'description'}=$config[1];
 6138: 	$config{'CODElocation'}=$config[2];
 6139: 	$config{'CODEstart'}=$config[3];
 6140: 	$config{'CODElength'}=$config[4];
 6141: 	$config{'IDstart'}=$config[5];
 6142: 	$config{'IDlength'}=$config[6];
 6143: 	$config{'Qstart'}=$config[7];
 6144:  	$config{'Qlength'}=$config[8];
 6145: 	$config{'Qoff'}=$config[9];
 6146: 	$config{'Qon'}=$config[10];
 6147: 	$config{'PaperID'}=$config[11];
 6148: 	$config{'PaperIDlength'}=$config[12];
 6149: 	$config{'FirstName'}=$config[13];
 6150: 	$config{'FirstNamelength'}=$config[14];
 6151: 	$config{'LastName'}=$config[15];
 6152: 	$config{'LastNamelength'}=$config[16];
 6153:         $config{'BubblesPerRow'}=$config[17];
 6154: 	last;
 6155:     }
 6156:     return %config;
 6157: }
 6158: 
 6159: =pod 
 6160: 
 6161: =item username_to_idmap
 6162: 
 6163:     creates a hash keyed by student/employee ID with values of the corresponding
 6164:     student username:domain.
 6165: 
 6166:   Arguments:
 6167: 
 6168:     $classlist - reference to the class list hash. This is a hash
 6169:                  keyed by student name:domain  whose elements are references
 6170:                  to arrays containing various chunks of information
 6171:                  about the student. (See loncoursedata for more info).
 6172: 
 6173:   Returns
 6174:     %idmap - the constructed hash
 6175: 
 6176: =cut
 6177: 
 6178: sub username_to_idmap {
 6179:     my ($classlist)= @_;
 6180:     my %idmap;
 6181:     foreach my $student (keys(%$classlist)) {
 6182:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6183:         unless ($id eq '') {
 6184:             if (!exists($idmap{$id})) {
 6185:                 $idmap{$id} = $student;
 6186:             } else {
 6187:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6188:                 if ($status eq 'Active') {
 6189:                     $idmap{$id} = $student;
 6190:                 }
 6191:             }
 6192:         }
 6193:     }
 6194:     return %idmap;
 6195: }
 6196: 
 6197: =pod
 6198: 
 6199: =item scantron_fixup_scanline
 6200: 
 6201:    Process a requested correction to a scanline.
 6202: 
 6203:   Arguments:
 6204:     $scantron_config   - hash from &get_scantron_config()
 6205:     $scan_data         - hash of correction information 
 6206:                           (see &scantron_getfile())
 6207:     $line              - existing scanline
 6208:     $whichline         - line number of the passed in scanline
 6209:     $field             - type of change to process 
 6210:                          (either 
 6211:                           'ID'     -> correct the student/employee ID
 6212:                           'CODE'   -> correct the CODE
 6213:                           'answer' -> fixup the submitted answers)
 6214:     
 6215:    $args               - hash of additional info,
 6216:                           - 'ID' 
 6217:                                'newid' -> studentID to use in replacement
 6218:                                           of existing one
 6219:                           - 'CODE' 
 6220:                                'CODE_ignore_dup' - set to true if duplicates
 6221:                                                    should be ignored.
 6222: 	                       'CODE' - is new code or 'use_unfound'
 6223:                                         if the existing unfound code should
 6224:                                         be used as is
 6225:                           - 'answer'
 6226:                                'response' - new answer or 'none' if blank
 6227:                                'question' - the bubble line to change
 6228:                                'questionnum' - the question identifier,
 6229:                                                may include subquestion. 
 6230: 
 6231:   Returns:
 6232:     $line - the modified scanline
 6233: 
 6234:   Side effects: 
 6235:     $scan_data - may be updated
 6236: 
 6237: =cut
 6238: 
 6239: 
 6240: sub scantron_fixup_scanline {
 6241:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6242:     if ($field eq 'ID') {
 6243: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6244: 	    return ($line,1,'New value too large');
 6245: 	}
 6246: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6247: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6248: 				     $args->{'newid'});
 6249: 	}
 6250: 	substr($line,$$scantron_config{'IDstart'}-1,
 6251: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6252: 	if ($args->{'newid'}=~/^\s*$/) {
 6253: 	    &scan_data($scan_data,"$whichline.user",
 6254: 		       $args->{'username'}.':'.$args->{'domain'});
 6255: 	}
 6256:     } elsif ($field eq 'CODE') {
 6257: 	if ($args->{'CODE_ignore_dup'}) {
 6258: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6259: 	}
 6260: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6261: 	if ($args->{'CODE'} ne 'use_unfound') {
 6262: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6263: 		return ($line,1,'New CODE value too large');
 6264: 	    }
 6265: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6266: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6267: 	    }
 6268: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6269: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6270: 	}
 6271:     } elsif ($field eq 'answer') {
 6272: 	my $length=$scantron_config->{'Qlength'};
 6273: 	my $off=$scantron_config->{'Qoff'};
 6274: 	my $on=$scantron_config->{'Qon'};
 6275: 	my $answer=${off}x$length;
 6276: 	if ($args->{'response'} eq 'none') {
 6277: 	    &scan_data($scan_data,
 6278: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6279: 	} else {
 6280: 	    if ($on eq 'letter') {
 6281: 		my @alphabet=('A'..'Z');
 6282: 		$answer=$alphabet[$args->{'response'}];
 6283: 	    } elsif ($on eq 'number') {
 6284: 		$answer=$args->{'response'}+1;
 6285: 		if ($answer == 10) { $answer = '0'; }
 6286: 	    } else {
 6287: 		substr($answer,$args->{'response'},1)=$on;
 6288: 	    }
 6289: 	    &scan_data($scan_data,
 6290: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6291: 	}
 6292: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6293: 	substr($line,$where-1,$length)=$answer;
 6294:     }
 6295:     return $line;
 6296: }
 6297: 
 6298: =pod
 6299: 
 6300: =item scan_data
 6301: 
 6302:     Edit or look up  an item in the scan_data hash.
 6303: 
 6304:   Arguments:
 6305:     $scan_data  - The hash (see scantron_getfile)
 6306:     $key        - shorthand of the key to edit (actual key is
 6307:                   scantronfilename_key).
 6308:     $data        - New value of the hash entry.
 6309:     $delete      - If true, the entry is removed from the hash.
 6310: 
 6311:   Returns:
 6312:     The new value of the hash table field (undefined if deleted).
 6313: 
 6314: =cut
 6315: 
 6316: 
 6317: sub scan_data {
 6318:     my ($scan_data,$key,$value,$delete)=@_;
 6319:     my $filename=$env{'form.scantron_selectfile'};
 6320:     if (defined($value)) {
 6321: 	$scan_data->{$filename.'_'.$key} = $value;
 6322:     }
 6323:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6324:     return $scan_data->{$filename.'_'.$key};
 6325: }
 6326: 
 6327: # ----- These first few routines are general use routines.----
 6328: 
 6329: # Return the number of occurences of a pattern in a string.
 6330: 
 6331: sub occurence_count {
 6332:     my ($string, $pattern) = @_;
 6333: 
 6334:     my @matches = ($string =~ /$pattern/g);
 6335: 
 6336:     return scalar(@matches);
 6337: }
 6338: 
 6339: 
 6340: # Take a string known to have digits and convert all the
 6341: # digits into letters in the range J,A..I.
 6342: 
 6343: sub digits_to_letters {
 6344:     my ($input) = @_;
 6345: 
 6346:     my @alphabet = ('J', 'A'..'I');
 6347: 
 6348:     my @input    = split(//, $input);
 6349:     my $output ='';
 6350:     for (my $i = 0; $i < scalar(@input); $i++) {
 6351: 	if ($input[$i] =~ /\d/) {
 6352: 	    $output .= $alphabet[$input[$i]];
 6353: 	} else {
 6354: 	    $output .= $input[$i];
 6355: 	}
 6356:     }
 6357:     return $output;
 6358: }
 6359: 
 6360: =pod 
 6361: 
 6362: =item scantron_parse_scanline
 6363: 
 6364:   Decodes a scanline from the selected scantron file
 6365: 
 6366:  Arguments:
 6367:     line             - The text of the scantron file line to process
 6368:     whichline        - Line number
 6369:     scantron_config  - Hash describing the format of the scantron lines.
 6370:     scan_data        - Hash of extra information about the scanline
 6371:                        (see scantron_getfile for more information)
 6372:     just_header      - True if should not process question answers but only
 6373:                        the stuff to the left of the answers.
 6374:     randomorder      - True if randomorder in use
 6375:     randompick       - True if randompick in use
 6376:     sequence         - Exam folder URL
 6377:     master_seq       - Ref to array containing symbs in exam folder
 6378:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6379:                        (corresponding values are resource objects)
 6380:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6381:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6382:                        are refs to an array of resource objects, ordered
 6383:                        according to order used for CODE, when randomorder
 6384:                        and or randompick are in use.
 6385:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6386:                        for current line to question number used for same question
 6387:                         in "Master Sequence" (as seen by Course Coordinator).
 6388:     startline        - Ref to hash where key is question number (0 is first)
 6389:                        and value is number of first bubble line for current 
 6390:                        student or code-based randompick and/or randomorder.
 6391:     totalref         - Ref of scalar used to score total number of bubble
 6392:                        lines needed for responses in a scan line (used when
 6393:                        randompick in use. 
 6394: 
 6395:  Returns:
 6396:    Hash containing the result of parsing the scanline
 6397: 
 6398:    Keys are all proceeded by the string 'scantron.'
 6399: 
 6400:        CODE    - the CODE in use for this scanline
 6401:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6402:                  by the operator
 6403:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6404:                             CODEs were selected, but the usage has been
 6405:                             forced by the operator
 6406:        ID  - student/employee ID
 6407:        PaperID - if used, the ID number printed on the sheet when the 
 6408:                  paper was scanned
 6409:        FirstName - first name from the sheet
 6410:        LastName  - last name from the sheet
 6411: 
 6412:      if just_header was not true these key may also exist
 6413: 
 6414:        missingerror - a list of bubble ranges that are considered to be answers
 6415:                       to a single question that don't have any bubbles filled in.
 6416:                       Of the form questionnumber:firstbubblenumber:count.
 6417:        doubleerror  - a list of bubble ranges that are considered to be answers
 6418:                       to a single question that have more than one bubble filled in.
 6419:                       Of the form questionnumber::firstbubblenumber:count
 6420:    
 6421:                 In the above, count is the number of bubble responses in the
 6422:                 input line needed to represent the possible answers to the question.
 6423:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6424:                 per line would have count = 2.
 6425: 
 6426:        maxquest     - the number of the last bubble line that was parsed
 6427: 
 6428:        (<number> starts at 1)
 6429:        <number>.answer - zero or more letters representing the selected
 6430:                          letters from the scanline for the bubble line 
 6431:                          <number>.
 6432:                          if blank there was either no bubble or there where
 6433:                          multiple bubbles, (consult the keys missingerror and
 6434:                          doubleerror if this is an error condition)
 6435: 
 6436: =cut
 6437: 
 6438: sub scantron_parse_scanline {
 6439:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6440:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6441:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6442: 
 6443:     my %record;
 6444:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6445:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6446: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6447: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6448: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6449: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6450: 	    $record{'scantron.CODE'}=substr($data,
 6451: 					    $$scantron_config{'CODEstart'}-1,
 6452: 					    $$scantron_config{'CODElength'});
 6453: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6454: 		$record{'scantron.useCODE'}=1;
 6455: 	    }
 6456: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6457: 		$record{'scantron.CODE_ignore_dup'}=1;
 6458: 	    }
 6459: 	} else {
 6460: 	    #FIXME interpret first N questions
 6461: 	}
 6462:     }
 6463:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6464: 				  $$scantron_config{'IDlength'});
 6465:     $record{'scantron.PaperID'}=
 6466: 	substr($data,$$scantron_config{'PaperID'}-1,
 6467: 	       $$scantron_config{'PaperIDlength'});
 6468:     $record{'scantron.FirstName'}=
 6469: 	substr($data,$$scantron_config{'FirstName'}-1,
 6470: 	       $$scantron_config{'FirstNamelength'});
 6471:     $record{'scantron.LastName'}=
 6472: 	substr($data,$$scantron_config{'LastName'}-1,
 6473: 	       $$scantron_config{'LastNamelength'});
 6474:     if ($just_header) { return \%record; }
 6475: 
 6476:     my @alphabet=('A'..'Z');
 6477:     my $questnum=0;
 6478:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6479: 
 6480:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6481:     if ($randompick || $randomorder) {
 6482:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6483:                                          $master_seq,$symb_to_resource,
 6484:                                          $partids_by_symb,$orderedforcode,
 6485:                                          $respnumlookup,$startline);
 6486:         if ($total) {
 6487:             $lastpos = $total*$$scantron_config{'Qlength'};
 6488:         }
 6489:         if (ref($totalref)) {
 6490:             $$totalref = $total;
 6491:         }
 6492:     }
 6493:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6494:     chomp($questions);		# Get rid of any trailing \n.
 6495:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6496:     while (length($questions)) {
 6497:         my $answers_needed;
 6498:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6499:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6500:         } else {
 6501:             $answers_needed = $bubble_lines_per_response{$questnum};
 6502:         }
 6503:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6504:                              || 1;
 6505:         $questnum++;
 6506:         my $quest_id = $questnum;
 6507:         my $currentquest = substr($questions,0,$answer_length);
 6508:         $questions       = substr($questions,$answer_length);
 6509:         if (length($currentquest) < $answer_length) { next; }
 6510: 
 6511:         my $subdivided;
 6512:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6513:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6514:         } else {
 6515:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6516:         }
 6517:         if ($subdivided =~ /,/) {
 6518:             my $subquestnum = 1;
 6519:             my $subquestions = $currentquest;
 6520:             my @subanswers_needed = split(/,/,$subdivided);
 6521:             foreach my $subans (@subanswers_needed) {
 6522:                 my $subans_length =
 6523:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6524:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6525:                 $subquestions   = substr($subquestions,$subans_length);
 6526:                 $quest_id = "$questnum.$subquestnum";
 6527:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6528:                     ($$scantron_config{'Qon'} eq 'number')) {
 6529:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6530:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6531:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6532:                         $randomorder,$randompick,$respnumlookup);
 6533:                 } else {
 6534:                     $ansnum = &scantron_validator_positional($ansnum,
 6535:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6536:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6537:                         $randomorder,$randompick,$respnumlookup);
 6538:                 }
 6539:                 $subquestnum ++;
 6540:             }
 6541:         } else {
 6542:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6543:                 ($$scantron_config{'Qon'} eq 'number')) {
 6544:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6545:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6546:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6547:                     $randomorder,$randompick,$respnumlookup);
 6548:             } else {
 6549:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6550:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6551:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6552:                     $randomorder,$randompick,$respnumlookup);
 6553:             }
 6554:         }
 6555:     }
 6556:     $record{'scantron.maxquest'}=$questnum;
 6557:     return \%record;
 6558: }
 6559: 
 6560: sub get_master_seq {
 6561:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6562:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6563:                    (ref($symb_to_resource) eq 'HASH'));
 6564:     my $resource_error;
 6565:     foreach my $resource (@{$resources}) {
 6566:         my $ressymb;
 6567:         if (ref($resource)) {
 6568:             $ressymb = $resource->symb();
 6569:             push(@{$master_seq},$ressymb);
 6570:             $symb_to_resource->{$ressymb} = $resource;
 6571:         } else {
 6572:             $resource_error = 1;
 6573:             last;
 6574:         }
 6575:     }
 6576:     return $resource_error;
 6577: }
 6578: 
 6579: sub get_respnum_lookups {
 6580:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6581:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6582:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6583:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6584:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6585:                    (ref($startline) eq 'HASH'));
 6586:     my ($user,$scancode);
 6587:     if ((exists($record->{'scantron.CODE'})) &&
 6588:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6589:         $scancode = $record->{'scantron.CODE'};
 6590:     } else {
 6591:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6592:     }
 6593:     my @mapresources =
 6594:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6595:                      $orderedforcode);
 6596:     my $total = 0;
 6597:     my $count = 0;
 6598:     foreach my $resource (@mapresources) {
 6599:         my $id = $resource->id();
 6600:         my $symb = $resource->symb();
 6601:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6602:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6603:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6604:                 if ($respnum ne '') {
 6605:                     $respnumlookup->{$count} = $respnum;
 6606:                     $startline->{$count} = $total;
 6607:                     $total += $bubble_lines_per_response{$respnum};
 6608:                     $count ++;
 6609:                 }
 6610:             }
 6611:         }
 6612:     }
 6613:     return $total;
 6614: }
 6615: 
 6616: sub scantron_validator_lettnum {
 6617:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6618:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6619:         $randompick,$respnumlookup) = @_;
 6620: 
 6621:     # Qon 'letter' implies for each slot in currquest we have:
 6622:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6623:     #    about anything else (esp. a value of Qoff) for missing
 6624:     #    bubbles.
 6625:     #
 6626:     # Qon 'number' implies each slot gives a digit that indexes the
 6627:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6628:     #    and * or ? for double bubbles on a single line.
 6629:     #
 6630: 
 6631:     my $matchon;
 6632:     if ($$scantron_config{'Qon'} eq 'letter') {
 6633:         $matchon = '[A-Z]';
 6634:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6635:         $matchon = '\d';
 6636:     }
 6637:     my $occurrences = 0;
 6638:     my $responsenum = $questnum-1;
 6639:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6640:        $responsenum = $respnumlookup->{$questnum-1}
 6641:     }
 6642:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6643:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6644:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6645:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6646:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6647:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6648:         my @singlelines = split('',$currquest);
 6649:         foreach my $entry (@singlelines) {
 6650:             $occurrences = &occurence_count($entry,$matchon);
 6651:             if ($occurrences > 1) {
 6652:                 last;
 6653:             }
 6654:         }
 6655:     } else {
 6656:         $occurrences = &occurence_count($currquest,$matchon); 
 6657:     }
 6658:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6659:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6660:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6661:             my $bubble = substr($currquest,$ans,1);
 6662:             if ($bubble =~ /$matchon/ ) {
 6663:                 if ($$scantron_config{'Qon'} eq 'number') {
 6664:                     if ($bubble == 0) {
 6665:                         $bubble = 10; 
 6666:                     }
 6667:                     $record->{"scantron.$ansnum.answer"} = 
 6668:                         $alphabet->[$bubble-1];
 6669:                 } else {
 6670:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6671:                 }
 6672:             } else {
 6673:                 $record->{"scantron.$ansnum.answer"}='';
 6674:             }
 6675:             $ansnum++;
 6676:         }
 6677:     } elsif (!defined($currquest)
 6678:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6679:             || (&occurence_count($currquest,$matchon) == 0)) {
 6680:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6681:             $record->{"scantron.$ansnum.answer"}='';
 6682:             $ansnum++;
 6683:         }
 6684:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6685:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6686:         }
 6687:     } else {
 6688:         if ($$scantron_config{'Qon'} eq 'number') {
 6689:             $currquest = &digits_to_letters($currquest);            
 6690:         }
 6691:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6692:             my $bubble = substr($currquest,$ans,1);
 6693:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6694:             $ansnum++;
 6695:         }
 6696:     }
 6697:     return $ansnum;
 6698: }
 6699: 
 6700: sub scantron_validator_positional {
 6701:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6702:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6703:         $randomorder,$randompick,$respnumlookup) = @_;
 6704: 
 6705:     # Otherwise there's a positional notation;
 6706:     # each bubble line requires Qlength items, and there are filled in
 6707:     # bubbles for each case where there 'Qon' characters.
 6708:     #
 6709: 
 6710:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6711: 
 6712:     # If the split only gives us one element.. the full length of the
 6713:     # answer string, no bubbles are filled in:
 6714: 
 6715:     if ($answers_needed eq '') {
 6716:         return;
 6717:     }
 6718: 
 6719:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6720:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6721:             $record->{"scantron.$ansnum.answer"}='';
 6722:             $ansnum++;
 6723:         }
 6724:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6725:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6726:         }
 6727:     } elsif (scalar(@array) == 2) {
 6728:         my $location = length($array[0]);
 6729:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6730:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6731:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6732:             if ($ans eq $line_num) {
 6733:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6734:             } else {
 6735:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6736:             }
 6737:             $ansnum++;
 6738:          }
 6739:     } else {
 6740:         #  If there's more than one instance of a bubble character
 6741:         #  That's a double bubble; with positional notation we can
 6742:         #  record all the bubbles filled in as well as the
 6743:         #  fact this response consists of multiple bubbles.
 6744:         #
 6745:         my $responsenum = $questnum-1;
 6746:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6747:             $responsenum = $respnumlookup->{$questnum-1}
 6748:         }
 6749:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6750:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6751:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6752:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6753:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6754:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6755:             my $doubleerror = 0;
 6756:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6757:                    (!$doubleerror)) {
 6758:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6759:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6760:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6761:                if (length(@currarray) > 2) {
 6762:                    $doubleerror = 1;
 6763:                } 
 6764:             }
 6765:             if ($doubleerror) {
 6766:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6767:             }
 6768:         } else {
 6769:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6770:         }
 6771:         my $item = $ansnum;
 6772:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6773:             $record->{"scantron.$item.answer"} = '';
 6774:             $item ++;
 6775:         }
 6776: 
 6777:         my @ans=@array;
 6778:         my $i=0;
 6779:         my $increment = 0;
 6780:         while ($#ans) {
 6781:             $i+=length($ans[0]) + $increment;
 6782:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6783:             my $bubble = $i%$$scantron_config{'Qlength'};
 6784:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6785:             shift(@ans);
 6786:             $increment = 1;
 6787:         }
 6788:         $ansnum += $answers_needed;
 6789:     }
 6790:     return $ansnum;
 6791: }
 6792: 
 6793: =pod
 6794: 
 6795: =item scantron_add_delay
 6796: 
 6797:    Adds an error message that occurred during the grading phase to a
 6798:    queue of messages to be shown after grading pass is complete
 6799: 
 6800:  Arguments:
 6801:    $delayqueue  - arrary ref of hash ref of error messages
 6802:    $scanline    - the scanline that caused the error
 6803:    $errormesage - the error message
 6804:    $errorcode   - a numeric code for the error
 6805: 
 6806:  Side Effects:
 6807:    updates the $delayqueue to have a new hash ref of the error
 6808: 
 6809: =cut
 6810: 
 6811: sub scantron_add_delay {
 6812:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6813:     push(@$delayqueue,
 6814: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6815: 	  'ecode' => $errorcode }
 6816: 	 );
 6817: }
 6818: 
 6819: =pod
 6820: 
 6821: =item scantron_find_student
 6822: 
 6823:    Finds the username for the current scanline
 6824: 
 6825:   Arguments:
 6826:    $scantron_record - hash result from scantron_parse_scanline
 6827:    $scan_data       - hash of correction information 
 6828:                       (see &scantron_getfile() form more information)
 6829:    $idmap           - hash from &username_to_idmap()
 6830:    $line            - number of current scanline
 6831:  
 6832:   Returns:
 6833:    Either 'username:domain' or undef if unknown
 6834: 
 6835: =cut
 6836: 
 6837: sub scantron_find_student {
 6838:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6839:     my $scanID=$$scantron_record{'scantron.ID'};
 6840:     if ($scanID =~ /^\s*$/) {
 6841:  	return &scan_data($scan_data,"$line.user");
 6842:     }
 6843:     foreach my $id (keys(%$idmap)) {
 6844:  	if (lc($id) eq lc($scanID)) {
 6845:  	    return $$idmap{$id};
 6846:  	}
 6847:     }
 6848:     return undef;
 6849: }
 6850: 
 6851: =pod
 6852: 
 6853: =item scantron_filter
 6854: 
 6855:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6856:    hidden resources was selected
 6857: 
 6858: =cut
 6859: 
 6860: sub scantron_filter {
 6861:     my ($curres)=@_;
 6862: 
 6863:     if (ref($curres) && $curres->is_problem()) {
 6864: 	# if the user has asked to not have either hidden
 6865: 	# or 'randomout' controlled resources to be graded
 6866: 	# don't include them
 6867: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6868: 	    && $curres->randomout) {
 6869: 	    return 0;
 6870: 	}
 6871: 	return 1;
 6872:     }
 6873:     return 0;
 6874: }
 6875: 
 6876: =pod
 6877: 
 6878: =item scantron_process_corrections
 6879: 
 6880:    Gets correction information out of submitted form data and corrects
 6881:    the scanline
 6882: 
 6883: =cut
 6884: 
 6885: sub scantron_process_corrections {
 6886:     my ($r) = @_;
 6887:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6888:     my ($scanlines,$scan_data)=&scantron_getfile();
 6889:     my $classlist=&Apache::loncoursedata::get_classlist();
 6890:     my $which=$env{'form.scantron_line'};
 6891:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6892:     my ($skip,$err,$errmsg);
 6893:     if ($env{'form.scantron_skip_record'}) {
 6894: 	$skip=1;
 6895:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6896: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6897: 	    $env{'form.scantron_domain'};
 6898: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6899: 	($line,$err,$errmsg)=
 6900: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6901: 				     'ID',{'newid'=>$newid,
 6902: 				    'username'=>$env{'form.scantron_username'},
 6903: 				    'domain'=>$env{'form.scantron_domain'}});
 6904:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6905: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6906: 	my $newCODE;
 6907: 	my %args;
 6908: 	if      ($resolution eq 'use_unfound') {
 6909: 	    $newCODE='use_unfound';
 6910: 	} elsif ($resolution eq 'use_found') {
 6911: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6912: 	} elsif ($resolution eq 'use_typed') {
 6913: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6914: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6915: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6916: 	}
 6917: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6918: 	    $args{'CODE_ignore_dup'}=1;
 6919: 	}
 6920: 	$args{'CODE'}=$newCODE;
 6921: 	($line,$err,$errmsg)=
 6922: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6923: 				     'CODE',\%args);
 6924:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6925: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6926: 	    ($line,$err,$errmsg)=
 6927: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6928: 					 $which,'answer',
 6929: 					 { 'question'=>$question,
 6930: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6931:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6932: 	    if ($err) { last; }
 6933: 	}
 6934:     }
 6935:     if ($err) {
 6936: 	$r->print(
 6937:             '<p class="LC_error">'
 6938:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6939:                 $errmsg)
 6940:            .'</p>');
 6941:     } else {
 6942: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6943: 	&scantron_putfile($scanlines,$scan_data);
 6944:     }
 6945: }
 6946: 
 6947: =pod
 6948: 
 6949: =item reset_skipping_status
 6950: 
 6951:    Forgets the current set of remember skipped scanlines (and thus
 6952:    reverts back to considering all lines in the
 6953:    scantron_skipped_<filename> file)
 6954: 
 6955: =cut
 6956: 
 6957: sub reset_skipping_status {
 6958:     my ($scanlines,$scan_data)=&scantron_getfile();
 6959:     &scan_data($scan_data,'remember_skipping',undef,1);
 6960:     &scantron_putfile(undef,$scan_data);
 6961: }
 6962: 
 6963: =pod
 6964: 
 6965: =item start_skipping
 6966: 
 6967:    Marks a scanline to be skipped. 
 6968: 
 6969: =cut
 6970: 
 6971: sub start_skipping {
 6972:     my ($scan_data,$i)=@_;
 6973:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6974:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6975: 	$remembered{$i}=2;
 6976:     } else {
 6977: 	$remembered{$i}=1;
 6978:     }
 6979:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6980: }
 6981: 
 6982: =pod
 6983: 
 6984: =item should_be_skipped
 6985: 
 6986:    Checks whether a scanline should be skipped.
 6987: 
 6988: =cut
 6989: 
 6990: sub should_be_skipped {
 6991:     my ($scanlines,$scan_data,$i)=@_;
 6992:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6993: 	# not redoing old skips
 6994: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6995: 	return 0;
 6996:     }
 6997:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6998: 
 6999:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7000: 	return 0;
 7001:     }
 7002:     return 1;
 7003: }
 7004: 
 7005: =pod
 7006: 
 7007: =item remember_current_skipped
 7008: 
 7009:    Discovers what scanlines are in the scantron_skipped_<filename>
 7010:    file and remembers them into scan_data for later use.
 7011: 
 7012: =cut
 7013: 
 7014: sub remember_current_skipped {
 7015:     my ($scanlines,$scan_data)=&scantron_getfile();
 7016:     my %to_remember;
 7017:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7018: 	if ($scanlines->{'skipped'}[$i]) {
 7019: 	    $to_remember{$i}=1;
 7020: 	}
 7021:     }
 7022: 
 7023:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7024:     &scantron_putfile(undef,$scan_data);
 7025: }
 7026: 
 7027: =pod
 7028: 
 7029: =item check_for_error
 7030: 
 7031:     Checks if there was an error when attempting to remove a specific
 7032:     scantron_.. bubblesheet data file. Prints out an error if
 7033:     something went wrong.
 7034: 
 7035: =cut
 7036: 
 7037: sub check_for_error {
 7038:     my ($r,$result)=@_;
 7039:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7040: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7041:     }
 7042: }
 7043: 
 7044: =pod
 7045: 
 7046: =item scantron_warning_screen
 7047: 
 7048:    Interstitial screen to make sure the operator has selected the
 7049:    correct options before we start the validation phase.
 7050: 
 7051: =cut
 7052: 
 7053: sub scantron_warning_screen {
 7054:     my ($button_text)=@_;
 7055:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7056:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7057:     my $CODElist;
 7058:     if ($scantron_config{'CODElocation'} &&
 7059: 	$scantron_config{'CODEstart'} &&
 7060: 	$scantron_config{'CODElength'}) {
 7061: 	$CODElist=$env{'form.scantron_CODElist'};
 7062: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7063: 	$CODElist=
 7064: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7065: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7066:     }
 7067:     my $lastbubblepoints;
 7068:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7069:         $lastbubblepoints =
 7070:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7071:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7072:     }
 7073:     return ('
 7074: <p>
 7075: <span class="LC_warning">
 7076: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7077: </p>
 7078: <table>
 7079: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7080: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7081: '.$CODElist.$lastbubblepoints.'
 7082: </table>
 7083: <br />
 7084: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 7085: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 7086: 
 7087: <br />
 7088: ');
 7089: }
 7090: 
 7091: =pod
 7092: 
 7093: =item scantron_do_warning
 7094: 
 7095:    Check if the operator has picked something for all required
 7096:    fields. Error out if something is missing.
 7097: 
 7098: =cut
 7099: 
 7100: sub scantron_do_warning {
 7101:     my ($r)=@_;
 7102:     my ($symb)=&get_symb($r);
 7103:     if (!$symb) {return '';}
 7104:     my $default_form_data=&defaultFormData($symb);
 7105:     $r->print(&scantron_form_start().$default_form_data);
 7106:     if ( $env{'form.selectpage'} eq '' ||
 7107: 	 $env{'form.scantron_selectfile'} eq '' ||
 7108: 	 $env{'form.scantron_format'} eq '' ) {
 7109: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7110: 	if ( $env{'form.selectpage'} eq '') {
 7111: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7112: 	} 
 7113: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7114: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7115: 	} 
 7116: 	if ( $env{'form.scantron_format'} eq '') {
 7117: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7118: 	} 
 7119:     } else {
 7120: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 7121:         my $bubbledbyhand=&hand_bubble_option();
 7122: 	$r->print('
 7123: '.$warning.$bubbledbyhand.'
 7124: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7125: <input type="hidden" name="command" value="scantron_validate" />
 7126: ');
 7127:     }
 7128:     $r->print("</form><br />".&show_grading_menu_form($symb));
 7129:     return '';
 7130: }
 7131: 
 7132: =pod
 7133: 
 7134: =item scantron_form_start
 7135: 
 7136:     html hidden input for remembering all selected grading options
 7137: 
 7138: =cut
 7139: 
 7140: sub scantron_form_start {
 7141:     my ($max_bubble)=@_;
 7142:     my $result= <<SCANTRONFORM;
 7143: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7144:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7145:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7146:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7147:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7148:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7149:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7150:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7151:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7152:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7153: SCANTRONFORM
 7154: 
 7155:   my $line = 0;
 7156:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7157:        my $chunk =
 7158: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7159:        $chunk .=
 7160: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7161:        $chunk .= 
 7162:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7163:        $chunk .=
 7164:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7165:        $chunk .=
 7166:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7167:        $result .= $chunk;
 7168:        $line++;
 7169:     }
 7170:     return $result;
 7171: }
 7172: 
 7173: =pod
 7174: 
 7175: =item scantron_validate_file
 7176: 
 7177:     Dispatch routine for doing validation of a bubblesheet data file.
 7178: 
 7179:     Also processes any necessary information resets that need to
 7180:     occur before validation begins (ignore previous corrections,
 7181:     restarting the skipped records processing)
 7182: 
 7183: =cut
 7184: 
 7185: sub scantron_validate_file {
 7186:     my ($r) = @_;
 7187:     my ($symb)=&get_symb($r);
 7188:     if (!$symb) {return '';}
 7189:     my $default_form_data=&defaultFormData($symb);
 7190:     
 7191:     # do the detection of only doing skipped records first before we delete
 7192:     # them when doing the corrections reset
 7193:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7194: 	&reset_skipping_status();
 7195:     }
 7196:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7197: 	&remember_current_skipped();
 7198: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7199:     }
 7200: 
 7201:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7202: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7203: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7204: 	&check_for_error($r,&scantron_remove_scan_data());
 7205: 	$env{'form.scantron_options_ignore'}='done';
 7206:     }
 7207: 
 7208:     if ($env{'form.scantron_corrections'}) {
 7209: 	&scantron_process_corrections($r);
 7210:     }
 7211:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7212:     #get the student pick code ready
 7213:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7214:     my $nav_error;
 7215:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7216:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7217:     if ($nav_error) {
 7218:         $r->print(&navmap_errormsg());
 7219:         return '';
 7220:     }
 7221:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7222:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7223:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7224:     }
 7225:     $r->print($result);
 7226:     
 7227:     my @validate_phases=( 'sequence',
 7228: 			  'ID',
 7229: 			  'CODE',
 7230: 			  'doublebubble',
 7231: 			  'missingbubbles');
 7232:     if (!$env{'form.validatepass'}) {
 7233: 	$env{'form.validatepass'} = 0;
 7234:     }
 7235:     my $currentphase=$env{'form.validatepass'};
 7236: 
 7237: 
 7238:     my $stop=0;
 7239:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7240: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7241: 	$r->rflush();
 7242: 
 7243: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7244: 	{
 7245: 	    no strict 'refs';
 7246: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7247: 	}
 7248:     }
 7249:     if (!$stop) {
 7250: 	my $warning=&scantron_warning_screen('Start Grading');
 7251: 	$r->print(&mt('Validation process complete.').'<br />'.
 7252:                   $warning.
 7253:                   &mt('Perform verification for each student after storage of submissions?').
 7254:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7255:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7256:                   ('&nbsp;'x3).'<label>'.
 7257:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7258:                   '</label></span><br />'.
 7259:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7260:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 7261:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7262:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7263:     } else {
 7264: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7265: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7266:     }
 7267:     if ($stop) {
 7268: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7269: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7270: 	    $r->print(' '.&mt('this error').' <br />');
 7271: 
 7272: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 7273: 	} else {
 7274:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7275: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7276:             } else {
 7277:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7278:             }
 7279: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7280: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7281: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7282: 	}
 7283:     }
 7284:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 7285:     return '';
 7286: }
 7287: 
 7288: 
 7289: =pod
 7290: 
 7291: =item scantron_remove_file
 7292: 
 7293:    Removes the requested bubblesheet data file, makes sure that
 7294:    scantron_original_<filename> is never removed
 7295: 
 7296: 
 7297: =cut
 7298: 
 7299: sub scantron_remove_file {
 7300:     my ($which)=@_;
 7301:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7302:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7303:     my $file='scantron_';
 7304:     if ($which eq 'corrected' || $which eq 'skipped') {
 7305: 	$file.=$which.'_';
 7306:     } else {
 7307: 	return 'refused';
 7308:     }
 7309:     $file.=$env{'form.scantron_selectfile'};
 7310:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7311: }
 7312: 
 7313: 
 7314: =pod
 7315: 
 7316: =item scantron_remove_scan_data
 7317: 
 7318:    Removes all scan_data correction for the requested bubblesheet
 7319:    data file.  (In the case that both the are doing skipped records we need
 7320:    to remember the old skipped lines for the time being so that element
 7321:    persists for a while.)
 7322: 
 7323: =cut
 7324: 
 7325: sub scantron_remove_scan_data {
 7326:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7327:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7328:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7329:     my @todelete;
 7330:     my $filename=$env{'form.scantron_selectfile'};
 7331:     foreach my $key (@keys) {
 7332: 	if ($key=~/^\Q$filename\E_/) {
 7333: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7334: 		$key=~/remember_skipping/) {
 7335: 		next;
 7336: 	    }
 7337: 	    push(@todelete,$key);
 7338: 	}
 7339:     }
 7340:     my $result;
 7341:     if (@todelete) {
 7342: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7343: 				       \@todelete,$cdom,$cname);
 7344:     } else {
 7345: 	$result = 'ok';
 7346:     }
 7347:     return $result;
 7348: }
 7349: 
 7350: 
 7351: =pod
 7352: 
 7353: =item scantron_getfile
 7354: 
 7355:     Fetches the requested bubblesheet data file (all 3 versions), and
 7356:     the scan_data hash
 7357:   
 7358:   Arguments:
 7359:     None
 7360: 
 7361:   Returns:
 7362:     2 hash references
 7363: 
 7364:      - first one has 
 7365:          orig      -
 7366:          corrected -
 7367:          skipped   -  each of which points to an array ref of the specified
 7368:                       file broken up into individual lines
 7369:          count     - number of scanlines
 7370:  
 7371:      - second is the scan_data hash possible keys are
 7372:        ($number refers to scanline numbered $number and thus the key affects
 7373:         only that scanline
 7374:         $bubline refers to the specific bubble line element and the aspects
 7375:         refers to that specific bubble line element)
 7376: 
 7377:        $number.user - username:domain to use
 7378:        $number.CODE_ignore_dup 
 7379:                     - ignore the duplicate CODE error 
 7380:        $number.useCODE
 7381:                     - use the CODE in the scanline as is
 7382:        $number.no_bubble.$bubline
 7383:                     - it is valid that there is no bubbled in bubble
 7384:                       at $number $bubline
 7385:        remember_skipping
 7386:                     - a frozen hash containing keys of $number and values
 7387:                       of either 
 7388:                         1 - we are on a 'do skipped records pass' and plan
 7389:                             on processing this line
 7390:                         2 - we are on a 'do skipped records pass' and this
 7391:                             scanline has been marked to skip yet again
 7392: 
 7393: =cut
 7394: 
 7395: sub scantron_getfile {
 7396:     #FIXME really would prefer a scantron directory
 7397:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7398:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7399:     my $lines;
 7400:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7401: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7402:     my %scanlines;
 7403:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7404:     my $temp=$scanlines{'orig'};
 7405:     $scanlines{'count'}=$#$temp;
 7406: 
 7407:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7408: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7409:     if ($lines eq '-1') {
 7410: 	$scanlines{'corrected'}=[];
 7411:     } else {
 7412: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7413:     }
 7414:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7415: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7416:     if ($lines eq '-1') {
 7417: 	$scanlines{'skipped'}=[];
 7418:     } else {
 7419: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7420:     }
 7421:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7422:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7423:     my %scan_data = @tmp;
 7424:     return (\%scanlines,\%scan_data);
 7425: }
 7426: 
 7427: =pod
 7428: 
 7429: =item lonnet_putfile
 7430: 
 7431:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7432: 
 7433:  Arguments:
 7434:    $contents - data to store
 7435:    $filename - filename to store $contents into
 7436: 
 7437:  Returns:
 7438:    result value from &Apache::lonnet::finishuserfileupload
 7439: 
 7440: =cut
 7441: 
 7442: sub lonnet_putfile {
 7443:     my ($contents,$filename)=@_;
 7444:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7445:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7446:     $env{'form.sillywaytopassafilearound'}=$contents;
 7447:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7448: 
 7449: }
 7450: 
 7451: =pod
 7452: 
 7453: =item scantron_putfile
 7454: 
 7455:     Stores the current version of the bubblesheet data files, and the
 7456:     scan_data hash. (Does not modify the original version only the
 7457:     corrected and skipped versions.
 7458: 
 7459:  Arguments:
 7460:     $scanlines - hash ref that looks like the first return value from
 7461:                  &scantron_getfile()
 7462:     $scan_data - hash ref that looks like the second return value from
 7463:                  &scantron_getfile()
 7464: 
 7465: =cut
 7466: 
 7467: sub scantron_putfile {
 7468:     my ($scanlines,$scan_data) = @_;
 7469:     #FIXME really would prefer a scantron directory
 7470:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7471:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7472:     if ($scanlines) {
 7473: 	my $prefix='scantron_';
 7474: # no need to update orig, shouldn't change
 7475: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7476: #		    $env{'form.scantron_selectfile'});
 7477: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7478: 			$prefix.'corrected_'.
 7479: 			$env{'form.scantron_selectfile'});
 7480: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7481: 			$prefix.'skipped_'.
 7482: 			$env{'form.scantron_selectfile'});
 7483:     }
 7484:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7485: }
 7486: 
 7487: =pod
 7488: 
 7489: =item scantron_get_line
 7490: 
 7491:    Returns the correct version of the scanline
 7492: 
 7493:  Arguments:
 7494:     $scanlines - hash ref that looks like the first return value from
 7495:                  &scantron_getfile()
 7496:     $scan_data - hash ref that looks like the second return value from
 7497:                  &scantron_getfile()
 7498:     $i         - number of the requested line (starts at 0)
 7499: 
 7500:  Returns:
 7501:    A scanline, (either the original or the corrected one if it
 7502:    exists), or undef if the requested scanline should be
 7503:    skipped. (Either because it's an skipped scanline, or it's an
 7504:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7505:    pass.
 7506: 
 7507: =cut
 7508: 
 7509: sub scantron_get_line {
 7510:     my ($scanlines,$scan_data,$i)=@_;
 7511:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7512:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7513:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7514:     return $scanlines->{'orig'}[$i]; 
 7515: }
 7516: 
 7517: =pod
 7518: 
 7519: =item scantron_todo_count
 7520: 
 7521:     Counts the number of scanlines that need processing.
 7522: 
 7523:  Arguments:
 7524:     $scanlines - hash ref that looks like the first return value from
 7525:                  &scantron_getfile()
 7526:     $scan_data - hash ref that looks like the second return value from
 7527:                  &scantron_getfile()
 7528: 
 7529:  Returns:
 7530:     $count - number of scanlines to process
 7531: 
 7532: =cut
 7533: 
 7534: sub get_todo_count {
 7535:     my ($scanlines,$scan_data)=@_;
 7536:     my $count=0;
 7537:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7538: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7539: 	if ($line=~/^[\s\cz]*$/) { next; }
 7540: 	$count++;
 7541:     }
 7542:     return $count;
 7543: }
 7544: 
 7545: =pod
 7546: 
 7547: =item scantron_put_line
 7548: 
 7549:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7550:     data file.
 7551: 
 7552:  Arguments:
 7553:     $scanlines - hash ref that looks like the first return value from
 7554:                  &scantron_getfile()
 7555:     $scan_data - hash ref that looks like the second return value from
 7556:                  &scantron_getfile()
 7557:     $i         - line number to update
 7558:     $newline   - contents of the updated scanline
 7559:     $skip      - if true make the line for skipping and update the
 7560:                  'skipped' file
 7561: 
 7562: =cut
 7563: 
 7564: sub scantron_put_line {
 7565:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7566:     if ($skip) {
 7567: 	$scanlines->{'skipped'}[$i]=$newline;
 7568: 	&start_skipping($scan_data,$i);
 7569: 	return;
 7570:     }
 7571:     $scanlines->{'corrected'}[$i]=$newline;
 7572: }
 7573: 
 7574: =pod
 7575: 
 7576: =item scantron_clear_skip
 7577: 
 7578:    Remove a line from the 'skipped' file
 7579: 
 7580:  Arguments:
 7581:     $scanlines - hash ref that looks like the first return value from
 7582:                  &scantron_getfile()
 7583:     $scan_data - hash ref that looks like the second return value from
 7584:                  &scantron_getfile()
 7585:     $i         - line number to update
 7586: 
 7587: =cut
 7588: 
 7589: sub scantron_clear_skip {
 7590:     my ($scanlines,$scan_data,$i)=@_;
 7591:     if (exists($scanlines->{'skipped'}[$i])) {
 7592: 	undef($scanlines->{'skipped'}[$i]);
 7593: 	return 1;
 7594:     }
 7595:     return 0;
 7596: }
 7597: 
 7598: =pod
 7599: 
 7600: =item scantron_filter_not_exam
 7601: 
 7602:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7603:    filter out resources that are not marked as 'exam' mode
 7604: 
 7605: =cut
 7606: 
 7607: sub scantron_filter_not_exam {
 7608:     my ($curres)=@_;
 7609:     
 7610:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7611: 	# if the user has asked to not have either hidden
 7612: 	# or 'randomout' controlled resources to be graded
 7613: 	# don't include them
 7614: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7615: 	    && $curres->randomout) {
 7616: 	    return 0;
 7617: 	}
 7618: 	return 1;
 7619:     }
 7620:     return 0;
 7621: }
 7622: 
 7623: =pod
 7624: 
 7625: =item scantron_validate_sequence
 7626: 
 7627:     Validates the selected sequence, checking for resource that are
 7628:     not set to exam mode.
 7629: 
 7630: =cut
 7631: 
 7632: sub scantron_validate_sequence {
 7633:     my ($r,$currentphase) = @_;
 7634: 
 7635:     my $navmap=Apache::lonnavmaps::navmap->new();
 7636:     unless (ref($navmap)) {
 7637:         $r->print(&navmap_errormsg());
 7638:         return (1,$currentphase);
 7639:     }
 7640:     my (undef,undef,$sequence)=
 7641: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7642: 
 7643:     my $map=$navmap->getResourceByUrl($sequence);
 7644: 
 7645:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7646:                                     value="ignore" />');
 7647:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7648: 	my @resources=
 7649: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7650: 	if (@resources) {
 7651: 	    $r->print('<p class="LC_warning">'
 7652:                .&mt('Some resources in the sequence currently are not set to'
 7653:                    .' exam mode. Grading these resources currently may not'
 7654:                    .' work correctly.')
 7655:                .'</p>'
 7656:             );
 7657: 	    return (1,$currentphase);
 7658: 	}
 7659:     }
 7660: 
 7661:     return (0,$currentphase+1);
 7662: }
 7663: 
 7664: 
 7665: 
 7666: sub scantron_validate_ID {
 7667:     my ($r,$currentphase) = @_;
 7668:     
 7669:     #get student info
 7670:     my $classlist=&Apache::loncoursedata::get_classlist();
 7671:     my %idmap=&username_to_idmap($classlist);
 7672: 
 7673:     #get scantron line setup
 7674:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7675:     my ($scanlines,$scan_data)=&scantron_getfile();
 7676: 
 7677:     my $nav_error;
 7678:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7679:     if ($nav_error) {
 7680:         $r->print(&navmap_errormsg());
 7681:         return(1,$currentphase);
 7682:     }
 7683: 
 7684:     my %found=('ids'=>{},'usernames'=>{});
 7685:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7686: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7687: 	if ($line=~/^[\s\cz]*$/) { next; }
 7688: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7689: 						 $scan_data);
 7690: 	my $id=$$scan_record{'scantron.ID'};
 7691: 	my $found;
 7692: 	foreach my $checkid (keys(%idmap)) {
 7693: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7694: 	}
 7695: 	if ($found) {
 7696: 	    my $username=$idmap{$found};
 7697: 	    if ($found{'ids'}{$found}) {
 7698: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7699: 					 $line,'duplicateID',$found);
 7700: 		return(1,$currentphase);
 7701: 	    } elsif ($found{'usernames'}{$username}) {
 7702: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7703: 					 $line,'duplicateID',$username);
 7704: 		return(1,$currentphase);
 7705: 	    }
 7706: 	    #FIXME store away line we previously saw the ID on to use above
 7707: 	    $found{'ids'}{$found}++;
 7708: 	    $found{'usernames'}{$username}++;
 7709: 	} else {
 7710: 	    if ($id =~ /^\s*$/) {
 7711: 		my $username=&scan_data($scan_data,"$i.user");
 7712: 		if (defined($username) && $found{'usernames'}{$username}) {
 7713: 		    &scantron_get_correction($r,$i,$scan_record,
 7714: 					     \%scantron_config,
 7715: 					     $line,'duplicateID',$username);
 7716: 		    return(1,$currentphase);
 7717: 		} elsif (!defined($username)) {
 7718: 		    &scantron_get_correction($r,$i,$scan_record,
 7719: 					     \%scantron_config,
 7720: 					     $line,'incorrectID');
 7721: 		    return(1,$currentphase);
 7722: 		}
 7723: 		$found{'usernames'}{$username}++;
 7724: 	    } else {
 7725: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7726: 					 $line,'incorrectID');
 7727: 		return(1,$currentphase);
 7728: 	    }
 7729: 	}
 7730:     }
 7731: 
 7732:     return (0,$currentphase+1);
 7733: }
 7734: 
 7735: 
 7736: sub scantron_get_correction {
 7737:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7738:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7739: #FIXME in the case of a duplicated ID the previous line, probably need
 7740: #to show both the current line and the previous one and allow skipping
 7741: #the previous one or the current one
 7742: 
 7743:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7744:         $r->print(
 7745:             '<p class="LC_warning">'
 7746:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7747:                 "<b>$error</b>",
 7748:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7749:            ."</p> \n");
 7750:     } else {
 7751:         $r->print(
 7752:             '<p class="LC_warning">'
 7753:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7754:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7755:            ."</p> \n");
 7756:     }
 7757:     my $message =
 7758:         '<p>'
 7759:        .&mt('The ID on the form is [_1]',
 7760:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7761:        .'<br />'
 7762:        .&mt('The name on the paper is [_1], [_2]',
 7763:             $$scan_record{'scantron.LastName'},
 7764:             $$scan_record{'scantron.FirstName'})
 7765:        .'</p>';
 7766: 
 7767:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7768:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7769:                            # Array populated for doublebubble or
 7770:     my @lines_to_correct;  # missingbubble errors to build javascript
 7771:                            # to validate radio button checking   
 7772: 
 7773:     if ($error =~ /ID$/) {
 7774: 	if ($error eq 'incorrectID') {
 7775: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7776: 		      "</p>\n");
 7777: 	} elsif ($error eq 'duplicateID') {
 7778: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7779: 	}
 7780: 	$r->print($message);
 7781: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7782: 	$r->print("\n<ul><li> ");
 7783: 	#FIXME it would be nice if this sent back the user ID and
 7784: 	#could do partial userID matches
 7785: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7786: 				       'scantron_username','scantron_domain'));
 7787: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7788: 	$r->print("\n:\n".
 7789: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7790: 
 7791: 	$r->print('</li>');
 7792:     } elsif ($error =~ /CODE$/) {
 7793: 	if ($error eq 'incorrectCODE') {
 7794: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7795: 	} elsif ($error eq 'duplicateCODE') {
 7796: 	    $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");
 7797: 	}
 7798:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7799:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7800:                  ."</p>\n");
 7801: 	$r->print($message);
 7802: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7803: 	$r->print("\n<br /> ");
 7804: 	my $i=0;
 7805: 	if ($error eq 'incorrectCODE' 
 7806: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7807: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7808: 	    if ($closest > 0) {
 7809: 		foreach my $testcode (@{$closest}) {
 7810: 		    my $checked='';
 7811: 		    if (!$i) { $checked=' checked="checked"'; }
 7812: 		    $r->print("
 7813:    <label>
 7814:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7815:        ".&mt("Use the similar CODE [_1] instead.",
 7816: 	    "<b><tt>".$testcode."</tt></b>")."
 7817:     </label>
 7818:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7819: 		    $r->print("\n<br />");
 7820: 		    $i++;
 7821: 		}
 7822: 	    }
 7823: 	}
 7824: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7825: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7826: 	    $r->print("
 7827:     <label>
 7828:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7829:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7830: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7831:     </label>");
 7832: 	    $r->print("\n<br />");
 7833: 	}
 7834: 
 7835: 	$r->print(<<ENDSCRIPT);
 7836: <script type="text/javascript">
 7837: function change_radio(field) {
 7838:     var slct=document.scantronupload.scantron_CODE_resolution;
 7839:     var i;
 7840:     for (i=0;i<slct.length;i++) {
 7841:         if (slct[i].value==field) { slct[i].checked=true; }
 7842:     }
 7843: }
 7844: </script>
 7845: ENDSCRIPT
 7846: 	my $href="/adm/pickcode?".
 7847: 	   "form=".&escape("scantronupload").
 7848: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7849: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7850: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7851: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7852: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7853: 	    $r->print("
 7854:     <label>
 7855:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7856:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7857: 	     "<a target='_blank' href='$href'>","</a>")."
 7858:     </label> 
 7859:     ".&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\')" />'));
 7860: 	    $r->print("\n<br />");
 7861: 	}
 7862: 	$r->print("
 7863:     <label>
 7864:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7865:        ".&mt("Use [_1] as the CODE.",
 7866: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7867: 	$r->print("\n<br /><br />");
 7868:     } elsif ($error eq 'doublebubble') {
 7869: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7870: 
 7871: 	# The form field scantron_questions is acutally a list of line numbers.
 7872: 	# represented by this form so:
 7873: 
 7874: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7875:                                                 $respnumlookup,$startline);
 7876: 
 7877: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7878: 		  $line_list.'" />');
 7879: 	$r->print($message);
 7880: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7881: 	foreach my $question (@{$arg}) {
 7882: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7883:                                                    $scan_record, $error,
 7884:                                                    $randomorder,$randompick,
 7885:                                                    $respnumlookup,$startline);
 7886:             push(@lines_to_correct,@linenums);
 7887: 	}
 7888:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7889:     } elsif ($error eq 'missingbubble') {
 7890: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7891: 	$r->print($message);
 7892: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7893: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7894: 
 7895: 	# The form field scantron_questions is actually a list of line numbers not
 7896: 	# a list of question numbers. Therefore:
 7897: 	#
 7898: 	
 7899: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7900:                                                 $respnumlookup,$startline);
 7901: 
 7902: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7903: 		  $line_list.'" />');
 7904: 	foreach my $question (@{$arg}) {
 7905: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7906:                                                    $scan_record, $error,
 7907:                                                    $randomorder,$randompick,
 7908:                                                    $respnumlookup,$startline);
 7909:             push(@lines_to_correct,@linenums);
 7910: 	}
 7911:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7912:     } else {
 7913: 	$r->print("\n<ul>");
 7914:     }
 7915:     $r->print("\n</li></ul>");
 7916: }
 7917: 
 7918: sub verify_bubbles_checked {
 7919:     my (@ansnums) = @_;
 7920:     my $ansnumstr = join('","',@ansnums);
 7921:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7922:     &js_escape(\$warning);
 7923:     my $output = (<<ENDSCRIPT);
 7924: <script type="text/javascript">
 7925: function verify_bubble_radio(form) {
 7926:     var ansnumArray = new Array ("$ansnumstr");
 7927:     var need_bubble_count = 0;
 7928:     for (var i=0; i<ansnumArray.length; i++) {
 7929:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7930:             var bubble_picked = 0; 
 7931:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7932:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7933:                     bubble_picked = 1;
 7934:                 }
 7935:             }
 7936:             if (bubble_picked == 0) {
 7937:                 need_bubble_count ++;
 7938:             }
 7939:         }
 7940:     }
 7941:     if (need_bubble_count) {
 7942:         alert("$warning");
 7943:         return;
 7944:     }
 7945:     form.submit(); 
 7946: }
 7947: </script>
 7948: ENDSCRIPT
 7949:     return $output;
 7950: }
 7951: 
 7952: =pod
 7953: 
 7954: =item  questions_to_line_list
 7955: 
 7956: Converts a list of questions into a string of comma separated
 7957: line numbers in the answer sheet used by the questions.  This is
 7958: used to fill in the scantron_questions form field.
 7959: 
 7960:   Arguments:
 7961:      questions    - Reference to an array of questions.
 7962:      randomorder  - True if randomorder in use.
 7963:      randompick   - True if randompick in use.
 7964:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7965:                      for current line to question number used for same question
 7966:                      in "Master Seqence" (as seen by Course Coordinator).
 7967:      startline    - Reference to hash where key is question number (0 is first)
 7968:                     and key is number of first bubble line for current student
 7969:                     or code-based randompick and/or randomorder.
 7970: 
 7971: =cut
 7972: 
 7973: 
 7974: sub questions_to_line_list {
 7975:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7976:     my @lines;
 7977: 
 7978:     foreach my $item (@{$questions}) {
 7979:         my $question = $item;
 7980:         my ($first,$count,$last);
 7981:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7982:             $question = $1;
 7983:             my $subquestion = $2;
 7984:             my $responsenum = $question-1;
 7985:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7986:                 $responsenum = $respnumlookup->{$question-1};
 7987:                 if (ref($startline) eq 'HASH') {
 7988:                     $first = $startline->{$question-1} + 1;
 7989:                 }
 7990:             } else {
 7991:                 $first = $first_bubble_line{$responsenum} + 1;
 7992:             }
 7993:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7994:             my $subcount = 1;
 7995:             while ($subcount<$subquestion) {
 7996:                 $first += $subans[$subcount-1];
 7997:                 $subcount ++;
 7998:             }
 7999:             $count = $subans[$subquestion-1];
 8000:         } else {
 8001:             my $responsenum = $question-1;
 8002:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8003:                 $responsenum = $respnumlookup->{$question-1};
 8004:                 if (ref($startline) eq 'HASH') {
 8005:                     $first = $startline->{$question-1} + 1;
 8006:                 }
 8007:             } else {
 8008:                 $first = $first_bubble_line{$responsenum} + 1;
 8009:             }
 8010:             $count   = $bubble_lines_per_response{$responsenum};
 8011:         }
 8012:         $last = $first+$count-1;
 8013:         push(@lines, ($first..$last));
 8014:     }
 8015:     return join(',', @lines);
 8016: }
 8017: 
 8018: =pod 
 8019: 
 8020: =item prompt_for_corrections
 8021: 
 8022: Prompts for a potentially multiline correction to the
 8023: user's bubbling (factors out common code from scantron_get_correction
 8024: for multi and missing bubble cases).
 8025: 
 8026:  Arguments:
 8027:    $r           - Apache request object.
 8028:    $question    - The question number to prompt for.
 8029:    $scan_config - The scantron file configuration hash.
 8030:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8031:    $error       - Type of error
 8032:    $randomorder - True if randomorder in use.
 8033:    $randompick  - True if randompick in use.
 8034:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8035:                     for current line to question number used for same question
 8036:                     in "Master Seqence" (as seen by Course Coordinator).
 8037:    $startline   - Reference to hash where key is question number (0 is first)
 8038:                   and value is number of first bubble line for current student
 8039:                   or code-based randompick and/or randomorder.
 8040: 
 8041:  Implicit inputs:
 8042:    %bubble_lines_per_response   - Starting line numbers for each question.
 8043:                                   Numbered from 0 (but question numbers are from
 8044:                                   1.
 8045:    %first_bubble_line           - Starting bubble line for each question.
 8046:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8047:                                   type problems render as separate sub-questions, 
 8048:                                   in exam mode. This hash contains a 
 8049:                                   comma-separated list of the lines per 
 8050:                                   sub-question.
 8051:    %responsetype_per_response   - essayresponse, formularesponse,
 8052:                                   stringresponse, imageresponse, reactionresponse,
 8053:                                   and organicresponse type problem parts can have
 8054:                                   multiple lines per response if the weight
 8055:                                   assigned exceeds 10.  In this case, only
 8056:                                   one bubble per line is permitted, but more 
 8057:                                   than one line might contain bubbles, e.g.
 8058:                                   bubbling of: line 1 - J, line 2 - J, 
 8059:                                   line 3 - B would assign 22 points.  
 8060: 
 8061: =cut
 8062: 
 8063: sub prompt_for_corrections {
 8064:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8065:         $randompick, $respnumlookup, $startline) = @_;
 8066:     my ($current_line,$lines);
 8067:     my @linenums;
 8068:     my $questionnum = $question;
 8069:     my ($first,$responsenum);
 8070:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8071:         $question = $1;
 8072:         my $subquestion = $2;
 8073:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8074:             $responsenum = $respnumlookup->{$question-1};
 8075:             if (ref($startline) eq 'HASH') {
 8076:                 $first = $startline->{$question-1};
 8077:             }
 8078:         } else {
 8079:             $responsenum = $question-1;
 8080:             $first = $first_bubble_line{$responsenum};
 8081:         }
 8082:         $current_line = $first + 1 ;
 8083:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8084:         my $subcount = 1;
 8085:         while ($subcount<$subquestion) {
 8086:             $current_line += $subans[$subcount-1];
 8087:             $subcount ++;
 8088:         }
 8089:         $lines = $subans[$subquestion-1];
 8090:     } else {
 8091:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8092:             $responsenum = $respnumlookup->{$question-1};
 8093:             if (ref($startline) eq 'HASH') {
 8094:                 $first = $startline->{$question-1};
 8095:             }
 8096:         } else {
 8097:             $responsenum = $question-1;
 8098:             $first = $first_bubble_line{$responsenum};
 8099:         }
 8100:         $current_line = $first + 1;
 8101:         $lines        = $bubble_lines_per_response{$responsenum};
 8102:     }
 8103:     if ($lines > 1) {
 8104:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8105:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8106:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8107:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8108:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8109:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8110:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8111:             $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 />');
 8112:         } else {
 8113:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8114:         }
 8115:     }
 8116:     for (my $i =0; $i < $lines; $i++) {
 8117:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8118: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8119: 	        		  $questionnum,$error,split('', $selected));
 8120:         push(@linenums,$current_line);
 8121: 	$current_line++;
 8122:     }
 8123:     if ($lines > 1) {
 8124: 	$r->print("<hr /><br />");
 8125:     }
 8126:     return @linenums;
 8127: }
 8128: 
 8129: =pod
 8130: 
 8131: =item scantron_bubble_selector
 8132:   
 8133:    Generates the html radiobuttons to correct a single bubble line
 8134:    possibly showing the existing the selected bubbles if known
 8135: 
 8136:  Arguments:
 8137:     $r           - Apache request object
 8138:     $scan_config - hash from &get_scantron_config()
 8139:     $line        - Number of the line being displayed.
 8140:     $questionnum - Question number (may include subquestion)
 8141:     $error       - Type of error.
 8142:     @selected    - Array of bubbles picked on this line.
 8143: 
 8144: =cut
 8145: 
 8146: sub scantron_bubble_selector {
 8147:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8148:     my $max=$$scan_config{'Qlength'};
 8149: 
 8150:     my $scmode=$$scan_config{'Qon'};
 8151:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8152:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8153:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8154:             $max=$$scan_config{'BubblesPerRow'};
 8155:             if (($scmode eq 'number') && ($max > 10)) {
 8156:                 $max = 10;
 8157:             } elsif (($scmode eq 'letter') && $max > 26) {
 8158:                 $max = 26;
 8159:             }
 8160:         } else {
 8161:             $max = 10;
 8162:         }
 8163:     }
 8164: 
 8165:     my @alphabet=('A'..'Z');
 8166:     $r->print(&Apache::loncommon::start_data_table().
 8167:               &Apache::loncommon::start_data_table_row());
 8168:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8169:     for (my $i=0;$i<$max+1;$i++) {
 8170: 	$r->print("\n".'<td align="center">');
 8171: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8172: 	else { $r->print('&nbsp;'); }
 8173: 	$r->print('</td>');
 8174:     }
 8175:     $r->print(&Apache::loncommon::end_data_table_row().
 8176:               &Apache::loncommon::start_data_table_row());
 8177:     for (my $i=0;$i<$max;$i++) {
 8178: 	$r->print("\n".
 8179: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8180: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8181:     }
 8182:     my $nobub_checked = ' ';
 8183:     if ($error eq 'missingbubble') {
 8184:         $nobub_checked = ' checked = "checked" ';
 8185:     }
 8186:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8187: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8188:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8189:               $line.'" value="'.$questionnum.'" /></td>');
 8190:     $r->print(&Apache::loncommon::end_data_table_row().
 8191:               &Apache::loncommon::end_data_table());
 8192: }
 8193: 
 8194: =pod
 8195: 
 8196: =item num_matches
 8197: 
 8198:    Counts the number of characters that are the same between the two arguments.
 8199: 
 8200:  Arguments:
 8201:    $orig - CODE from the scanline
 8202:    $code - CODE to match against
 8203: 
 8204:  Returns:
 8205:    $count - integer count of the number of same characters between the
 8206:             two arguments
 8207: 
 8208: =cut
 8209: 
 8210: sub num_matches {
 8211:     my ($orig,$code) = @_;
 8212:     my @code=split(//,$code);
 8213:     my @orig=split(//,$orig);
 8214:     my $same=0;
 8215:     for (my $i=0;$i<scalar(@code);$i++) {
 8216: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8217:     }
 8218:     return $same;
 8219: }
 8220: 
 8221: =pod
 8222: 
 8223: =item scantron_get_closely_matching_CODEs
 8224: 
 8225:    Cycles through all CODEs and finds the set that has the greatest
 8226:    number of same characters as the provided CODE
 8227: 
 8228:  Arguments:
 8229:    $allcodes - hash ref returned by &get_codes()
 8230:    $CODE     - CODE from the current scanline
 8231: 
 8232:  Returns:
 8233:    2 element list
 8234:     - first elements is number of how closely matching the best fit is 
 8235:       (5 means best set has 5 matching characters)
 8236:     - second element is an arrary ref containing the set of valid CODEs
 8237:       that best fit the passed in CODE
 8238: 
 8239: =cut
 8240: 
 8241: sub scantron_get_closely_matching_CODEs {
 8242:     my ($allcodes,$CODE)=@_;
 8243:     my @CODEs;
 8244:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8245: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8246:     }
 8247: 
 8248:     return ($#CODEs,$CODEs[-1]);
 8249: }
 8250: 
 8251: =pod
 8252: 
 8253: =item get_codes
 8254: 
 8255:    Builds a hash which has keys of all of the valid CODEs from the selected
 8256:    set of remembered CODEs.
 8257: 
 8258:  Arguments:
 8259:   $old_name - name of the set of remembered CODEs
 8260:   $cdom     - domain of the course
 8261:   $cnum     - internal course name
 8262: 
 8263:  Returns:
 8264:   %allcodes - keys are the valid CODEs, values are all 1
 8265: 
 8266: =cut
 8267: 
 8268: sub get_codes {
 8269:     my ($old_name, $cdom, $cnum) = @_;
 8270:     if (!$old_name) {
 8271: 	$old_name=$env{'form.scantron_CODElist'};
 8272:     }
 8273:     if (!$cdom) {
 8274: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8275:     }
 8276:     if (!$cnum) {
 8277: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8278:     }
 8279:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8280: 				    $cdom,$cnum);
 8281:     my %allcodes;
 8282:     if ($result{"type\0$old_name"} eq 'number') {
 8283: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8284:     } else {
 8285: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8286:     }
 8287:     return %allcodes;
 8288: }
 8289: 
 8290: =pod
 8291: 
 8292: =item scantron_validate_CODE
 8293: 
 8294:    Validates all scanlines in the selected file to not have any
 8295:    invalid or underspecified CODEs and that none of the codes are
 8296:    duplicated if this was requested.
 8297: 
 8298: =cut
 8299: 
 8300: sub scantron_validate_CODE {
 8301:     my ($r,$currentphase) = @_;
 8302:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8303:     if ($scantron_config{'CODElocation'} &&
 8304: 	$scantron_config{'CODEstart'} &&
 8305: 	$scantron_config{'CODElength'}) {
 8306: 	if (!defined($env{'form.scantron_CODElist'})) {
 8307: 	    &FIXME_blow_up()
 8308: 	}
 8309:     } else {
 8310: 	return (0,$currentphase+1);
 8311:     }
 8312:     
 8313:     my %usedCODEs;
 8314: 
 8315:     my %allcodes=&get_codes();
 8316: 
 8317:     my $nav_error;
 8318:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8319:     if ($nav_error) {
 8320:         $r->print(&navmap_errormsg());
 8321:         return(1,$currentphase);
 8322:     }
 8323: 
 8324:     my ($scanlines,$scan_data)=&scantron_getfile();
 8325:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8326: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8327: 	if ($line=~/^[\s\cz]*$/) { next; }
 8328: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8329: 						 $scan_data);
 8330: 	my $CODE=$$scan_record{'scantron.CODE'};
 8331: 	my $error=0;
 8332: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8333: 	    &scantron_get_correction($r,$i,$scan_record,
 8334: 				     \%scantron_config,
 8335: 				     $line,'incorrectCODE',\%allcodes);
 8336: 	    return(1,$currentphase);
 8337: 	}
 8338: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8339: 	    && !$$scan_record{'scantron.useCODE'}) {
 8340: 	    &scantron_get_correction($r,$i,$scan_record,
 8341: 				     \%scantron_config,
 8342: 				     $line,'incorrectCODE',\%allcodes);
 8343: 	    return(1,$currentphase);
 8344: 	}
 8345: 	if (exists($usedCODEs{$CODE}) 
 8346: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8347: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8348: 	    &scantron_get_correction($r,$i,$scan_record,
 8349: 				     \%scantron_config,
 8350: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8351: 	    return(1,$currentphase);
 8352: 	}
 8353: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8354:     }
 8355:     return (0,$currentphase+1);
 8356: }
 8357: 
 8358: =pod
 8359: 
 8360: =item scantron_validate_doublebubble
 8361: 
 8362:    Validates all scanlines in the selected file to not have any
 8363:    bubble lines with multiple bubbles marked.
 8364: 
 8365: =cut
 8366: 
 8367: sub scantron_validate_doublebubble {
 8368:     my ($r,$currentphase) = @_;
 8369:     #get student info
 8370:     my $classlist=&Apache::loncoursedata::get_classlist();
 8371:     my %idmap=&username_to_idmap($classlist);
 8372:     my (undef,undef,$sequence)=
 8373:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8374: 
 8375:     #get scantron line setup
 8376:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8377:     my ($scanlines,$scan_data)=&scantron_getfile();
 8378: 
 8379:     my $navmap = Apache::lonnavmaps::navmap->new();
 8380:     unless (ref($navmap)) {
 8381:         $r->print(&navmap_errormsg());
 8382:         return(1,$currentphase);
 8383:     }
 8384:     my $map=$navmap->getResourceByUrl($sequence);
 8385:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8386:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8387:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8388:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8389: 
 8390:     my $nav_error;
 8391:     if (ref($map)) {
 8392:         $randomorder = $map->randomorder();
 8393:         $randompick = $map->randompick();
 8394:         if ($randomorder || $randompick) {
 8395:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8396:             if ($nav_error) {
 8397:                 $r->print(&navmap_errormsg());
 8398:                 return(1,$currentphase);
 8399:             }
 8400:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8401:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8402:         }
 8403:     } else {
 8404:         $r->print(&navmap_errormsg());
 8405:         return(1,$currentphase);
 8406:     }
 8407: 
 8408:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8409:     if ($nav_error) {
 8410:         $r->print(&navmap_errormsg());
 8411:         return(1,$currentphase);
 8412:     }
 8413: 
 8414:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8415: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8416: 	if ($line=~/^[\s\cz]*$/) { next; }
 8417: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8418: 						 $scan_data,undef,\%idmap,$randomorder,
 8419:                                                  $randompick,$sequence,\@master_seq,
 8420:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8421:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8422: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8423: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8424: 				 'doublebubble',
 8425: 				 $$scan_record{'scantron.doubleerror'},
 8426:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8427:     	return (1,$currentphase);
 8428:     }
 8429:     return (0,$currentphase+1);
 8430: }
 8431: 
 8432: 
 8433: sub scantron_get_maxbubble {
 8434:     my ($nav_error,$scantron_config) = @_;
 8435:     if (defined($env{'form.scantron_maxbubble'}) &&
 8436: 	$env{'form.scantron_maxbubble'}) {
 8437: 	&restore_bubble_lines();
 8438: 	return $env{'form.scantron_maxbubble'};
 8439:     }
 8440: 
 8441:     my (undef, undef, $sequence) =
 8442: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8443: 
 8444:     my $navmap=Apache::lonnavmaps::navmap->new();
 8445:     unless (ref($navmap)) {
 8446:         if (ref($nav_error)) {
 8447:             $$nav_error = 1;
 8448:         }
 8449:         return;
 8450:     }
 8451:     my $map=$navmap->getResourceByUrl($sequence);
 8452:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8453:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8454: 
 8455:     &Apache::lonxml::clear_problem_counter();
 8456: 
 8457:     my $uname       = $env{'user.name'};
 8458:     my $udom        = $env{'user.domain'};
 8459:     my $cid         = $env{'request.course.id'};
 8460:     my $total_lines = 0;
 8461:     %bubble_lines_per_response = ();
 8462:     %first_bubble_line         = ();
 8463:     %subdivided_bubble_lines   = ();
 8464:     %responsetype_per_response = ();
 8465:     %masterseq_id_responsenum  = ();
 8466: 
 8467:     my $response_number = 0;
 8468:     my $bubble_line     = 0;
 8469:     foreach my $resource (@resources) {
 8470:         my $resid = $resource->id();
 8471:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8472:                                                           $udom,undef,$bubbles_per_row);
 8473:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8474: 	    foreach my $part_id (@{$parts}) {
 8475:                 my $lines;
 8476: 
 8477: 	        # TODO - make this a persistent hash not an array.
 8478: 
 8479:                 # optionresponse, matchresponse and rankresponse type items 
 8480:                 # render as separate sub-questions in exam mode.
 8481:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8482:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8483:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8484:                     my ($numbub,$numshown);
 8485:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8486:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8487:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8488:                         }
 8489:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8490:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8491:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8492:                         }
 8493:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8494:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8495:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8496:                         }
 8497:                     }
 8498:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8499:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8500:                     }
 8501:                     my $bubbles_per_row =
 8502:                         &bubblesheet_bubbles_per_row($scantron_config);
 8503:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8504:                     if (($numbub % $bubbles_per_row) != 0) {
 8505:                         $inner_bubble_lines++;
 8506:                     }
 8507:                     for (my $i=0; $i<$numshown; $i++) {
 8508:                         $subdivided_bubble_lines{$response_number} .= 
 8509:                             $inner_bubble_lines.',';
 8510:                     }
 8511:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8512:                     $lines = $numshown * $inner_bubble_lines;
 8513:                 } else {
 8514:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8515:                 }
 8516: 
 8517:                 $first_bubble_line{$response_number} = $bubble_line;
 8518: 	        $bubble_lines_per_response{$response_number} = $lines;
 8519:                 $responsetype_per_response{$response_number} = 
 8520:                     $analysis->{$part_id.'.type'};
 8521:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8522: 	        $response_number++;
 8523: 
 8524: 	        $bubble_line +=  $lines;
 8525: 	        $total_lines +=  $lines;
 8526: 	    }
 8527:         }
 8528:     }
 8529:     &Apache::lonnet::delenv('scantron.');
 8530: 
 8531:     &save_bubble_lines();
 8532:     $env{'form.scantron_maxbubble'} =
 8533: 	$total_lines;
 8534:     return $env{'form.scantron_maxbubble'};
 8535: }
 8536: 
 8537: sub bubblesheet_bubbles_per_row {
 8538:     my ($scantron_config) = @_;
 8539:     my $bubbles_per_row;
 8540:     if (ref($scantron_config) eq 'HASH') {
 8541:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8542:     }
 8543:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8544:         $bubbles_per_row = 10;
 8545:     }
 8546:     return $bubbles_per_row;
 8547: }
 8548: 
 8549: sub scantron_validate_missingbubbles {
 8550:     my ($r,$currentphase) = @_;
 8551:     #get student info
 8552:     my $classlist=&Apache::loncoursedata::get_classlist();
 8553:     my %idmap=&username_to_idmap($classlist);
 8554:     my (undef,undef,$sequence)=
 8555:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8556: 
 8557:     #get scantron line setup
 8558:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8559:     my ($scanlines,$scan_data)=&scantron_getfile();
 8560: 
 8561:     my $navmap = Apache::lonnavmaps::navmap->new();
 8562:     unless (ref($navmap)) {
 8563:         $r->print(&navmap_errormsg());
 8564:         return(1,$currentphase);
 8565:     }
 8566: 
 8567:     my $map=$navmap->getResourceByUrl($sequence);
 8568:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8569:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8570:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8571:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8572: 
 8573:     my $nav_error;
 8574:     if (ref($map)) {
 8575:         $randomorder = $map->randomorder();
 8576:         $randompick = $map->randompick();
 8577:         if ($randomorder || $randompick) {
 8578:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8579:             if ($nav_error) {
 8580:                 $r->print(&navmap_errormsg());
 8581:                 return(1,$currentphase);
 8582:             }
 8583:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8584:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8585:         }
 8586:     } else {
 8587:         $r->print(&navmap_errormsg());
 8588:         return(1,$currentphase);
 8589:     }
 8590: 
 8591: 
 8592:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8593:     if ($nav_error) {
 8594:         $r->print(&navmap_errormsg());
 8595:         return(1,$currentphase);
 8596:     }
 8597: 
 8598:     if (!$max_bubble) { $max_bubble=2**31; }
 8599:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8600: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8601: 	if ($line=~/^[\s\cz]*$/) { next; }
 8602:         my $scan_record =
 8603:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8604:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8605:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8606:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8607: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8608: 	my @to_correct;
 8609: 	
 8610: 	# Probably here's where the error is...
 8611: 
 8612: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8613:             my $lastbubble;
 8614:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8615:                 my $question = $1;
 8616:                 my $subquestion = $2;
 8617:                 my ($first,$responsenum);
 8618:                 if ($randomorder || $randompick) {
 8619:                     $responsenum = $respnumlookup{$question-1};
 8620:                     $first = $startline{$question-1};
 8621:                 } else {
 8622:                     $responsenum = $question-1;
 8623:                     $first = $first_bubble_line{$responsenum};
 8624:                 }
 8625:                 if (!defined($first)) { next; }
 8626:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8627:                 my $subcount = 1;
 8628:                 while ($subcount<$subquestion) {
 8629:                     $first += $subans[$subcount-1];
 8630:                     $subcount ++;
 8631:                 }
 8632:                 my $count = $subans[$subquestion-1];
 8633:                 $lastbubble = $first + $count;
 8634:             } else {
 8635:                 my ($first,$responsenum);
 8636:                 if ($randomorder || $randompick) {
 8637:                     $responsenum = $respnumlookup{$missing-1};
 8638:                     $first = $startline{$missing-1};
 8639:                 } else {
 8640:                     $responsenum = $missing-1;
 8641:                     $first = $first_bubble_line{$responsenum};
 8642:                 }
 8643:                 if (!defined($first)) { next; }
 8644:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8645:             }
 8646:             if ($lastbubble > $max_bubble) { next; }
 8647: 	    push(@to_correct,$missing);
 8648: 	}
 8649: 	if (@to_correct) {
 8650: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8651: 				     $line,'missingbubble',\@to_correct,
 8652:                                      $randomorder,$randompick,\%respnumlookup,
 8653:                                      \%startline);
 8654: 	    return (1,$currentphase);
 8655: 	}
 8656: 
 8657:     }
 8658:     return (0,$currentphase+1);
 8659: }
 8660: 
 8661: sub hand_bubble_option {
 8662:     my (undef, undef, $sequence) =
 8663:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8664:     return if ($sequence eq '');
 8665:     my $navmap = Apache::lonnavmaps::navmap->new();
 8666:     unless (ref($navmap)) {
 8667:         return;
 8668:     }
 8669:     my $needs_hand_bubbles;
 8670:     my $map=$navmap->getResourceByUrl($sequence);
 8671:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8672:     foreach my $res (@resources) {
 8673:         if (ref($res)) {
 8674:             if ($res->is_problem()) {
 8675:                 my $partlist = $res->parts();
 8676:                 foreach my $part (@{ $partlist }) {
 8677:                     my @types = $res->responseType($part);
 8678:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8679:                         $needs_hand_bubbles = 1;
 8680:                         last;
 8681:                     }
 8682:                 }
 8683:             }
 8684:         }
 8685:     }
 8686:     if ($needs_hand_bubbles) {
 8687:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8688:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8689:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8690:                &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 />').
 8691:                '<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;'.
 8692:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8693:     }
 8694:     return;
 8695: }
 8696: 
 8697: sub scantron_process_students {
 8698:     my ($r) = @_;
 8699: 
 8700:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8701:     my ($symb)=&get_symb($r);
 8702:     if (!$symb) {
 8703: 	return '';
 8704:     }
 8705:     my $default_form_data=&defaultFormData($symb);
 8706: 
 8707:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8708:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8709:     my ($scanlines,$scan_data)=&scantron_getfile();
 8710:     my $classlist=&Apache::loncoursedata::get_classlist();
 8711:     my %idmap=&username_to_idmap($classlist);
 8712:     my $navmap=Apache::lonnavmaps::navmap->new();
 8713:     unless (ref($navmap)) {
 8714:         $r->print(&navmap_errormsg());
 8715:         return '';
 8716:     }
 8717:     my $map=$navmap->getResourceByUrl($sequence);
 8718:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8719:         %grader_randomlists_by_symb);
 8720:     if (ref($map)) {
 8721:         $randomorder = $map->randomorder();
 8722:         $randompick = $map->randompick();
 8723:     } else {
 8724:         $r->print(&navmap_errormsg());
 8725:         return '';
 8726:     }
 8727:     my $nav_error;
 8728:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8729:     if ($randomorder || $randompick) {
 8730:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8731:         if ($nav_error) {
 8732:             $r->print(&navmap_errormsg());
 8733:             return '';
 8734:         }
 8735:     }
 8736:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8737:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8738: 
 8739:     my ($uname,$udom);
 8740:     my $result= <<SCANTRONFORM;
 8741: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8742:   <input type="hidden" name="command" value="scantron_configphase" />
 8743:   $default_form_data
 8744: SCANTRONFORM
 8745:     $r->print($result);
 8746: 
 8747:     my @delayqueue;
 8748:     my (%completedstudents,%scandata);
 8749:     
 8750:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8751:     my $count=&get_todo_count($scanlines,$scan_data);
 8752:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8753:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8754: 					  'Processing first student');
 8755:     $r->print('<br />');
 8756:     my $start=&Time::HiRes::time();
 8757:     my $i=-1;
 8758:     my $started;
 8759: 
 8760:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8761:     if ($nav_error) {
 8762:         $r->print(&navmap_errormsg());
 8763:         return '';
 8764:     }
 8765: 
 8766:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8767:     # the user and return.
 8768: 
 8769:     if ($ssi_error) {
 8770: 	$r->print("</form>");
 8771: 	&ssi_print_error($r);
 8772: 	$r->print(&show_grading_menu_form($symb));
 8773:         &Apache::lonnet::remove_lock($lock);
 8774: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8775:     }
 8776: 
 8777:     my %lettdig = &letter_to_digits();
 8778:     my $numletts = scalar(keys(%lettdig));
 8779:     my %orderedforcode;
 8780: 
 8781:     while ($i<$scanlines->{'count'}) {
 8782:  	($uname,$udom)=('','');
 8783:  	$i++;
 8784:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8785:  	if ($line=~/^[\s\cz]*$/) { next; }
 8786: 	if ($started) {
 8787: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8788: 						     'last student');
 8789: 	}
 8790: 	$started=1;
 8791:         my %respnumlookup = ();
 8792:         my %startline = ();
 8793:         my $total;
 8794:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8795:  						 $scan_data,undef,\%idmap,$randomorder,
 8796:                                                  $randompick,$sequence,\@master_seq,
 8797:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8798:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8799:                                                  \$total);
 8800:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8801:  					      \%idmap,$i)) {
 8802:   	    &scantron_add_delay(\@delayqueue,$line,
 8803:  				'Unable to find a student that matches',1);
 8804:  	    next;
 8805:   	}
 8806:  	if (exists $completedstudents{$uname}) {
 8807:  	    &scantron_add_delay(\@delayqueue,$line,
 8808:  				'Student '.$uname.' has multiple sheets',2);
 8809:  	    next;
 8810:  	}
 8811:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8812:         my $user = $uname.':'.$usec;
 8813:   	($uname,$udom)=split(/:/,$uname);
 8814: 
 8815:         my $scancode;
 8816:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8817:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8818:             $scancode = $scan_record->{'scantron.CODE'};
 8819:         } else {
 8820:             $scancode = '';
 8821:         }
 8822: 
 8823:         my @mapresources = @resources;
 8824:         if ($randomorder || $randompick) {
 8825:             @mapresources =
 8826:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8827:                              \%orderedforcode);
 8828:         }
 8829:         my (%partids_by_symb,$res_error);
 8830:         foreach my $resource (@mapresources) {
 8831:             my $ressymb;
 8832:             if (ref($resource)) {
 8833:                 $ressymb = $resource->symb();
 8834:             } else {
 8835:                 $res_error = 1;
 8836:                 last;
 8837:             }
 8838:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8839:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8840:                 my $currcode;
 8841:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8842:                     $currcode = $scancode;
 8843:                 }
 8844:                 my ($analysis,$parts) =
 8845:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8846:                                               $uname,$udom,undef,$bubbles_per_row,
 8847:                                               $currcode);
 8848:                 $partids_by_symb{$ressymb} = $parts;
 8849:             } else {
 8850:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8851:             }
 8852:         }
 8853: 
 8854:         if ($res_error) {
 8855:             &scantron_add_delay(\@delayqueue,$line,
 8856:                                 'An error occurred while grading student '.$uname,2);
 8857:             next;
 8858:         }
 8859: 
 8860: 	&Apache::lonxml::clear_problem_counter();
 8861:   	&Apache::lonnet::appenv($scan_record);
 8862: 
 8863: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8864: 	    &scantron_putfile($scanlines,$scan_data);
 8865: 	}
 8866: 	
 8867:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8868:                                    \@mapresources,\%partids_by_symb,
 8869:                                    $bubbles_per_row,$randomorder,$randompick,
 8870:                                    \%respnumlookup,\%startline) 
 8871:             eq 'ssi_error') {
 8872:             $ssi_error = 0; # So end of handler error message does not trigger.
 8873:             $r->print("</form>");
 8874:             &ssi_print_error($r);
 8875:             $r->print(&show_grading_menu_form($symb));
 8876:             &Apache::lonnet::remove_lock($lock);
 8877:             return '';      # Why return ''?  Beats me.
 8878:         }
 8879: 
 8880:         if (($scancode) && ($randomorder || $randompick)) {
 8881:             my $parmresult =
 8882:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8883:                                                        '0_examcode',2,$scancode,
 8884:                                                        'string_examcode',$uname,
 8885:                                                        $udom);
 8886:         }
 8887: 	$completedstudents{$uname}={'line'=>$line};
 8888:         if ($env{'form.verifyrecord'}) {
 8889:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8890:             if ($randompick) {
 8891:                 if ($total) {
 8892:                     $lastpos = $total*$scantron_config{'Qlength'};
 8893:                 }
 8894:             }
 8895: 
 8896:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8897:             chomp($studentdata);
 8898:             $studentdata =~ s/\r$//;
 8899:             my $studentrecord = '';
 8900:             my $counter = -1;
 8901:             foreach my $resource (@mapresources) {
 8902:                 my $ressymb = $resource->symb();
 8903:                 ($counter,my $recording) =
 8904:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8905:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8906:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8907:                                              $randompick,\%respnumlookup,\%startline);
 8908:                 $studentrecord .= $recording;
 8909:             }
 8910:             if ($studentrecord ne $studentdata) {
 8911:                 &Apache::lonxml::clear_problem_counter();
 8912:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8913:                                            \@mapresources,\%partids_by_symb,
 8914:                                            $bubbles_per_row,$randomorder,$randompick,
 8915:                                            \%respnumlookup,\%startline)
 8916:                     eq 'ssi_error') {
 8917:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8918:                     $r->print("</form>");
 8919:                     &ssi_print_error($r);
 8920:                     $r->print(&show_grading_menu_form($symb));
 8921:                     &Apache::lonnet::remove_lock($lock);
 8922:                     delete($completedstudents{$uname});
 8923:                     return '';
 8924:                 }
 8925:                 $counter = -1;
 8926:                 $studentrecord = '';
 8927:                 foreach my $resource (@mapresources) {
 8928:                     my $ressymb = $resource->symb();
 8929:                     ($counter,my $recording) =
 8930:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8931:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8932:                                                  \%scantron_config,\%lettdig,$numletts,
 8933:                                                  $randomorder,$randompick,\%respnumlookup,
 8934:                                                  \%startline);
 8935:                     $studentrecord .= $recording;
 8936:                 }
 8937:                 if ($studentrecord ne $studentdata) {
 8938:                     $r->print('<p><span class="LC_warning">');
 8939:                     if ($scancode eq '') {
 8940:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8941:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8942:                     } else {
 8943:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8944:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8945:                     }
 8946:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8947:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8948:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8949:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8950:                               &Apache::loncommon::start_data_table_row().
 8951:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8952:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8953:                               &Apache::loncommon::end_data_table_row().
 8954:                               &Apache::loncommon::start_data_table_row().
 8955:                               '<td>'.&mt('Stored submissions').'</td>'.
 8956:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8957:                               &Apache::loncommon::end_data_table_row().
 8958:                               &Apache::loncommon::end_data_table().'</p>');
 8959:                 } else {
 8960:                     $r->print('<br /><span class="LC_warning">'.
 8961:                              &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 />'.
 8962:                              &mt("As a consequence, this user's submission history records two tries.").
 8963:                                  '</span><br />');
 8964:                 }
 8965:             }
 8966:         }
 8967:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8968:     } continue {
 8969: 	&Apache::lonxml::clear_problem_counter();
 8970: 	&Apache::lonnet::delenv('scantron.');
 8971:     }
 8972:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8973:     &Apache::lonnet::remove_lock($lock);
 8974: #    my $lasttime = &Time::HiRes::time()-$start;
 8975: #    $r->print("<p>took $lasttime</p>");
 8976: 
 8977:     $r->print("</form>");
 8978:     $r->print(&show_grading_menu_form($symb));
 8979:     return '';
 8980: }
 8981: 
 8982: sub graders_resources_pass {
 8983:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8984:         $bubbles_per_row) = @_;
 8985:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8986:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8987:         foreach my $resource (@{$resources}) {
 8988:             my $ressymb = $resource->symb();
 8989:             my ($analysis,$parts) =
 8990:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8991:                                           $env{'user.name'},$env{'user.domain'},
 8992:                                           1,$bubbles_per_row);
 8993:             $grader_partids_by_symb->{$ressymb} = $parts;
 8994:             if (ref($analysis) eq 'HASH') {
 8995:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8996:                     $grader_randomlists_by_symb->{$ressymb} =
 8997:                         $analysis->{'parts_withrandomlist'};
 8998:                 }
 8999:             }
 9000:         }
 9001:     }
 9002:     return;
 9003: }
 9004: 
 9005: =pod
 9006: 
 9007: =item users_order
 9008: 
 9009:   Returns array of resources in current map, ordered based on either CODE,
 9010:   if this is a CODEd exam, or based on student's identity if this is a
 9011:   "NAMEd" exam.
 9012: 
 9013:   Should be used when randomorder and/or randompick applied when the 
 9014:   corresponding exam was printed, prior to students completing bubblesheets 
 9015:   for the version of the exam the student received.
 9016: 
 9017: =cut
 9018: 
 9019: sub users_order  {
 9020:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9021:     my @mapresources;
 9022:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9023:         return @mapresources;
 9024:     }
 9025:     if ($scancode) {
 9026:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9027:             @mapresources = @{$orderedforcode->{$scancode}};
 9028:         } else {
 9029:             $env{'form.CODE'} = $scancode;
 9030:             my $actual_seq =
 9031:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9032:                                                                $master_seq,
 9033:                                                                $user,$scancode,1);
 9034:             if (ref($actual_seq) eq 'ARRAY') {
 9035:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9036:                 if (ref($orderedforcode) eq 'HASH') {
 9037:                     if (@mapresources > 0) {
 9038:                         $orderedforcode->{$scancode} = \@mapresources;
 9039:                     }
 9040:                 }
 9041:             }
 9042:             delete($env{'form.CODE'});
 9043:         }
 9044:     } else {
 9045:         my $actual_seq =
 9046:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9047:                                                            $master_seq,
 9048:                                                            $user,undef,1);
 9049:         if (ref($actual_seq) eq 'ARRAY') {
 9050:             @mapresources =
 9051:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9052:         }
 9053:     }
 9054:     return @mapresources;
 9055: }
 9056: 
 9057: sub grade_student_bubbles {
 9058:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9059:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9060:     my $uselookup = 0;
 9061:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9062:         (ref($startline) eq 'HASH')) {
 9063:         $uselookup = 1;
 9064:     }
 9065: 
 9066:     if (ref($resources) eq 'ARRAY') {
 9067:         my $count = 0;
 9068:         foreach my $resource (@{$resources}) {
 9069:             my $ressymb = $resource->symb();
 9070:             my %form = ('submitted'      => 'scantron',
 9071:                         'grade_target'   => 'grade',
 9072:                         'grade_username' => $uname,
 9073:                         'grade_domain'   => $udom,
 9074:                         'grade_courseid' => $env{'request.course.id'},
 9075:                         'grade_symb'     => $ressymb,
 9076:                         'CODE'           => $scancode
 9077:                        );
 9078:             if ($bubbles_per_row ne '') {
 9079:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9080:             }
 9081:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9082:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9083:             }
 9084:             if (ref($parts) eq 'HASH') {
 9085:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9086:                     foreach my $part (@{$parts->{$ressymb}}) {
 9087:                         if ($uselookup) {
 9088:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9089:                         } else {
 9090:                             $form{'scantron_questnum_start.'.$part} =
 9091:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9092:                         }
 9093:                         $count++;
 9094:                     }
 9095:                 }
 9096:             }
 9097:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9098:             return 'ssi_error' if ($ssi_error);
 9099:             last if (&Apache::loncommon::connection_aborted($r));
 9100:         }
 9101:     }
 9102:     return;
 9103: }
 9104: 
 9105: sub scantron_upload_scantron_data {
 9106:     my ($r)=@_;
 9107:     my $dom = $env{'request.role.domain'};
 9108:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9109:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9110:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9111: 							  'domainid',
 9112: 							  'coursename',$dom);
 9113:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9114:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9115:     my ($symb) = &get_symb($r,1);
 9116:     my $default_form_data=&defaultFormData($symb);
 9117:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9118:     &js_escape(\$nofile_alert);
 9119:     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.");
 9120:     &js_escape(\$nocourseid_alert);
 9121:     $r->print('
 9122: <script type="text/javascript" language="javascript">
 9123:     function checkUpload(formname) {
 9124: 	if (formname.upfile.value == "") {
 9125: 	    alert("'.$nofile_alert.'");
 9126: 	    return false;
 9127: 	}
 9128:         if (formname.courseid.value == "") {
 9129:             alert("'.$nocourseid_alert.'");
 9130:             return false;
 9131:         }
 9132: 	formname.submit();
 9133:     }
 9134: 
 9135:     function ToSyllabus() {
 9136:         var cdom = '."'$dom'".';
 9137:         var cnum = document.rules.courseid.value;
 9138:         if (cdom == "" || cdom == null) {
 9139:             return;
 9140:         }
 9141:         if (cnum == "" || cnum == null) {
 9142:            return;
 9143:         }
 9144:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9145:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9146:         return;
 9147:     }
 9148: 
 9149: </script>
 9150: 
 9151: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9152: 
 9153: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9154: '.$default_form_data.
 9155:   &Apache::lonhtmlcommon::start_pick_box().
 9156:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9157:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9158:   &Apache::lonhtmlcommon::row_closure().
 9159:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9160:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9161:   &Apache::lonhtmlcommon::row_closure().
 9162:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9163:   '<input name="domainid" type="hidden" />'.$domdesc.
 9164:   &Apache::lonhtmlcommon::row_closure().
 9165:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9166:   '<input type="file" name="upfile" size="50" />'.
 9167:   &Apache::lonhtmlcommon::row_closure(1).
 9168:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9169: 
 9170: <input name="command" value="scantronupload_save" type="hidden" />
 9171: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9172: </form>
 9173: ');
 9174:     return '';
 9175: }
 9176: 
 9177: 
 9178: sub scantron_upload_scantron_data_save {
 9179:     my($r)=@_;
 9180:     my ($symb)=&get_symb($r,1);
 9181:     my $doanotherupload=
 9182: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9183: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9184: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9185: 	'</form>'."\n";
 9186:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9187: 	!&Apache::lonnet::allowed('usc',
 9188: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9189: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9190: 	if ($symb) {
 9191: 	    $r->print(&show_grading_menu_form($symb));
 9192: 	} else {
 9193: 	    $r->print($doanotherupload);
 9194: 	}
 9195: 	return '';
 9196:     }
 9197:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9198:     my $uploadedfile;
 9199:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9200:     if (length($env{'form.upfile'}) < 2) {
 9201:         $r->print(
 9202:             &Apache::lonhtmlcommon::confirm_success(
 9203:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9204:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9205:     } else {
 9206:         my $result = 
 9207:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 9208:                                             $env{'form.courseid'},$env{'form.domainid'});
 9209: 	if ($result =~ m{^/uploaded/}) {
 9210:             $r->print(
 9211:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9212:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9213:                         (length($env{'form.upfile'})-1),
 9214:                         '<span class="LC_filename">'.$result.'</span>'));
 9215:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9216:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9217:                                                        $env{'form.courseid'},$uploadedfile));
 9218: 	} else {
 9219:             $r->print(
 9220:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9221:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9222:                           $result,
 9223: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9224: 	}
 9225:     }
 9226:     if ($symb) {
 9227: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 9228:     } else {
 9229: 	$r->print($doanotherupload);
 9230:     }
 9231:     return '';
 9232: }
 9233: 
 9234: sub validate_uploaded_scantron_file {
 9235:     my ($cdom,$cname,$fname) = @_;
 9236:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9237:     my @lines;
 9238:     if ($scanlines ne '-1') {
 9239:         @lines=split("\n",$scanlines,-1);
 9240:     }
 9241:     my $output;
 9242:     if (@lines) {
 9243:         my (%counts,$max_match_format);
 9244:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9245:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9246:         my %idmap = &username_to_idmap($classlist);
 9247:         foreach my $key (keys(%idmap)) {
 9248:             my $lckey = lc($key);
 9249:             $idmap{$lckey} = $idmap{$key};
 9250:         }
 9251:         my %unique_formats;
 9252:         my @formatlines = &get_scantronformat_file();
 9253:         foreach my $line (@formatlines) {
 9254:             chomp($line);
 9255:             my @config = split(/:/,$line);
 9256:             my $idstart = $config[5];
 9257:             my $idlength = $config[6];
 9258:             if (($idstart ne '') && ($idlength > 0)) {
 9259:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9260:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9261:                 } else {
 9262:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9263:                 }
 9264:             }
 9265:         }
 9266:         foreach my $key (keys(%unique_formats)) {
 9267:             my ($idstart,$idlength) = split(':',$key);
 9268:             %{$counts{$key}} = (
 9269:                                'found'   => 0,
 9270:                                'total'   => 0,
 9271:                               );
 9272:             foreach my $line (@lines) {
 9273:                 next if ($line =~ /^#/);
 9274:                 next if ($line =~ /^[\s\cz]*$/);
 9275:                 my $id = substr($line,$idstart-1,$idlength);
 9276:                 $id = lc($id);
 9277:                 if (exists($idmap{$id})) {
 9278:                     $counts{$key}{'found'} ++;
 9279:                 }
 9280:                 $counts{$key}{'total'} ++;
 9281:             }
 9282:             if ($counts{$key}{'total'}) {
 9283:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9284:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9285:                     $max_match_pct = $percent_match;
 9286:                     $max_match_format = $key;
 9287:                     $found_match_count = $counts{$key}{'found'};
 9288:                     $max_match_count = $counts{$key}{'total'};
 9289:                 }
 9290:             }
 9291:         }
 9292:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9293:             my $format_descs;
 9294:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9295:             for (my $i=0; $i<$numwithformat; $i++) {
 9296:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9297:                 if ($i<$numwithformat-2) {
 9298:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9299:                 } elsif ($i==$numwithformat-2) {
 9300:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9301:                 } elsif ($i==$numwithformat-1) {
 9302:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9303:                 }
 9304:             }
 9305:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9306:             $output .= '<br />';
 9307:             if ($found_match_count == $max_match_count) {
 9308:                 # 100% matching entries
 9309:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9310:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9311:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9312:                 &mt('Comparison of student IDs in the uploaded file with'.
 9313:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9314:                     ' in the file (for the format defined for [_3]).',
 9315:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9316:             } else {
 9317:                 # Not all entries matching? -> Show warning and additional info
 9318:                 $output .=
 9319:                     &Apache::lonhtmlcommon::confirm_success(
 9320:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9321:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9322:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9323:                     &mt('Comparison of student IDs in the uploaded file with'.
 9324:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9325:                         ' in the file (for the format defined for [_3]).',
 9326:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9327:                     '<p class="LC_info">'.
 9328:                     &mt('A low percentage of matches results from one of the following:').
 9329:                     '</p><ul>'.
 9330:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9331:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9332:                                '<i>'.$cdom.'</i>').'</li>'.
 9333:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9334:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9335:                     '</ul>';
 9336:             }
 9337:         }
 9338:     } else {
 9339:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9340:     }
 9341:     return $output;
 9342: }
 9343: 
 9344: sub valid_file {
 9345:     my ($requested_file)=@_;
 9346:     foreach my $filename (sort(&scantron_filenames())) {
 9347: 	if ($requested_file eq $filename) { return 1; }
 9348:     }
 9349:     return 0;
 9350: }
 9351: 
 9352: sub scantron_download_scantron_data {
 9353:     my ($r)=@_;
 9354:     my ($symb) = &get_symb($r,1);
 9355:     my $default_form_data=&defaultFormData($symb);
 9356:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9357:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9358:     my $file=$env{'form.scantron_selectfile'};
 9359:     if (! &valid_file($file)) {
 9360: 	$r->print('
 9361: 	<p>
 9362: 	    '.&mt('The requested filename was invalid.').'
 9363:         </p>
 9364: ');
 9365: 	$r->print(&show_grading_menu_form($symb));
 9366: 	return;
 9367:     }
 9368:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9369:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9370:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9371:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9372:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9373:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9374:     $r->print('
 9375:     <p>
 9376: 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
 9377: 	      '<a href="'.$orig.'">','</a>').'
 9378:     </p>
 9379:     <p>
 9380: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9381: 	      '<a href="'.$corrected.'">','</a>').'
 9382:     </p>
 9383:     <p>
 9384: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9385: 	      '<a href="'.$skipped.'">','</a>').'
 9386:     </p>
 9387: ');
 9388:     $r->print(&show_grading_menu_form($symb));
 9389:     return '';
 9390: }
 9391: 
 9392: sub checkscantron_results {
 9393:     my ($r) = @_;
 9394:     my ($symb)=&get_symb($r);
 9395:     if (!$symb) {return '';}
 9396:     my $grading_menu_button=&show_grading_menu_form($symb);
 9397:     my $cid = $env{'request.course.id'};
 9398:     my %lettdig = &letter_to_digits();
 9399:     my $numletts = scalar(keys(%lettdig));
 9400:     my $cnum = $env{'course.'.$cid.'.num'};
 9401:     my $cdom = $env{'course.'.$cid.'.domain'};
 9402:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9403:     my %record;
 9404:     my %scantron_config =
 9405:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9406:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9407:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9408:     my $classlist=&Apache::loncoursedata::get_classlist();
 9409:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9410:     my $navmap=Apache::lonnavmaps::navmap->new();
 9411:     unless (ref($navmap)) {
 9412:         $r->print(&navmap_errormsg());
 9413:         return '';
 9414:     }
 9415:     my $map=$navmap->getResourceByUrl($sequence);
 9416:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9417:         %grader_randomlists_by_symb,%orderedforcode);
 9418:     if (ref($map)) {
 9419:         $randomorder=$map->randomorder();
 9420:         $randompick=$map->randompick();
 9421:     }
 9422:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9423:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9424:     if ($nav_error) {
 9425:         $r->print(&navmap_errormsg());
 9426:         return '';
 9427:     }
 9428:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9429:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9430:     my ($uname,$udom);
 9431:     my (%scandata,%lastname,%bylast);
 9432:     $r->print('
 9433: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9434: 
 9435:     my @delayqueue;
 9436:     my %completedstudents;
 9437: 
 9438:     my $count=&get_todo_count($scanlines,$scan_data);
 9439:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9440:     my ($username,$domain,$started);
 9441:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9442:     if ($nav_error) {
 9443:         $r->print(&navmap_errormsg());
 9444:         return '';
 9445:     }
 9446: 
 9447:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9448:                                           'Processing first student');
 9449:     my $start=&Time::HiRes::time();
 9450:     my $i=-1;
 9451: 
 9452:     while ($i<$scanlines->{'count'}) {
 9453:         ($username,$domain,$uname)=('','','');
 9454:         $i++;
 9455:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9456:         if ($line=~/^[\s\cz]*$/) { next; }
 9457:         if ($started) {
 9458:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9459:                                                      'last student');
 9460:         }
 9461:         $started=1;
 9462:         my $scan_record=
 9463:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9464:                                                      $scan_data);
 9465:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9466:                                               \%idmap,$i)) {
 9467:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9468:                                 'Unable to find a student that matches',1);
 9469:             next;
 9470:         }
 9471:         if (exists $completedstudents{$uname}) {
 9472:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9473:                                 'Student '.$uname.' has multiple sheets',2);
 9474:             next;
 9475:         }
 9476:         my $pid = $scan_record->{'scantron.ID'};
 9477:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9478:         push(@{$bylast{$lastname{$pid}}},$pid);
 9479:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9480:         my $user = $uname.':'.$usec;
 9481:         ($username,$domain)=split(/:/,$uname);
 9482: 
 9483:         my $scancode;
 9484:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9485:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9486:             $scancode = $scan_record->{'scantron.CODE'};
 9487:         } else {
 9488:             $scancode = '';
 9489:         }
 9490: 
 9491:         my @mapresources = @resources;
 9492:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9493:         my %respnumlookup=();
 9494:         my %startline=();
 9495:         if ($randomorder || $randompick) {
 9496:             @mapresources =
 9497:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9498:                              \%orderedforcode);
 9499:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9500:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9501:                                              \%grader_partids_by_symb,\%orderedforcode,
 9502:                                              \%respnumlookup,\%startline);
 9503:             if ($randompick && $total) {
 9504:                 $lastpos = $total*$scantron_config{'Qlength'};
 9505:             }
 9506:         }
 9507:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9508:         chomp($scandata{$pid});
 9509:         $scandata{$pid} =~ s/\r$//;
 9510: 
 9511:         my $counter = -1;
 9512:         foreach my $resource (@mapresources) {
 9513:             my $parts;
 9514:             my $ressymb = $resource->symb();
 9515:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9516:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9517:                 my $currcode;
 9518:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9519:                     $currcode = $scancode;
 9520:                 }
 9521:                 (my $analysis,$parts) =
 9522:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9523:                                               $username,$domain,undef,
 9524:                                               $bubbles_per_row,$currcode);
 9525:             } else {
 9526:                 $parts = $grader_partids_by_symb{$ressymb};
 9527:             }
 9528:             ($counter,my $recording) =
 9529:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9530:                                          $scandata{$pid},$parts,
 9531:                                          \%scantron_config,\%lettdig,$numletts,
 9532:                                          $randomorder,$randompick,
 9533:                                          \%respnumlookup,\%startline);
 9534:             $record{$pid} .= $recording;
 9535:         }
 9536:     }
 9537:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9538:     $r->print('<br />');
 9539:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9540:     $passed = 0;
 9541:     $failed = 0;
 9542:     $numstudents = 0;
 9543:     foreach my $last (sort(keys(%bylast))) {
 9544:         if (ref($bylast{$last}) eq 'ARRAY') {
 9545:             foreach my $pid (sort(@{$bylast{$last}})) {
 9546:                 my $showscandata = $scandata{$pid};
 9547:                 my $showrecord = $record{$pid};
 9548:                 $showscandata =~ s/\s/&nbsp;/g;
 9549:                 $showrecord =~ s/\s/&nbsp;/g;
 9550:                 if ($scandata{$pid} eq $record{$pid}) {
 9551:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9552:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9553: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9554: '</tr>'."\n".
 9555: '<tr class="'.$css_class.'">'."\n".
 9556: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9557:                     $passed ++;
 9558:                 } else {
 9559:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9560:                     $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".
 9561: '</tr>'."\n".
 9562: '<tr class="'.$css_class.'">'."\n".
 9563: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9564: '</tr>'."\n";
 9565:                     $failed ++;
 9566:                 }
 9567:                 $numstudents ++;
 9568:             }
 9569:         }
 9570:     }
 9571:     $r->print('<p>'.
 9572:               &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).',
 9573:                   '<b>',
 9574:                   $numstudents,
 9575:                   '</b>',
 9576:                   $env{'form.scantron_maxbubble'}).
 9577:               '</p>'
 9578:     );
 9579:     $r->print('<p>'
 9580:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9581:              .'<br />'
 9582:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9583:              .'</p>');
 9584:     if ($passed) {
 9585:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9586:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9587:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9588:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9589:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9590:                  $okstudents."\n".
 9591:                  &Apache::loncommon::end_data_table().'<br />');
 9592:     }
 9593:     if ($failed) {
 9594:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9595:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9596:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9597:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9598:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9599:                  $badstudents."\n".
 9600:                  &Apache::loncommon::end_data_table()).'<br />'.
 9601:                  &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.');  
 9602:     }
 9603:     $r->print('</form><br />'.$grading_menu_button);
 9604:     return;
 9605: }
 9606: 
 9607: sub verify_scantron_grading {
 9608:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9609:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9610:         $respnumlookup,$startline) = @_;
 9611:     my ($record,%expected,%startpos);
 9612:     return ($counter,$record) if (!ref($resource));
 9613:     return ($counter,$record) if (!$resource->is_problem());
 9614:     my $symb = $resource->symb();
 9615:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9616:     foreach my $part_id (@{$partids}) {
 9617:         $counter ++;
 9618:         $expected{$part_id} = 0;
 9619:         my $respnum = $counter;
 9620:         if ($randomorder || $randompick) {
 9621:             $respnum = $respnumlookup->{$counter};
 9622:             $startpos{$part_id} = $startline->{$counter} + 1;
 9623:         } else {
 9624:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9625:         }
 9626:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9627:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9628:             foreach my $item (@sub_lines) {
 9629:                 $expected{$part_id} += $item;
 9630:             }
 9631:         } else {
 9632:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9633:         }
 9634:     }
 9635:     if ($symb) {
 9636:         my %recorded;
 9637:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9638:         if ($returnhash{'version'}) {
 9639:             my %lasthash=();
 9640:             my $version;
 9641:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9642:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9643:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9644:                 }
 9645:             }
 9646:             foreach my $key (keys(%lasthash)) {
 9647:                 if ($key =~ /\.scantron$/) {
 9648:                     my $value = &unescape($lasthash{$key});
 9649:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9650:                     if ($value eq '') {
 9651:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9652:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9653:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9654:                             }
 9655:                         }
 9656:                     } else {
 9657:                         my @tocheck;
 9658:                         my @items = split(//,$value);
 9659:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9660:                             ($scantron_config->{'Qon'} eq 'number')) {
 9661:                             if (@items < $expected{$part_id}) {
 9662:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9663:                                 my @singles = split(//,$fragment);
 9664:                                 foreach my $pos (@singles) {
 9665:                                     if ($pos eq ' ') {
 9666:                                         push(@tocheck,$pos);
 9667:                                     } else {
 9668:                                         my $next = shift(@items);
 9669:                                         push(@tocheck,$next);
 9670:                                     }
 9671:                                 }
 9672:                             } else {
 9673:                                 @tocheck = @items;
 9674:                             }
 9675:                             foreach my $letter (@tocheck) {
 9676:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9677:                                     if ($letter !~ /^[A-J]$/) {
 9678:                                         $letter = $scantron_config->{'Qoff'};
 9679:                                     }
 9680:                                     $recorded{$part_id} .= $letter;
 9681:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9682:                                     my $digit;
 9683:                                     if ($letter !~ /^[A-J]$/) {
 9684:                                         $digit = $scantron_config->{'Qoff'};
 9685:                                     } else {
 9686:                                         $digit = $lettdig->{$letter};
 9687:                                     }
 9688:                                     $recorded{$part_id} .= $digit;
 9689:                                 }
 9690:                             }
 9691:                         } else {
 9692:                             @tocheck = @items;
 9693:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9694:                                 my $curr_sub = shift(@tocheck);
 9695:                                 my $digit;
 9696:                                 if ($curr_sub =~ /^[A-J]$/) {
 9697:                                     $digit = $lettdig->{$curr_sub}-1;
 9698:                                 }
 9699:                                 if ($curr_sub eq 'J') {
 9700:                                     $digit += scalar($numletts);
 9701:                                 }
 9702:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9703:                                     if ($j == $digit) {
 9704:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9705:                                     } else {
 9706:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9707:                                     }
 9708:                                 }
 9709:                             }
 9710:                         }
 9711:                     }
 9712:                 }
 9713:             }
 9714:         }
 9715:         foreach my $part_id (@{$partids}) {
 9716:             if ($recorded{$part_id} eq '') {
 9717:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9718:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9719:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9720:                     }
 9721:                 }
 9722:             }
 9723:             $record .= $recorded{$part_id};
 9724:         }
 9725:     }
 9726:     return ($counter,$record);
 9727: }
 9728: 
 9729: sub letter_to_digits {
 9730:     my %lettdig = (
 9731:                     A => 1,
 9732:                     B => 2,
 9733:                     C => 3,
 9734:                     D => 4,
 9735:                     E => 5,
 9736:                     F => 6,
 9737:                     G => 7,
 9738:                     H => 8,
 9739:                     I => 9,
 9740:                     J => 0,
 9741:                   );
 9742:     return %lettdig;
 9743: }
 9744: 
 9745: 
 9746: #-------- end of section for handling grading scantron forms -------
 9747: #
 9748: #-------------------------------------------------------------------
 9749: 
 9750: #-------------------------- Menu interface -------------------------
 9751: #
 9752: #--- Show a Grading Menu button - Calls the next routine ---
 9753: sub show_grading_menu_form {
 9754:     my ($symb)=@_;
 9755:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9756: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9757: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9758: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9759: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9760: 	'</form>'."\n";
 9761:     return $result;
 9762: }
 9763: 
 9764: # -- Retrieve choices for grading form
 9765: sub savedState {
 9766:     my %savedState = ();
 9767:     if ($env{'form.saveState'}) {
 9768: 	foreach (split(/:/,$env{'form.saveState'})) {
 9769: 	    my ($key,$value) = split(/=/,$_,2);
 9770: 	    $savedState{$key} = $value;
 9771: 	}
 9772:     }
 9773:     return \%savedState;
 9774: }
 9775: 
 9776: #--- Href with symb and command ---
 9777: 
 9778: sub href_symb_cmd {
 9779:     my ($symb,$cmd)=@_;
 9780:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9781: }
 9782: 
 9783: sub grading_menu {
 9784:     my ($request) = @_;
 9785:     my ($symb)=&get_symb($request);
 9786:     if (!$symb) {return '';}
 9787:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9788:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9789: 
 9790:     $request->print($table);
 9791:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9792:                   'handgrade'=>$hdgrade,
 9793:                   'probTitle'=>$probTitle,
 9794:                   'command'=>'submit_options',
 9795:                   'saveState'=>"",
 9796:                   'gradingMenu'=>1,
 9797:                   'showgrading'=>"yes");
 9798:     
 9799:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9800:     
 9801:     $fields{'command'} = 'csvform';
 9802:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9803:     
 9804:     $fields{'command'} = 'processclicker';
 9805:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9806:     
 9807:     $fields{'command'} = 'scantron_selectphase';
 9808:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9809:     
 9810:     my @menu = ({	categorytitle=>'Course Grading',
 9811:             items =>[
 9812:                         {	linktext => 'Manual Grading/View Submissions',
 9813:                     		url => $url1,
 9814:                     		permission => 'F',
 9815:                     		icon => 'edit-find-replace.png',
 9816:                     		linktitle => 'Start the process of hand grading submissions.'
 9817:                         },
 9818:                 	    {	linktext => 'Upload Scores',
 9819:                     		url => $url2,
 9820:                     		permission => 'F',
 9821:                     		icon => 'uploadscores.png',
 9822:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9823:                 	    },
 9824:                 	    {	linktext => 'Process Clicker',
 9825:                     		url => $url3,
 9826:                     		permission => 'F',
 9827:                     		icon => 'addClickerInfoFile.png',
 9828:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9829:                 	    },
 9830:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9831:                     		url => $url4,
 9832:                     		permission => 'F',
 9833:                     		icon => 'stat.png',
 9834:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9835:                 	    }
 9836:                     ]
 9837:             });
 9838: 
 9839:     #$fields{'command'} = 'verify';
 9840:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9841:     #
 9842:     # Create the menu
 9843:     my $Str;
 9844:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9845:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9846:     $Str .= '<input type="hidden" name="command" value="" />'.
 9847:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9848: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9849: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9850: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9851: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9852: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9853: 
 9854:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9855:     #$menudata->{'jscript'}
 9856:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9857:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9858:         ' /> '.
 9859:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9860:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9861: 
 9862:     $Str .="</form>\n";
 9863:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9864:     $request->print(<<GRADINGMENUJS);
 9865: <script type="text/javascript" language="javascript">
 9866:     function checkChoice(formname,val,cmdx) {
 9867: 	if (val <= 2) {
 9868: 	    var cmd = radioSelection(formname.radioChoice);
 9869: 	    var cmdsave = cmd;
 9870: 	} else {
 9871: 	    cmd = cmdx;
 9872: 	    cmdsave = 'submission';
 9873: 	}
 9874: 	formname.command.value = cmd;
 9875: 	if (val < 5) formname.submit();
 9876: 	if (val == 5) {
 9877: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9878: 	        return false;
 9879: 	    } else {
 9880: 	        formname.submit();
 9881: 	    }
 9882: 	}
 9883:     }
 9884: 
 9885:     function checkReceiptNo(formname,nospace) {
 9886: 	var receiptNo = formname.receipt.value;
 9887: 	var checkOpt = false;
 9888: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9889: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9890: 	if (checkOpt) {
 9891: 	    alert("$receiptalert");
 9892: 	    formname.receipt.value = "";
 9893: 	    formname.receipt.focus();
 9894: 	    return false;
 9895: 	}
 9896: 	return true;
 9897:     }
 9898: </script>
 9899: GRADINGMENUJS
 9900:     &commonJSfunctions($request);
 9901:     return $Str;    
 9902: }
 9903: 
 9904: 
 9905: #--- Displays the submissions first page -------
 9906: sub submit_options {
 9907:     my ($request) = @_;
 9908:     my ($symb)=&get_symb($request);
 9909:     if (!$symb) {return '';}
 9910:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9911: 
 9912:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9913:     $request->print(<<GRADINGMENUJS);
 9914: <script type="text/javascript" language="javascript">
 9915:     function checkChoice(formname,val,cmdx) {
 9916: 	if (val <= 2) {
 9917: 	    var cmd = radioSelection(formname.radioChoice);
 9918: 	    var cmdsave = cmd;
 9919: 	} else {
 9920: 	    cmd = cmdx;
 9921: 	    cmdsave = 'submission';
 9922: 	}
 9923: 	formname.command.value = cmd;
 9924: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9925: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9926: 	if (val < 5) formname.submit();
 9927: 	if (val == 5) {
 9928: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9929: 	    formname.submit();
 9930: 	}
 9931: 	if (val < 7) formname.submit();
 9932:     }
 9933: 
 9934:     function checkReceiptNo(formname,nospace) {
 9935: 	var receiptNo = formname.receipt.value;
 9936: 	var checkOpt = false;
 9937: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9938: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9939: 	if (checkOpt) {
 9940: 	    alert("$receiptalert");
 9941: 	    formname.receipt.value = "";
 9942: 	    formname.receipt.focus();
 9943: 	    return false;
 9944: 	}
 9945: 	return true;
 9946:     }
 9947: </script>
 9948: GRADINGMENUJS
 9949:     &commonJSfunctions($request);
 9950:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9951:     my $result;
 9952:     my (undef,$sections) = &getclasslist('all','0');
 9953:     my $savedState = &savedState();
 9954:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9955:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9956:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9957:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9958: 
 9959:     # Preselect sections
 9960:     my $selsec="";
 9961:     if (ref($sections)) {
 9962:         foreach my $section (sort(@$sections)) {
 9963:             $selsec.='<option value="'.$section.'" '.
 9964:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9965:         }
 9966:     }
 9967: 
 9968:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9969: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9970: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9971: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9972: 	'<input type="hidden" name="command"     value="" />'."\n".
 9973: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9974: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9975: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9976: 
 9977:     $result.='
 9978: <h2>
 9979:   '.&mt('Grade Current Resource').'
 9980: </h2>
 9981: <div>
 9982:   '.$table.'
 9983: </div>
 9984: 
 9985: <div class="LC_columnSection">
 9986:   
 9987:     <fieldset>
 9988:       <legend>
 9989:        '.&mt('Sections').'
 9990:       </legend>
 9991:       <select name="section" multiple="multiple" size="5">'."\n";
 9992:     $result.= $selsec;
 9993:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9994:     $result.='
 9995:     </fieldset>
 9996:   
 9997:     <fieldset>
 9998:       <legend>
 9999:         '.&mt('Groups').'
10000:       </legend>
10001:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10002:     </fieldset>
10003:   
10004:     <fieldset>
10005:       <legend>
10006:         '.&mt('Access Status').'
10007:       </legend>
10008:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
10009:     </fieldset>
10010:   
10011:     <fieldset>
10012:       <legend>
10013:         '.&mt('Submission Status').'
10014:       </legend>
10015:       <select name="submitonly" size="5">
10016: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
10017: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
10018: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
10019: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
10020:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
10021:       </select>
10022:     </fieldset>
10023:   
10024: </div>
10025: 
10026: <br />
10027:           <div>
10028:             <div>
10029:               <label>
10030:                 <input type="radio" name="radioChoice" value="submission" '.
10031:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
10032:              &mt('Select individual students to grade and view submissions.').'
10033: 	      </label> 
10034:             </div>
10035:             <div>
10036: 	      <label>
10037:                 <input type="radio" name="radioChoice" value="viewgrades" '.
10038:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
10039:                     &mt('Grade all selected students in a grading table.').'
10040:               </label>
10041:             </div>
10042:             <div>
10043: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
10044:             </div>
10045:           </div>
10046: 
10047: 
10048:         <h2>
10049:          '.&mt('Grade Complete Folder for One Student').'
10050:         </h2>
10051:         <div>
10052:             <div>
10053:               <label>
10054:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
10055: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
10056:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
10057:               </label>
10058:             </div>
10059:             <div>
10060: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
10061:             </div>
10062:         </div>
10063:   </form>';
10064:     $result .= &show_grading_menu_form($symb);
10065:     return $result;
10066: }
10067: 
10068: sub substatus_options {
10069:     return &Apache::lonlocal::texthash(
10070:                                       'yes'       => 'with submissions',
10071:                                       'queued'    => 'in grading queue',
10072:                                       'graded'    => 'with ungraded submissions',
10073:                                       'incorrect' => 'with incorrect submissions',
10074:                                       'all'       => 'with any status',
10075:                                       );
10076: }
10077: 
10078: sub reset_perm {
10079:     undef(%perm);
10080: }
10081: 
10082: sub init_perm {
10083:     &reset_perm();
10084:     foreach my $test_perm ('vgr','mgr','opa') {
10085: 
10086: 	my $scope = $env{'request.course.id'};
10087: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10088: 
10089: 	    $scope .= '/'.$env{'request.course.sec'};
10090: 	    if ( $perm{$test_perm}=
10091: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10092: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10093: 	    } else {
10094: 		delete($perm{$test_perm});
10095: 	    }
10096: 	}
10097:     }
10098: }
10099: 
10100: sub init_old_essays {
10101:     my ($symb,$apath,$adom,$aname) = @_;
10102:     if ($symb ne '') {
10103:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10104:         if (keys(%essays) > 0) {
10105:             $old_essays{$symb} = \%essays;
10106:         }
10107:     }
10108:     return;
10109: }
10110: 
10111: sub reset_old_essays {
10112:     undef(%old_essays);
10113: }
10114: 
10115: sub gather_clicker_ids {
10116:     my %clicker_ids;
10117: 
10118:     my $classlist = &Apache::loncoursedata::get_classlist();
10119: 
10120:     # Set up a couple variables.
10121:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10122:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10123:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10124: 
10125:     foreach my $student (keys(%$classlist)) {
10126:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10127:         my $username = $classlist->{$student}->[$username_idx];
10128:         my $domain   = $classlist->{$student}->[$domain_idx];
10129:         my $clickers =
10130: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10131:         foreach my $id (split(/\,/,$clickers)) {
10132:             $id=~s/^[\#0]+//;
10133:             $id=~s/[\-\:]//g;
10134:             if (exists($clicker_ids{$id})) {
10135: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10136:             } else {
10137: 		$clicker_ids{$id}=$username.':'.$domain;
10138:             }
10139:         }
10140:     }
10141:     return %clicker_ids;
10142: }
10143: 
10144: sub gather_adv_clicker_ids {
10145:     my %clicker_ids;
10146:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10147:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10148:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10149:     foreach my $element (sort(keys(%coursepersonnel))) {
10150:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10151:             my ($puname,$pudom)=split(/\:/,$person);
10152:             my $clickers =
10153: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10154:             foreach my $id (split(/\,/,$clickers)) {
10155: 		$id=~s/^[\#0]+//;
10156:                 $id=~s/[\-\:]//g;
10157: 		if (exists($clicker_ids{$id})) {
10158: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10159: 		} else {
10160: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10161: 		}
10162:             }
10163:         }
10164:     }
10165:     return %clicker_ids;
10166: }
10167: 
10168: sub clicker_grading_parameters {
10169:     return ('gradingmechanism' => 'scalar',
10170:             'upfiletype' => 'scalar',
10171:             'specificid' => 'scalar',
10172:             'pcorrect' => 'scalar',
10173:             'pincorrect' => 'scalar');
10174: }
10175: 
10176: sub process_clicker {
10177:     my ($r)=@_;
10178:     my ($symb)=&get_symb($r);
10179:     if (!$symb) {return '';}
10180:     my $result=&checkforfile_js();
10181:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
10182:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
10183:     $result.=$table;
10184:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
10185:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
10186:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
10187:         '</b></td></tr>'."\n";
10188:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
10189: # Attempt to restore parameters from last session, set defaults if not present
10190:     my %Saveable_Parameters=&clicker_grading_parameters();
10191:     &Apache::loncommon::restore_course_settings('grades_clicker',
10192:                                                  \%Saveable_Parameters);
10193:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10194:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10195:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10196:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10197: 
10198:     my %checked;
10199:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10200:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10201:           $checked{$gradingmechanism}=' checked="checked"';
10202:        }
10203:     }
10204: 
10205:     my $upload=&mt("Upload File");
10206:     my $type=&mt("Type");
10207:     my $attendance=&mt("Award points just for participation");
10208:     my $personnel=&mt("Correctness determined from response by course personnel");
10209:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10210:     my $given=&mt("Correctness determined from given list of answers").' '.
10211:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10212:     my $pcorrect=&mt("Percentage points for correct solution");
10213:     my $pincorrect=&mt("Percentage points for incorrect solution");
10214:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10215:                                                    {'iclicker' => 'i>clicker',
10216:                                                     'interwrite' => 'interwrite PRS',
10217:                                                     'turning' => 'Turning Technologies'});
10218:     $symb = &Apache::lonenc::check_encrypt($symb);
10219:     $result.=<<ENDUPFORM;
10220: <script type="text/javascript">
10221: function sanitycheck() {
10222: // Accept only integer percentages
10223:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10224:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10225: // Find out grading choice
10226:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10227:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10228:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10229:       }
10230:    }
10231: // By default, new choice equals user selection
10232:    newgradingchoice=gradingchoice;
10233: // Not good to give more points for false answers than correct ones
10234:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10235:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10236:    }
10237: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10238:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10239:       document.forms.gradesupload.pcorrect.value=100;
10240:       document.forms.gradesupload.pincorrect.value=100;
10241:    }
10242: // If the values are different, cannot be attendance only
10243:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10244:        (gradingchoice=='attendance')) {
10245:        newgradingchoice='personnel';
10246:    }
10247: // Change grading choice to new one
10248:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10249:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10250:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10251:       } else {
10252:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10253:       }
10254:    }
10255: // Remember the old state
10256:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10257: }
10258: </script>
10259: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10260: <input type="hidden" name="symb" value="$symb" />
10261: <input type="hidden" name="command" value="processclickerfile" />
10262: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10263: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10264: <input type="file" name="upfile" size="50" />
10265: <br /><label>$type: $selectform</label>
10266: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10267: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10268: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10269: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10270: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10271: <br />&nbsp;&nbsp;&nbsp;
10272: <input type="text" name="givenanswer" size="50" />
10273: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10274: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10275: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10276: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10277: </form>
10278: ENDUPFORM
10279:     $result.='</td></tr></table>'."\n".
10280:              '</td></tr></table><br /><br />'."\n";
10281:     $result.=&show_grading_menu_form($symb);
10282:     return $result;
10283: }
10284: 
10285: sub process_clicker_file {
10286:     my ($r)=@_;
10287:     my ($symb)=&get_symb($r);
10288:     if (!$symb) {return '';}
10289: 
10290:     my %Saveable_Parameters=&clicker_grading_parameters();
10291:     &Apache::loncommon::store_course_settings('grades_clicker',
10292:                                               \%Saveable_Parameters);
10293: 
10294:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10295:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10296: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10297: 	return $result.&show_grading_menu_form($symb);
10298:     }
10299:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10300:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10301:         return $result.&show_grading_menu_form($symb);
10302:     }
10303:     my $foundgiven=0;
10304:     if ($env{'form.gradingmechanism'} eq 'given') {
10305:         $env{'form.givenanswer'}=~s/^\s*//gs;
10306:         $env{'form.givenanswer'}=~s/\s*$//gs;
10307:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10308:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10309:         my @answers=split(/\,/,$env{'form.givenanswer'});
10310:         $foundgiven=$#answers+1;
10311:     }
10312:     my %clicker_ids=&gather_clicker_ids();
10313:     my %correct_ids;
10314:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10315: 	%correct_ids=&gather_adv_clicker_ids();
10316:     }
10317:     if ($env{'form.gradingmechanism'} eq 'specific') {
10318: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10319: 	   $correct_id=~tr/a-z/A-Z/;
10320: 	   $correct_id=~s/\s//gs;
10321: 	   $correct_id=~s/^[\#0]+//;
10322:            $correct_id=~s/[\-\:]//g;
10323:            if ($correct_id) {
10324: 	      $correct_ids{$correct_id}='specified';
10325:            }
10326:         }
10327:     }
10328:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10329: 	$result.=&mt('Score based on attendance only');
10330:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10331:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10332:     } else {
10333: 	my $number=0;
10334: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10335: 	foreach my $id (sort(keys(%correct_ids))) {
10336: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10337: 	    if ($correct_ids{$id} eq 'specified') {
10338: 		$result.=&mt('specified');
10339: 	    } else {
10340: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10341: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10342: 	    }
10343: 	    $number++;
10344: 	}
10345:         $result.="</p>\n";
10346:         if ($number==0) {
10347:             $result .=
10348:                  &Apache::lonhtmlcommon::confirm_success(
10349:                      &mt('No IDs found to determine correct answer'),1);
10350:             return $result,.&show_grading_menu_form($symb);
10351:         }
10352:     }
10353:     if (length($env{'form.upfile'}) < 2) {
10354:         $result .=
10355:             &Apache::lonhtmlcommon::confirm_success(
10356:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10357:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10358:         return $result.&show_grading_menu_form($symb);
10359:     }
10360: 
10361: # Were able to get all the info needed, now analyze the file
10362: 
10363:     $result.=&Apache::loncommon::studentbrowser_javascript();
10364:     $symb = &Apache::lonenc::check_encrypt($symb);
10365:     my $heading=&mt('Scanning clicker file');
10366:     $result.=(<<ENDHEADER);
10367: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
10368: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
10369: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
10370: <form method="post" action="/adm/grades" name="clickeranalysis">
10371: <input type="hidden" name="symb" value="$symb" />
10372: <input type="hidden" name="command" value="assignclickergrades" />
10373: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10374: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10375: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10376: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10377: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10378: ENDHEADER
10379:     if ($env{'form.gradingmechanism'} eq 'given') {
10380:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10381:     } 
10382:     my %responses;
10383:     my @questiontitles;
10384:     my $errormsg='';
10385:     my $number=0;
10386:     if ($env{'form.upfiletype'} eq 'iclicker') {
10387: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10388:     }
10389:     if ($env{'form.upfiletype'} eq 'interwrite') {
10390:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10391:     }
10392:     if ($env{'form.upfiletype'} eq 'turning') {
10393:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10394:     }
10395:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10396:              '<input type="hidden" name="number" value="'.$number.'" />'.
10397:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10398:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10399:              '<br />';
10400:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10401:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10402:        return $result.&show_grading_menu_form($symb);
10403:     } 
10404: # Remember Question Titles
10405: # FIXME: Possibly need delimiter other than ":"
10406:     for (my $i=0;$i<$number;$i++) {
10407:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10408:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10409:     }
10410:     my $correct_count=0;
10411:     my $student_count=0;
10412:     my $unknown_count=0;
10413: # Match answers with usernames
10414: # FIXME: Possibly need delimiter other than ":"
10415:     foreach my $id (keys(%responses)) {
10416:        if ($correct_ids{$id}) {
10417:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10418:           $correct_count++;
10419:        } elsif ($clicker_ids{$id}) {
10420:           if ($clicker_ids{$id}=~/\,/) {
10421: # More than one user with the same clicker!
10422:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10423:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10424:                            "<select name='multi".$id."'>";
10425:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10426:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10427:              }
10428:              $result.='</select>';
10429:              $unknown_count++;
10430:           } else {
10431: # Good: found one and only one user with the right clicker
10432:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10433:              $student_count++;
10434:           }
10435:        } else {
10436:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10437:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10438:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10439:                    "\n".&mt("Domain").": ".
10440:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10441:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10442:           $unknown_count++;
10443:        }
10444:     }
10445:     $result.='<hr />'.
10446:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10447:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10448:        if ($correct_count==0) {
10449:           $errormsg.="Found no correct answers for grading!";
10450:        } elsif ($correct_count>1) {
10451:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10452:        }
10453:     }
10454:     if ($number<1) {
10455:        $errormsg.="Found no questions.";
10456:     }
10457:     if ($errormsg) {
10458:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10459:     } else {
10460:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10461:     }
10462:     $result.='</form></td></tr></table>'."\n".
10463:              '</td></tr></table><br /><br />'."\n";
10464:     return $result.&show_grading_menu_form($symb);
10465: }
10466: 
10467: sub iclicker_eval {
10468:     my ($questiontitles,$responses)=@_;
10469:     my $number=0;
10470:     my $errormsg='';
10471:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10472:         my %components=&Apache::loncommon::record_sep($line);
10473:         my @entries=map {$components{$_}} (sort(keys(%components)));
10474: 	if ($entries[0] eq 'Question') {
10475: 	    for (my $i=3;$i<$#entries;$i+=6) {
10476: 		$$questiontitles[$number]=$entries[$i];
10477: 		$number++;
10478: 	    }
10479: 	}
10480: 	if ($entries[0]=~/^\#/) {
10481: 	    my $id=$entries[0];
10482: 	    my @idresponses;
10483: 	    $id=~s/^[\#0]+//;
10484: 	    for (my $i=0;$i<$number;$i++) {
10485: 		my $idx=3+$i*6;
10486:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10487: 		push(@idresponses,$entries[$idx]);
10488: 	    }
10489: 	    $$responses{$id}=join(',',@idresponses);
10490: 	}
10491:     }
10492:     return ($errormsg,$number);
10493: }
10494: 
10495: sub interwrite_eval {
10496:     my ($questiontitles,$responses)=@_;
10497:     my $number=0;
10498:     my $errormsg='';
10499:     my $skipline=1;
10500:     my $questionnumber=0;
10501:     my %idresponses=();
10502:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10503:         my %components=&Apache::loncommon::record_sep($line);
10504:         my @entries=map {$components{$_}} (sort(keys(%components)));
10505:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10506:         if ($entries[1] eq 'Response') { $skipline=1; }
10507:         next if $skipline;
10508:         if ($entries[0]!=$questionnumber) {
10509:            $questionnumber=$entries[0];
10510:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10511:            $number++;
10512:         }
10513:         my $id=$entries[4];
10514:         $id=~s/^[\#0]+//;
10515:         $id=~s/^v\d*\://i;
10516:         $id=~s/[\-\:]//g;
10517:         $idresponses{$id}[$number]=$entries[6];
10518:     }
10519:     foreach my $id (keys(%idresponses)) {
10520:        $$responses{$id}=join(',',@{$idresponses{$id}});
10521:        $$responses{$id}=~s/^\s*\,//;
10522:     }
10523:     return ($errormsg,$number);
10524: }
10525: 
10526: sub turning_eval {
10527:     my ($questiontitles,$responses)=@_;
10528:     my $number=0;
10529:     my $errormsg='';
10530:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10531:         my %components=&Apache::loncommon::record_sep($line);
10532:         my @entries=map {$components{$_}} (sort(keys(%components)));
10533:         if ($#entries>$number) { $number=$#entries; }
10534:         my $id=$entries[0];
10535:         my @idresponses;
10536:         $id=~s/^[\#0]+//;
10537:         unless ($id) { next; }
10538:         for (my $idx=1;$idx<=$#entries;$idx++) {
10539:             $entries[$idx]=~s/\,/\;/g;
10540:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10541:             push(@idresponses,$entries[$idx]);
10542:         }
10543:         $$responses{$id}=join(',',@idresponses);
10544:     }
10545:     for (my $i=1; $i<=$number; $i++) {
10546:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10547:     }
10548:     return ($errormsg,$number);
10549: }
10550: 
10551: sub assign_clicker_grades {
10552:     my ($r)=@_;
10553:     my ($symb)=&get_symb($r);
10554:     if (!$symb) {return '';}
10555: # See which part we are saving to
10556:     my $res_error;
10557:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10558:     if ($res_error) {
10559:         return &navmap_errormsg();
10560:     }
10561: # FIXME: This should probably look for the first handgradeable part
10562:     my $part=$$partlist[0];
10563: # Start screen output
10564:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10565: 
10566:     $result .= '<br />'.
10567:                &Apache::loncommon::start_data_table().
10568:                &Apache::loncommon::start_data_table_header_row().
10569:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10570:                &Apache::loncommon::end_data_table_header_row().
10571:                &Apache::loncommon::start_data_table_row().'<td>';
10572: 
10573: # Get correct result
10574: # FIXME: Possibly need delimiter other than ":"
10575:     my @correct=();
10576:     my $gradingmechanism=$env{'form.gradingmechanism'};
10577:     my $number=$env{'form.number'};
10578:     if ($gradingmechanism ne 'attendance') {
10579:        foreach my $key (keys(%env)) {
10580:           if ($key=~/^form\.correct\:/) {
10581:              my @input=split(/\,/,$env{$key});
10582:              for (my $i=0;$i<=$#input;$i++) {
10583:                  if (($correct[$i]) && ($input[$i]) &&
10584:                      ($correct[$i] ne $input[$i])) {
10585:                     $result.='<br /><span class="LC_warning">'.
10586:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10587:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10588:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10589:                     $correct[$i]=$input[$i];
10590:                  }
10591:              }
10592:           }
10593:        }
10594:        for (my $i=0;$i<$number;$i++) {
10595:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10596:              $result.='<br /><span class="LC_error">'.
10597:                       &mt('No correct result given for question "[_1]"!',
10598:                           $env{'form.question:'.$i}).'</span>';
10599:           }
10600:        }
10601:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10602:     }
10603: # Start grading
10604:     my $pcorrect=$env{'form.pcorrect'};
10605:     my $pincorrect=$env{'form.pincorrect'};
10606:     my $storecount=0;
10607:     my %users=();
10608:     foreach my $key (keys(%env)) {
10609:        my $user='';
10610:        if ($key=~/^form\.student\:(.*)$/) {
10611:           $user=$1;
10612:        }
10613:        if ($key=~/^form\.unknown\:(.*)$/) {
10614:           my $id=$1;
10615:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10616:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10617:           } elsif ($env{'form.multi'.$id}) {
10618:              $user=$env{'form.multi'.$id};
10619:           }
10620:        }
10621:        if ($user) {
10622:           if ($users{$user}) {
10623:              $result.='<br /><span class="LC_warning">'.
10624:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10625:                       '</span><br />';
10626:           }
10627:           $users{$user}=1;
10628:           my @answer=split(/\,/,$env{$key});
10629:           my $sum=0;
10630:           my $realnumber=$number;
10631:           for (my $i=0;$i<$number;$i++) {
10632:              if  ($correct[$i] eq '-') {
10633:                 $realnumber--;
10634:              } elsif ($answer[$i]) {
10635:                 if ($gradingmechanism eq 'attendance') {
10636:                    $sum+=$pcorrect;
10637:                 } elsif ($correct[$i] eq '*') {
10638:                    $sum+=$pcorrect;
10639:                 } else {
10640: # We actually grade if correct or not
10641:                    my $increment=$pincorrect;
10642: # Special case: numerical answer "0"
10643:                    if ($correct[$i] eq '0') {
10644:                       if ($answer[$i]=~/^[0\.]+$/) {
10645:                          $increment=$pcorrect;
10646:                       }
10647: # General numerical answer, both evaluate to something non-zero
10648:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10649:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10650:                          $increment=$pcorrect;
10651:                       }
10652: # Must be just alphanumeric
10653:                    } elsif ($answer[$i] eq $correct[$i]) {
10654:                       $increment=$pcorrect;
10655:                    }
10656:                    $sum+=$increment;
10657:                 }
10658:              }
10659:           }
10660:           my $ave=$sum/(100*$realnumber);
10661: # Store
10662:           my ($username,$domain)=split(/\:/,$user);
10663:           my %grades=();
10664:           $grades{"resource.$part.solved"}='correct_by_override';
10665:           $grades{"resource.$part.awarded"}=$ave;
10666:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10667:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10668:                                                  $env{'request.course.id'},
10669:                                                  $domain,$username);
10670:           if ($returncode ne 'ok') {
10671:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10672:           } else {
10673:              $storecount++;
10674:           }
10675:        }
10676:     }
10677: # We are done
10678:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10679:              '</td>'.
10680:              &Apache::loncommon::end_data_table_row().
10681:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10682:     return $result.&show_grading_menu_form($symb);
10683: }
10684: 
10685: sub navmap_errormsg {
10686:     return '<div class="LC_error">'.
10687:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10688:            &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>').
10689:            '</div>';
10690: }
10691: 
10692: sub startpage {
10693:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10694:     if ($nomenu) {
10695:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10696:     } else {
10697:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10698:                                                  {'bread_crumbs' => $crumbs}));
10699:     }
10700:     unless ($nodisplayflag) {
10701:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10702:     }
10703: }
10704: 
10705: sub handler {
10706:     my $request=$_[0];
10707:     &reset_caches();
10708:     if ($request->header_only) {
10709:         &Apache::loncommon::content_type($request,'text/html');
10710:         $request->send_http_header;
10711:         return OK;
10712:     }
10713:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10714: 
10715:     my $symb=&get_symb($request,1);
10716:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10717:     my $command=$commands[0];
10718: 
10719:     if ($#commands > 0) {
10720: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10721:     }
10722: 
10723:     $ssi_error = 0;
10724:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10725:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10726:                                                     {'bread_crumbs' => $brcrum});
10727:     if ($symb eq '' && $command eq '') {
10728: 	if ($env{'user.adv'}) {
10729:             &Apache::loncommon::content_type($request,'text/html');
10730:             $request->send_http_header;
10731:             $request->print($start_page);
10732: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10733: 		($env{'form.codethree'})) {
10734: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10735: 		    $env{'form.codethree'};
10736: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10737: 		    &Apache::lonnet::checkin($token);
10738: 		if ($tsymb) {
10739: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10740: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10741: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10742: 					  ('grade_username' => $tuname,
10743: 					   'grade_domain' => $tudom,
10744: 					   'grade_courseid' => $tcrsid,
10745: 					   'grade_symb' => $tsymb)));
10746: 		    } else {
10747: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10748: 		    }
10749: 		} else {
10750: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10751: 		}
10752: 	    } else {
10753: 		$request->print(&Apache::lonxml::tokeninputfield());
10754: 	    }
10755:         } elsif ($env{'request.course.id'}) {
10756:             &init_perm(); 
10757:             if (!%perm) {
10758:                 $request->internal_redirect('/adm/quickgrades');
10759:                 return OK;
10760:             } else {
10761:                 &Apache::loncommon::content_type($request,'text/html');
10762:                 $request->send_http_header;
10763:                 $request->print($start_page);
10764:             }
10765:         }
10766:     } else {
10767:         &init_perm();
10768:         if (!$env{'request.course.id'}) {
10769:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10770:                     ($command =~ /^scantronupload/)) {
10771:                 # Not in a course.
10772:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10773:                 return HTTP_NOT_ACCEPTABLE;
10774:             }
10775:         } elsif (!%perm) {
10776:             $request->internal_redirect('/adm/quickgrades');
10777:         }
10778:         &Apache::loncommon::content_type($request,'text/html');
10779:         $request->send_http_header;
10780:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10781:             $request->print($start_page); 
10782:         }
10783: 	if ($command eq 'submission' && $perm{'vgr'}) {
10784:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10785:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10786:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10787:                     &choose_task_version_form($symb,$env{'form.student'},
10788:                                               $env{'form.userdom'});
10789:             }
10790:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10791:             if ($versionform) {
10792:                 $request->print($versionform);
10793:             }
10794:             $request->print('<br clear="all" />');
10795: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10796:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10797:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10798:                 &choose_task_version_form($symb,$env{'form.student'},
10799:                                           $env{'form.userdom'},
10800:                                           $env{'form.inhibitmenu'});
10801:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10802:             if ($versionform) {
10803:                 $request->print($versionform);
10804:             }
10805:             $request->print('<br clear="all" />');
10806:             $request->print(&show_previous_task_version($request,$symb));
10807: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10808: 	    &pickStudentPage($request);
10809: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10810: 	    &displayPage($request);
10811: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10812: 	    &updateGradeByPage($request);
10813: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10814: 	    &processGroup($request);
10815: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10816: 	    $request->print(&grading_menu($request));
10817: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10818: 	    $request->print(&submit_options($request));
10819: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10820: 	    $request->print(&viewgrades($request));
10821: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10822: 	    $request->print(&processHandGrade($request));
10823: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10824: 	    $request->print(&editgrades($request));
10825: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10826: 	    $request->print(&verifyreceipt($request));
10827:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10828:             $request->print(&process_clicker($request));
10829:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10830:             $request->print(&process_clicker_file($request));
10831:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10832:             $request->print(&assign_clicker_grades($request));
10833: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10834: 	    $request->print(&upcsvScores_form($request));
10835: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10836: 	    $request->print(&csvupload($request));
10837: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10838: 	    $request->print(&csvuploadmap($request));
10839: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10840: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10841: 		$request->print(&csvuploadoptions($request));
10842: 	    } else {
10843: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10844: 		    $env{'form.upfile_associate'} = 'reverse';
10845: 		} else {
10846: 		    $env{'form.upfile_associate'} = 'forward';
10847: 		}
10848: 		$request->print(&csvuploadmap($request));
10849: 	    }
10850: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10851: 	    $request->print(&csvuploadassign($request));
10852: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10853: 	    $request->print(&scantron_selectphase($request));
10854:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10855:  	    $request->print(&scantron_do_warning($request));
10856: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10857: 	    $request->print(&scantron_validate_file($request));
10858: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10859: 	    $request->print(&scantron_process_students($request));
10860:  	} elsif ($command eq 'scantronupload' && 
10861:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10862: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10863:  	    $request->print(&scantron_upload_scantron_data($request)); 
10864:  	} elsif ($command eq 'scantronupload_save' &&
10865:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10866: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10867:  	    $request->print(&scantron_upload_scantron_data_save($request));
10868:  	} elsif ($command eq 'scantron_download' &&
10869: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10870:  	    $request->print(&scantron_download_scantron_data($request));
10871:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10872:             $request->print(&checkscantron_results($request));     
10873: 	} elsif ($command) {
10874: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10875: 	}
10876:     }
10877:     if ($ssi_error) {
10878: 	&ssi_print_error($request);
10879:     }
10880:     $request->print(&Apache::loncommon::end_page());
10881:     &reset_caches();
10882:     return OK;
10883: }
10884: 
10885: 1;
10886: 
10887: __END__;
10888: 
10889: 
10890: =head1 NAME
10891: 
10892: Apache::grades
10893: 
10894: =head1 SYNOPSIS
10895: 
10896: Handles the viewing of grades.
10897: 
10898: This is part of the LearningOnline Network with CAPA project
10899: described at http://www.lon-capa.org.
10900: 
10901: =head1 OVERVIEW
10902: 
10903: Do an ssi with retries:
10904: While I'd love to factor out this with the vesrion in lonprintout,
10905: 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
10906: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10907: 
10908: At least the logic that drives this has been pulled out into loncommon.
10909: 
10910: 
10911: 
10912: ssi_with_retries - Does the server side include of a resource.
10913:                      if the ssi call returns an error we'll retry it up to
10914:                      the number of times requested by the caller.
10915:                      If we still have a problem, no text is appended to the
10916:                      output and we set some global variables.
10917:                      to indicate to the caller an SSI error occurred.  
10918:                      All of this is supposed to deal with the issues described
10919:                      in LON-CAPA BZ 5631 see:
10920:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10921:                      by informing the user that this happened.
10922: 
10923: Parameters:
10924:   resource   - The resource to include.  This is passed directly, without
10925:                interpretation to lonnet::ssi.
10926:   form       - The form hash parameters that guide the interpretation of the resource
10927:                
10928:   retries    - Number of retries allowed before giving up completely.
10929: Returns:
10930:   On success, returns the rendered resource identified by the resource parameter.
10931: Side Effects:
10932:   The following global variables can be set:
10933:    ssi_error                - If an unrecoverable error occurred this becomes true.
10934:                               It is up to the caller to initialize this to false
10935:                               if desired.
10936:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10937:                               of the resource that could not be rendered by the ssi
10938:                               call.
10939:    ssi_error_message   - The error string fetched from the ssi response
10940:                               in the event of an error.
10941: 
10942: 
10943: =head1 HANDLER SUBROUTINE
10944: 
10945: ssi_with_retries()
10946: 
10947: =head1 SUBROUTINES
10948: 
10949: =over
10950: 
10951: =item scantron_get_correction() : 
10952: 
10953:    Builds the interface screen to interact with the operator to fix a
10954:    specific error condition in a specific scanline
10955: 
10956:  Arguments:
10957:     $r           - Apache request object
10958:     $i           - number of the current scanline
10959:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10960:     $scan_config - hash ref as returned from &get_scantron_config()
10961:     $line        - full contents of the current scanline
10962:     $error       - error condition, valid values are
10963:                    'incorrectCODE', 'duplicateCODE',
10964:                    'doublebubble', 'missingbubble',
10965:                    'duplicateID', 'incorrectID'
10966:     $arg         - extra information needed
10967:        For errors:
10968:          - duplicateID   - paper number that this studentID was seen before on
10969:          - duplicateCODE - array ref of the paper numbers this CODE was
10970:                            seen on before
10971:          - incorrectCODE - current incorrect CODE 
10972:          - doublebubble  - array ref of the bubble lines that have double
10973:                            bubble errors
10974:          - missingbubble - array ref of the bubble lines that have missing
10975:                            bubble errors
10976: 
10977:    $randomorder - True if exam folder has randomorder set
10978:    $randompick  - True if exam folder has randompick set
10979:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10980:                      for current line to question number used for same question
10981:                      in "Master Seqence" (as seen by Course Coordinator).
10982:    $startline   - Reference to hash where key is question number (0 is first)
10983:                   and value is number of first bubble line for current student
10984:                   or code-based randompick and/or randomorder.
10985: 
10986: 
10987: =item  scantron_get_maxbubble() : 
10988: 
10989:    Arguments:
10990:        $nav_error  - Reference to scalar which is a flag to indicate a
10991:                       failure to retrieve a navmap object.
10992:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10993:        calling routine should trap the error condition and display the warning
10994:        found in &navmap_errormsg().
10995: 
10996:        $scantron_config - Reference to bubblesheet format configuration hash.
10997: 
10998:    Returns the maximum number of bubble lines that are expected to
10999:    occur. Does this by walking the selected sequence rendering the
11000:    resource and then checking &Apache::lonxml::get_problem_counter()
11001:    for what the current value of the problem counter is.
11002: 
11003:    Caches the results to $env{'form.scantron_maxbubble'},
11004:    $env{'form.scantron.bubble_lines.n'}, 
11005:    $env{'form.scantron.first_bubble_line.n'} and
11006:    $env{"form.scantron.sub_bubblelines.n"}
11007:    which are the total number of bubble lines, the number of bubble
11008:    lines for response n and number of the first bubble line for response n,
11009:    and a comma separated list of numbers of bubble lines for sub-questions
11010:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11011: 
11012: 
11013: =item  scantron_validate_missingbubbles() : 
11014: 
11015:    Validates all scanlines in the selected file to not have any
11016:     answers that don't have bubbles that have not been verified
11017:     to be bubble free.
11018: 
11019: =item  scantron_process_students() : 
11020: 
11021:    Routine that does the actual grading of the bubblesheet information.
11022: 
11023:    The parsed scanline hash is added to %env 
11024: 
11025:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11026:    foreach resource , with the form data of
11027: 
11028: 	'submitted'     =>'scantron' 
11029: 	'grade_target'  =>'grade',
11030: 	'grade_username'=> username of student
11031: 	'grade_domain'  => domain of student
11032: 	'grade_courseid'=> of course
11033: 	'grade_symb'    => symb of resource to grade
11034: 
11035:     This triggers a grading pass. The problem grading code takes care
11036:     of converting the bubbled letter information (now in %env) into a
11037:     valid submission.
11038: 
11039: =item  scantron_upload_scantron_data() :
11040: 
11041:     Creates the screen for adding a new bubblesheet data file to a course.
11042: 
11043: =item  scantron_upload_scantron_data_save() : 
11044: 
11045:    Adds a provided bubble information data file to the course if user
11046:    has the correct privileges to do so. 
11047: 
11048: =item  valid_file() :
11049: 
11050:    Validates that the requested bubble data file exists in the course.
11051: 
11052: =item  scantron_download_scantron_data() : 
11053: 
11054:    Shows a list of the three internal files (original, corrected,
11055:    skipped) for a specific bubblesheet data file that exists in the
11056:    course.
11057: 
11058: =item  scantron_validate_ID() : 
11059: 
11060:    Validates all scanlines in the selected file to not have any
11061:    invalid or underspecified student/employee IDs
11062: 
11063: =item navmap_errormsg() :
11064: 
11065:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11066:    Should be called whenever the request to instantiate a navmap object fails.  
11067: 
11068: =back
11069: 
11070: =cut

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